test.cc 336 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927
  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 <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1092. auto host = "unresolvableaddress.local";
  1093. auto path = std::string{"/"};
  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(1);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_FALSE(res);
  1105. }
  1106. std::this_thread::sleep_for(std::chrono::seconds(8));
  1107. }
  1108. TEST(ConnectionErrorTest, InvalidHost) {
  1109. auto host = "-abcde.com";
  1110. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1111. auto port = 443;
  1112. SSLClient cli(host, port);
  1113. #else
  1114. auto port = 80;
  1115. Client cli(host, port);
  1116. #endif
  1117. cli.set_connection_timeout(std::chrono::seconds(2));
  1118. auto res = cli.Get("/");
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Connection, res.error());
  1121. }
  1122. TEST(ConnectionErrorTest, InvalidHost2) {
  1123. auto host = "httpbin.org/";
  1124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1125. SSLClient cli(host);
  1126. #else
  1127. Client cli(host);
  1128. #endif
  1129. cli.set_connection_timeout(std::chrono::seconds(2));
  1130. auto res = cli.Get("/");
  1131. ASSERT_TRUE(!res);
  1132. EXPECT_EQ(Error::Connection, res.error());
  1133. }
  1134. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1135. auto host = "httpbin.org/";
  1136. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1137. SSLClient cli(host);
  1138. #else
  1139. Client cli(host);
  1140. #endif
  1141. cli.set_connection_timeout(std::chrono::seconds(2));
  1142. auto res = cli.Get("/");
  1143. ASSERT_TRUE(!res);
  1144. stringstream s;
  1145. s << "error code: " << res.error();
  1146. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1147. }
  1148. TEST(ConnectionErrorTest, InvalidPort) {
  1149. auto host = "localhost";
  1150. auto port = 44380;
  1151. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1152. SSLClient cli(host, port);
  1153. #else
  1154. Client cli(host, port);
  1155. #endif
  1156. cli.set_connection_timeout(std::chrono::seconds(2));
  1157. auto res = cli.Get("/");
  1158. ASSERT_TRUE(!res);
  1159. EXPECT_TRUE(Error::Connection == res.error() ||
  1160. Error::ConnectionTimeout == res.error());
  1161. }
  1162. TEST(ConnectionErrorTest, Timeout_Online) {
  1163. auto host = "google.com";
  1164. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1165. auto port = 44380;
  1166. SSLClient cli(host, port);
  1167. #else
  1168. auto port = 8080;
  1169. Client cli(host, port);
  1170. #endif
  1171. cli.set_connection_timeout(std::chrono::seconds(2));
  1172. // only probe one address type so that the error reason
  1173. // correlates to the timed-out IPv4, not the unsupported
  1174. // IPv6 connection attempt
  1175. cli.set_address_family(AF_INET);
  1176. auto res = cli.Get("/");
  1177. ASSERT_TRUE(!res);
  1178. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1179. }
  1180. TEST(CancelTest, NoCancel_Online) {
  1181. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1182. auto host = "httpbin.org";
  1183. auto path = std::string{"/range/32"};
  1184. #else
  1185. auto host = "nghttp2.org";
  1186. auto path = std::string{"/httpbin/range/32"};
  1187. #endif
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. auto port = 443;
  1190. SSLClient cli(host, port);
  1191. #else
  1192. auto port = 80;
  1193. Client cli(host, port);
  1194. #endif
  1195. cli.set_connection_timeout(std::chrono::seconds(5));
  1196. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1197. ASSERT_TRUE(res);
  1198. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1199. EXPECT_EQ(StatusCode::OK_200, res->status);
  1200. }
  1201. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1202. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1203. auto host = "httpbin.org";
  1204. auto path = std::string{"/range/32"};
  1205. #else
  1206. auto host = "nghttp2.org";
  1207. auto path = std::string{"/httpbin/range/32"};
  1208. #endif
  1209. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1210. auto port = 443;
  1211. SSLClient cli(host, port);
  1212. #else
  1213. auto port = 80;
  1214. Client cli(host, port);
  1215. #endif
  1216. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1217. cli.set_connection_timeout(std::chrono::seconds(5));
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Canceled, res.error());
  1220. }
  1221. TEST(CancelTest, WithCancelLargePayload_Online) {
  1222. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1223. auto host = "httpbin.org";
  1224. auto path = std::string{"/range/65536"};
  1225. #else
  1226. auto host = "nghttp2.org";
  1227. auto path = std::string{"/httpbin/range/65536"};
  1228. #endif
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. auto port = 443;
  1231. SSLClient cli(host, port);
  1232. #else
  1233. auto port = 80;
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(5));
  1237. uint32_t count = 0;
  1238. auto res =
  1239. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1240. ASSERT_TRUE(!res);
  1241. EXPECT_EQ(Error::Canceled, res.error());
  1242. }
  1243. TEST(CancelTest, NoCancelPost) {
  1244. Server svr;
  1245. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1246. res.set_content("Hello World!", "text/plain");
  1247. });
  1248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1249. auto se = detail::scope_exit([&] {
  1250. svr.stop();
  1251. thread.join();
  1252. ASSERT_FALSE(svr.is_running());
  1253. });
  1254. svr.wait_until_ready();
  1255. Client cli(HOST, PORT);
  1256. cli.set_connection_timeout(std::chrono::seconds(5));
  1257. auto res =
  1258. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1259. "application/json", [](uint64_t, uint64_t) { return true; });
  1260. ASSERT_TRUE(res);
  1261. EXPECT_EQ("Hello World!", res->body);
  1262. EXPECT_EQ(StatusCode::OK_200, res->status);
  1263. }
  1264. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1265. Server svr;
  1266. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return false; });
  1281. ASSERT_TRUE(!res);
  1282. EXPECT_EQ(Error::Canceled, res.error());
  1283. }
  1284. TEST(CancelTest, WithCancelLargePayloadPost) {
  1285. Server svr;
  1286. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1287. res.set_content(LARGE_DATA, "text/plain");
  1288. });
  1289. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1290. auto se = detail::scope_exit([&] {
  1291. svr.stop();
  1292. thread.join();
  1293. ASSERT_FALSE(svr.is_running());
  1294. });
  1295. svr.wait_until_ready();
  1296. Client cli(HOST, PORT);
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. auto res =
  1299. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1300. "application/json", [](uint64_t, uint64_t) { return false; });
  1301. ASSERT_TRUE(!res);
  1302. EXPECT_EQ(Error::Canceled, res.error());
  1303. }
  1304. TEST(CancelTest, NoCancelPut) {
  1305. Server svr;
  1306. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1307. res.set_content("Hello World!", "text/plain");
  1308. });
  1309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1310. auto se = detail::scope_exit([&] {
  1311. svr.stop();
  1312. thread.join();
  1313. ASSERT_FALSE(svr.is_running());
  1314. });
  1315. svr.wait_until_ready();
  1316. Client cli(HOST, PORT);
  1317. cli.set_connection_timeout(std::chrono::seconds(5));
  1318. auto res =
  1319. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1320. "application/json", [](uint64_t, uint64_t) { return true; });
  1321. ASSERT_TRUE(res);
  1322. EXPECT_EQ("Hello World!", res->body);
  1323. EXPECT_EQ(StatusCode::OK_200, res->status);
  1324. }
  1325. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1326. Server svr;
  1327. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1328. res.set_content("Hello World!", "text/plain");
  1329. });
  1330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1331. auto se = detail::scope_exit([&] {
  1332. svr.stop();
  1333. thread.join();
  1334. ASSERT_FALSE(svr.is_running());
  1335. });
  1336. svr.wait_until_ready();
  1337. Client cli(HOST, PORT);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res =
  1340. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1341. "application/json", [](uint64_t, uint64_t) { return false; });
  1342. ASSERT_TRUE(!res);
  1343. EXPECT_EQ(Error::Canceled, res.error());
  1344. }
  1345. TEST(CancelTest, WithCancelLargePayloadPut) {
  1346. Server svr;
  1347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1348. res.set_content(LARGE_DATA, "text/plain");
  1349. });
  1350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1351. auto se = detail::scope_exit([&] {
  1352. svr.stop();
  1353. thread.join();
  1354. ASSERT_FALSE(svr.is_running());
  1355. });
  1356. svr.wait_until_ready();
  1357. Client cli(HOST, PORT);
  1358. cli.set_connection_timeout(std::chrono::seconds(5));
  1359. auto res =
  1360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1361. "application/json", [](uint64_t, uint64_t) { return false; });
  1362. ASSERT_TRUE(!res);
  1363. EXPECT_EQ(Error::Canceled, res.error());
  1364. }
  1365. TEST(CancelTest, NoCancelPatch) {
  1366. Server svr;
  1367. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1368. res.set_content("Hello World!", "text/plain");
  1369. });
  1370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1371. auto se = detail::scope_exit([&] {
  1372. svr.stop();
  1373. thread.join();
  1374. ASSERT_FALSE(svr.is_running());
  1375. });
  1376. svr.wait_until_ready();
  1377. Client cli(HOST, PORT);
  1378. cli.set_connection_timeout(std::chrono::seconds(5));
  1379. auto res =
  1380. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1381. "application/json", [](uint64_t, uint64_t) { return true; });
  1382. ASSERT_TRUE(res);
  1383. EXPECT_EQ("Hello World!", res->body);
  1384. EXPECT_EQ(StatusCode::OK_200, res->status);
  1385. }
  1386. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1387. Server svr;
  1388. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1389. res.set_content("Hello World!", "text/plain");
  1390. });
  1391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1392. auto se = detail::scope_exit([&] {
  1393. svr.stop();
  1394. thread.join();
  1395. ASSERT_FALSE(svr.is_running());
  1396. });
  1397. svr.wait_until_ready();
  1398. Client cli(HOST, PORT);
  1399. cli.set_connection_timeout(std::chrono::seconds(5));
  1400. auto res =
  1401. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1402. "application/json", [](uint64_t, uint64_t) { return false; });
  1403. ASSERT_TRUE(!res);
  1404. EXPECT_EQ(Error::Canceled, res.error());
  1405. }
  1406. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1407. Server svr;
  1408. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1409. res.set_content(LARGE_DATA, "text/plain");
  1410. });
  1411. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1412. auto se = detail::scope_exit([&] {
  1413. svr.stop();
  1414. thread.join();
  1415. ASSERT_FALSE(svr.is_running());
  1416. });
  1417. svr.wait_until_ready();
  1418. Client cli(HOST, PORT);
  1419. cli.set_connection_timeout(std::chrono::seconds(5));
  1420. auto res =
  1421. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1422. "application/json", [](uint64_t, uint64_t) { return false; });
  1423. ASSERT_TRUE(!res);
  1424. EXPECT_EQ(Error::Canceled, res.error());
  1425. }
  1426. TEST(CancelTest, NoCancelDelete) {
  1427. Server svr;
  1428. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1429. res.set_content("Hello World!", "text/plain");
  1430. });
  1431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. thread.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. Client cli(HOST, PORT);
  1439. cli.set_connection_timeout(std::chrono::seconds(5));
  1440. auto res =
  1441. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1442. "application/json", [](uint64_t, uint64_t) { return true; });
  1443. ASSERT_TRUE(res);
  1444. EXPECT_EQ("Hello World!", res->body);
  1445. EXPECT_EQ(StatusCode::OK_200, res->status);
  1446. }
  1447. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1448. Server svr;
  1449. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1450. res.set_content("Hello World!", "text/plain");
  1451. });
  1452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1453. auto se = detail::scope_exit([&] {
  1454. svr.stop();
  1455. thread.join();
  1456. ASSERT_FALSE(svr.is_running());
  1457. });
  1458. svr.wait_until_ready();
  1459. Client cli(HOST, PORT);
  1460. cli.set_connection_timeout(std::chrono::seconds(5));
  1461. auto res =
  1462. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1463. "application/json", [](uint64_t, uint64_t) { return false; });
  1464. ASSERT_TRUE(!res);
  1465. EXPECT_EQ(Error::Canceled, res.error());
  1466. }
  1467. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1468. Server svr;
  1469. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1470. res.set_content(LARGE_DATA, "text/plain");
  1471. });
  1472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1473. auto se = detail::scope_exit([&] {
  1474. svr.stop();
  1475. thread.join();
  1476. ASSERT_FALSE(svr.is_running());
  1477. });
  1478. svr.wait_until_ready();
  1479. Client cli(HOST, PORT);
  1480. cli.set_connection_timeout(std::chrono::seconds(5));
  1481. auto res =
  1482. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1483. "application/json", [](uint64_t, uint64_t) { return false; });
  1484. ASSERT_TRUE(!res);
  1485. EXPECT_EQ(Error::Canceled, res.error());
  1486. }
  1487. static std::string remove_whitespace(const std::string &input) {
  1488. std::string output;
  1489. output.reserve(input.size());
  1490. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1491. [](unsigned char c) { return !std::isspace(c); });
  1492. return output;
  1493. }
  1494. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1495. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1496. auto host = "httpbin.org";
  1497. auto path = std::string{"/basic-auth/hello/world"};
  1498. #else
  1499. auto host = "nghttp2.org";
  1500. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1501. #endif
  1502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1503. auto port = 443;
  1504. SSLClient cli(host, port);
  1505. #else
  1506. auto port = 80;
  1507. Client cli(host, port);
  1508. #endif
  1509. {
  1510. auto res = cli.Get(path);
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1513. }
  1514. {
  1515. auto res =
  1516. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1517. ASSERT_TRUE(res);
  1518. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1519. remove_whitespace(res->body));
  1520. EXPECT_EQ(StatusCode::OK_200, res->status);
  1521. }
  1522. {
  1523. cli.set_basic_auth("hello", "world");
  1524. auto res = cli.Get(path);
  1525. ASSERT_TRUE(res);
  1526. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1527. remove_whitespace(res->body));
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. }
  1530. {
  1531. cli.set_basic_auth("hello", "bad");
  1532. auto res = cli.Get(path);
  1533. ASSERT_TRUE(res);
  1534. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1535. }
  1536. {
  1537. cli.set_basic_auth("bad", "world");
  1538. auto res = cli.Get(path);
  1539. ASSERT_TRUE(res);
  1540. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1541. }
  1542. }
  1543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1544. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1545. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1546. auto host = "httpbin.org";
  1547. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1548. auto paths = std::vector<std::string>{
  1549. "/digest-auth/auth/hello/world/MD5",
  1550. "/digest-auth/auth/hello/world/SHA-256",
  1551. "/digest-auth/auth/hello/world/SHA-512",
  1552. "/digest-auth/auth-int/hello/world/MD5",
  1553. };
  1554. #else
  1555. auto host = "nghttp2.org";
  1556. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1557. auto paths = std::vector<std::string>{
  1558. "/httpbin/digest-auth/auth/hello/world/MD5",
  1559. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1560. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1561. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1562. };
  1563. #endif
  1564. auto port = 443;
  1565. SSLClient cli(host, port);
  1566. {
  1567. auto res = cli.Get(unauth_path);
  1568. ASSERT_TRUE(res);
  1569. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1570. }
  1571. {
  1572. cli.set_digest_auth("hello", "world");
  1573. for (const auto &path : paths) {
  1574. auto res = cli.Get(path.c_str());
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1577. remove_whitespace(res->body));
  1578. EXPECT_EQ(StatusCode::OK_200, res->status);
  1579. }
  1580. cli.set_digest_auth("hello", "bad");
  1581. for (const auto &path : paths) {
  1582. auto res = cli.Get(path.c_str());
  1583. ASSERT_TRUE(res);
  1584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1585. }
  1586. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1587. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1588. // cli.set_digest_auth("bad", "world");
  1589. // for (const auto& path : paths) {
  1590. // auto res = cli.Get(path.c_str());
  1591. // ASSERT_TRUE(res);
  1592. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1593. // }
  1594. }
  1595. }
  1596. #endif
  1597. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1598. auto host = "google.com";
  1599. auto another_host = "example.com";
  1600. auto wrong_ip = "0.0.0.0";
  1601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1602. SSLClient cli(host);
  1603. #else
  1604. Client cli(host);
  1605. #endif
  1606. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1607. auto res = cli.Get("/");
  1608. ASSERT_TRUE(res);
  1609. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1610. }
  1611. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1612. auto host = "google.com";
  1613. auto wrong_ip = "0.0.0.0";
  1614. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1615. SSLClient cli(host);
  1616. #else
  1617. Client cli(host);
  1618. #endif
  1619. cli.set_hostname_addr_map({{host, wrong_ip}});
  1620. auto res = cli.Get("/");
  1621. ASSERT_TRUE(!res);
  1622. EXPECT_EQ(Error::Connection, res.error());
  1623. }
  1624. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1625. auto host = "nghttp2.org";
  1626. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1627. SSLClient cli(host);
  1628. #else
  1629. Client cli(host);
  1630. #endif
  1631. cli.set_follow_location(true);
  1632. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1633. ASSERT_TRUE(res);
  1634. EXPECT_EQ(StatusCode::OK_200, res->status);
  1635. }
  1636. TEST(RedirectTest, Redirect_Online) {
  1637. auto host = "nghttp2.org";
  1638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1639. SSLClient cli(host);
  1640. #else
  1641. Client cli(host);
  1642. #endif
  1643. cli.set_follow_location(true);
  1644. auto res = cli.Get("/httpbin/redirect/3");
  1645. ASSERT_TRUE(res);
  1646. EXPECT_EQ(StatusCode::OK_200, res->status);
  1647. }
  1648. TEST(RelativeRedirectTest, Redirect_Online) {
  1649. auto host = "nghttp2.org";
  1650. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1651. SSLClient cli(host);
  1652. #else
  1653. Client cli(host);
  1654. #endif
  1655. cli.set_follow_location(true);
  1656. auto res = cli.Get("/httpbin/relative-redirect/3");
  1657. ASSERT_TRUE(res);
  1658. EXPECT_EQ(StatusCode::OK_200, res->status);
  1659. }
  1660. TEST(TooManyRedirectTest, Redirect_Online) {
  1661. auto host = "nghttp2.org";
  1662. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1663. SSLClient cli(host);
  1664. #else
  1665. Client cli(host);
  1666. #endif
  1667. cli.set_follow_location(true);
  1668. auto res = cli.Get("/httpbin/redirect/21");
  1669. ASSERT_TRUE(!res);
  1670. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1671. }
  1672. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1673. TEST(YahooRedirectTest, Redirect_Online) {
  1674. Client cli("yahoo.com");
  1675. auto res = cli.Get("/");
  1676. ASSERT_TRUE(res);
  1677. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1678. cli.set_follow_location(true);
  1679. res = cli.Get("/");
  1680. ASSERT_TRUE(res);
  1681. EXPECT_EQ(StatusCode::OK_200, res->status);
  1682. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1683. }
  1684. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1685. #define REDIR_HOST "httpbingo.org"
  1686. #define REDIR_PATH "/redirect-to"
  1687. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1688. SSLClient cli(REDIR_HOST);
  1689. cli.set_follow_location(true);
  1690. auto res =
  1691. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1692. ASSERT_TRUE(res);
  1693. EXPECT_EQ(StatusCode::OK_200, res->status);
  1694. }
  1695. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1696. SSLClient cli(REDIR_HOST);
  1697. cli.set_follow_location(true);
  1698. Params params;
  1699. params.emplace("url", "http://example.com");
  1700. params.emplace("status_code", "302");
  1701. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1702. ASSERT_TRUE(res);
  1703. EXPECT_EQ(StatusCode::OK_200, res->status);
  1704. }
  1705. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1706. SSLClient cli(REDIR_HOST);
  1707. cli.set_follow_location(true);
  1708. Params params;
  1709. params.emplace("url", "http://example.com");
  1710. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1711. ASSERT_TRUE(res);
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. }
  1714. TEST(UrlWithSpace, Redirect_Online) {
  1715. SSLClient cli("edge.forgecdn.net");
  1716. cli.set_follow_location(true);
  1717. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1721. }
  1722. #endif
  1723. #if !defined(_WIN32) && !defined(_WIN64)
  1724. TEST(ReceiveSignals, Signal) {
  1725. auto setupSignalHandlers = []() {
  1726. struct sigaction act;
  1727. sigemptyset(&act.sa_mask);
  1728. act.sa_flags = SA_SIGINFO;
  1729. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1730. switch (sig) {
  1731. case SIGINT:
  1732. default: break;
  1733. }
  1734. };
  1735. ::sigaction(SIGINT, &act, nullptr);
  1736. };
  1737. Server svr;
  1738. int port = 0;
  1739. auto thread = std::thread([&]() {
  1740. setupSignalHandlers();
  1741. port = svr.bind_to_any_port("localhost");
  1742. svr.listen_after_bind();
  1743. });
  1744. auto se = detail::scope_exit([&] {
  1745. svr.stop();
  1746. thread.join();
  1747. ASSERT_FALSE(svr.is_running());
  1748. });
  1749. svr.wait_until_ready();
  1750. ASSERT_TRUE(svr.is_running());
  1751. pthread_kill(thread.native_handle(), SIGINT);
  1752. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1753. ASSERT_TRUE(svr.is_running());
  1754. }
  1755. #endif
  1756. TEST(RedirectToDifferentPort, Redirect) {
  1757. Server svr1;
  1758. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1759. res.set_content("Hello World!", "text/plain");
  1760. });
  1761. int svr1_port = 0;
  1762. auto thread1 = std::thread([&]() {
  1763. svr1_port = svr1.bind_to_any_port("localhost");
  1764. svr1.listen_after_bind();
  1765. });
  1766. Server svr2;
  1767. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1768. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1769. });
  1770. int svr2_port = 0;
  1771. auto thread2 = std::thread([&]() {
  1772. svr2_port = svr2.bind_to_any_port("localhost");
  1773. svr2.listen_after_bind();
  1774. });
  1775. auto se = detail::scope_exit([&] {
  1776. svr2.stop();
  1777. thread2.join();
  1778. svr1.stop();
  1779. thread1.join();
  1780. ASSERT_FALSE(svr2.is_running());
  1781. ASSERT_FALSE(svr1.is_running());
  1782. });
  1783. svr1.wait_until_ready();
  1784. svr2.wait_until_ready();
  1785. Client cli("localhost", svr2_port);
  1786. cli.set_follow_location(true);
  1787. auto res = cli.Get("/2");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. TEST(RedirectFromPageWithContent, Redirect) {
  1793. Server svr;
  1794. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1795. res.set_content("___", "text/plain");
  1796. res.set_redirect("/2");
  1797. });
  1798. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1799. res.set_content("Hello World!", "text/plain");
  1800. });
  1801. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1802. auto se = detail::scope_exit([&] {
  1803. svr.stop();
  1804. th.join();
  1805. ASSERT_FALSE(svr.is_running());
  1806. });
  1807. svr.wait_until_ready();
  1808. {
  1809. Client cli("localhost", PORT);
  1810. cli.set_follow_location(true);
  1811. std::string body;
  1812. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1813. body.append(data, data_length);
  1814. return true;
  1815. });
  1816. ASSERT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. EXPECT_EQ("Hello World!", body);
  1819. }
  1820. {
  1821. Client cli("localhost", PORT);
  1822. std::string body;
  1823. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1824. body.append(data, data_length);
  1825. return true;
  1826. });
  1827. ASSERT_TRUE(res);
  1828. EXPECT_EQ(StatusCode::Found_302, res->status);
  1829. EXPECT_EQ("___", body);
  1830. }
  1831. }
  1832. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1833. Server svr;
  1834. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1835. res.set_content("___", "text/plain");
  1836. // res.set_redirect("/2");
  1837. res.set_redirect("http://[::1]:1234/2");
  1838. });
  1839. svr.Get("/2", [&](const Request &req, Response &res) {
  1840. auto host_header = req.headers.find("Host");
  1841. ASSERT_TRUE(host_header != req.headers.end());
  1842. EXPECT_EQ("[::1]:1234", host_header->second);
  1843. res.set_content("Hello World!", "text/plain");
  1844. });
  1845. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1846. auto se = detail::scope_exit([&] {
  1847. svr.stop();
  1848. th.join();
  1849. ASSERT_FALSE(svr.is_running());
  1850. });
  1851. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1852. // actually starts anything, so the condition !svr.is_running() will
  1853. // always remain true, and the loop never stops.
  1854. // This basically counts how many milliseconds have passed since the
  1855. // call to svr.listen(), and if after 5 seconds nothing started yet
  1856. // aborts the test.
  1857. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1858. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1859. ASSERT_LT(milliseconds, 5000U);
  1860. }
  1861. {
  1862. Client cli("http://[::1]:1234");
  1863. cli.set_follow_location(true);
  1864. std::string body;
  1865. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1866. body.append(data, data_length);
  1867. return true;
  1868. });
  1869. ASSERT_TRUE(res);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. EXPECT_EQ("Hello World!", body);
  1872. }
  1873. {
  1874. Client cli("http://[::1]:1234");
  1875. std::string body;
  1876. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1877. body.append(data, data_length);
  1878. return true;
  1879. });
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::Found_302, res->status);
  1882. EXPECT_EQ("___", body);
  1883. }
  1884. }
  1885. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1886. Server svr;
  1887. svr.Get("/foo", [](const Request &req, Response &res) {
  1888. auto a = req.params.find("a");
  1889. if (a != req.params.end()) {
  1890. res.set_content((*a).second, "text/plain");
  1891. res.status = StatusCode::OK_200;
  1892. } else {
  1893. res.status = StatusCode::BadRequest_400;
  1894. }
  1895. });
  1896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1897. auto se = detail::scope_exit([&] {
  1898. svr.stop();
  1899. thread.join();
  1900. ASSERT_FALSE(svr.is_running());
  1901. });
  1902. svr.wait_until_ready();
  1903. {
  1904. Client cli(HOST, PORT);
  1905. cli.set_path_encode(false);
  1906. auto res = cli.Get("/foo?a=explicitly+encoded");
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::OK_200, res->status);
  1909. // This expects it back with a space, as the `+` won't have been
  1910. // url-encoded, and server-side the params get decoded turning `+`
  1911. // into spaces.
  1912. EXPECT_EQ("explicitly encoded", res->body);
  1913. }
  1914. }
  1915. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1916. Server svr;
  1917. svr.Get("/", [](const Request &req, Response &) {
  1918. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. {
  1928. Client cli(HOST, PORT);
  1929. cli.set_path_encode(false);
  1930. auto res = cli.Get("/?something=%0A");
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. }
  1934. }
  1935. TEST(BindServerTest, DISABLED_BindDualStack) {
  1936. Server svr;
  1937. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1938. res.set_content("Hello World!", "text/plain");
  1939. });
  1940. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1941. auto se = detail::scope_exit([&] {
  1942. svr.stop();
  1943. thread.join();
  1944. ASSERT_FALSE(svr.is_running());
  1945. });
  1946. svr.wait_until_ready();
  1947. {
  1948. Client cli("127.0.0.1", PORT);
  1949. auto res = cli.Get("/1");
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::OK_200, res->status);
  1952. EXPECT_EQ("Hello World!", res->body);
  1953. }
  1954. {
  1955. Client cli("::1", PORT);
  1956. auto res = cli.Get("/1");
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", res->body);
  1960. }
  1961. }
  1962. TEST(BindServerTest, BindAndListenSeparately) {
  1963. Server svr;
  1964. int port = svr.bind_to_any_port("0.0.0.0");
  1965. ASSERT_TRUE(svr.is_valid());
  1966. ASSERT_TRUE(port > 0);
  1967. svr.stop();
  1968. }
  1969. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1970. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1972. CLIENT_CA_CERT_DIR);
  1973. int port = svr.bind_to_any_port("0.0.0.0");
  1974. ASSERT_TRUE(svr.is_valid());
  1975. ASSERT_TRUE(port > 0);
  1976. svr.stop();
  1977. }
  1978. #endif
  1979. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1980. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1981. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1982. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1983. int port = svr.bind_to_any_port("0.0.0.0");
  1984. ASSERT_TRUE(svr.is_valid());
  1985. ASSERT_TRUE(port > 0);
  1986. svr.stop();
  1987. }
  1988. #endif
  1989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1990. X509 *readCertificate(const std::string &strFileName) {
  1991. std::ifstream inStream(strFileName);
  1992. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1993. std::istreambuf_iterator<char>());
  1994. if (strCertPEM.empty()) return (nullptr);
  1995. BIO *pbCert = BIO_new(BIO_s_mem());
  1996. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1997. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1998. BIO_free(pbCert);
  1999. return (pCert);
  2000. }
  2001. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2002. std::ifstream inStream(strFileName);
  2003. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2004. std::istreambuf_iterator<char>());
  2005. if (strPrivateKeyPEM.empty()) return (nullptr);
  2006. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2007. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2008. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2009. BIO_free(pbPrivKey);
  2010. return (pPrivateKey);
  2011. }
  2012. TEST(BindServerTest, UpdateCerts) {
  2013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2014. int port = svr.bind_to_any_port("0.0.0.0");
  2015. ASSERT_TRUE(svr.is_valid());
  2016. ASSERT_TRUE(port > 0);
  2017. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2018. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2019. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2020. ASSERT_TRUE(cert != nullptr);
  2021. ASSERT_TRUE(ca_cert != nullptr);
  2022. ASSERT_TRUE(key != nullptr);
  2023. X509_STORE *cert_store = X509_STORE_new();
  2024. X509_STORE_add_cert(cert_store, ca_cert);
  2025. svr.update_certs(cert, key, cert_store);
  2026. ASSERT_TRUE(svr.is_valid());
  2027. svr.stop();
  2028. X509_free(cert);
  2029. X509_free(ca_cert);
  2030. EVP_PKEY_free(key);
  2031. }
  2032. #endif
  2033. TEST(ErrorHandlerTest, ContentLength) {
  2034. Server svr;
  2035. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2036. res.status = StatusCode::OK_200;
  2037. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2038. "text/html"); // <= Content-Length still 13
  2039. });
  2040. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2041. res.set_content("Hello World!\n", "text/plain");
  2042. res.status = 524;
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. Client cli(HOST, PORT);
  2053. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2054. ASSERT_TRUE(res);
  2055. EXPECT_EQ(StatusCode::OK_200, res->status);
  2056. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2057. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2058. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2059. }
  2060. }
  2061. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2062. TEST(ExceptionTest, WithoutExceptionHandler) {
  2063. Server svr;
  2064. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2065. throw std::runtime_error("exception...");
  2066. });
  2067. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2068. throw std::runtime_error("exception\r\n...");
  2069. });
  2070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2071. auto se = detail::scope_exit([&] {
  2072. svr.stop();
  2073. listen_thread.join();
  2074. ASSERT_FALSE(svr.is_running());
  2075. });
  2076. svr.wait_until_ready();
  2077. Client cli("localhost", PORT);
  2078. {
  2079. auto res = cli.Get("/exception");
  2080. ASSERT_TRUE(res);
  2081. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2082. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2083. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2084. }
  2085. {
  2086. auto res = cli.Get("/unknown");
  2087. ASSERT_TRUE(res);
  2088. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2089. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2090. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2091. }
  2092. }
  2093. TEST(ExceptionTest, WithExceptionHandler) {
  2094. Server svr;
  2095. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2096. std::exception_ptr ep) {
  2097. EXPECT_FALSE(ep == nullptr);
  2098. try {
  2099. std::rethrow_exception(ep);
  2100. } catch (std::exception &e) {
  2101. EXPECT_EQ("abc", std::string(e.what()));
  2102. } catch (...) {}
  2103. res.status = StatusCode::InternalServerError_500;
  2104. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2105. "text/html"); // <= Content-Length still 13 at this point
  2106. });
  2107. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2108. res.set_content("Hello World!\n", "text/plain");
  2109. throw std::runtime_error("abc");
  2110. });
  2111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2112. auto se = detail::scope_exit([&] {
  2113. svr.stop();
  2114. thread.join();
  2115. ASSERT_FALSE(svr.is_running());
  2116. });
  2117. svr.wait_until_ready();
  2118. for (size_t i = 0; i < 10; i++) {
  2119. Client cli(HOST, PORT);
  2120. for (size_t j = 0; j < 100; j++) {
  2121. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2124. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2127. }
  2128. cli.set_keep_alive(true);
  2129. for (size_t j = 0; j < 100; j++) {
  2130. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2131. ASSERT_TRUE(res);
  2132. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2134. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2135. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2136. }
  2137. }
  2138. }
  2139. TEST(ExceptionTest, AndErrorHandler) {
  2140. Server svr;
  2141. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2142. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2143. });
  2144. svr.set_exception_handler(
  2145. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2146. EXPECT_FALSE(ep == nullptr);
  2147. try {
  2148. std::rethrow_exception(ep);
  2149. } catch (std::exception &e) {
  2150. res.set_content(e.what(), "text/html");
  2151. } catch (...) {}
  2152. res.status = StatusCode::InternalServerError_500;
  2153. });
  2154. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2155. throw std::runtime_error("EXCEPTION");
  2156. });
  2157. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2158. res.set_content("ERROR", "text/html");
  2159. res.status = StatusCode::InternalServerError_500;
  2160. });
  2161. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2162. auto se = detail::scope_exit([&] {
  2163. svr.stop();
  2164. thread.join();
  2165. ASSERT_FALSE(svr.is_running());
  2166. });
  2167. svr.wait_until_ready();
  2168. Client cli(HOST, PORT);
  2169. {
  2170. auto res = cli.Get("/exception");
  2171. ASSERT_TRUE(res);
  2172. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2173. EXPECT_EQ("EXCEPTION", res->body);
  2174. }
  2175. {
  2176. auto res = cli.Get("/error");
  2177. ASSERT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2179. EXPECT_EQ("ERROR", res->body);
  2180. }
  2181. {
  2182. auto res = cli.Get("/invalid");
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2185. EXPECT_EQ("NOT_FOUND", res->body);
  2186. }
  2187. }
  2188. #endif
  2189. TEST(NoContentTest, ContentLength) {
  2190. Server svr;
  2191. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2192. res.status = StatusCode::NoContent_204;
  2193. });
  2194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2195. auto se = detail::scope_exit([&] {
  2196. svr.stop();
  2197. thread.join();
  2198. ASSERT_FALSE(svr.is_running());
  2199. });
  2200. svr.wait_until_ready();
  2201. {
  2202. Client cli(HOST, PORT);
  2203. auto res = cli.Get("/hi");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2206. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2207. }
  2208. }
  2209. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2211. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2212. ASSERT_TRUE(svr.is_valid());
  2213. #else
  2214. Server svr;
  2215. #endif
  2216. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2217. if (req.path == "/routing_handler") {
  2218. res.set_header("PRE_ROUTING", "on");
  2219. res.set_content("Routing Handler", "text/plain");
  2220. return httplib::Server::HandlerResponse::Handled;
  2221. }
  2222. return httplib::Server::HandlerResponse::Unhandled;
  2223. });
  2224. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2225. res.set_content("Error", "text/html");
  2226. });
  2227. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2228. if (req.path == "/routing_handler") {
  2229. res.set_header("POST_ROUTING", "on");
  2230. }
  2231. });
  2232. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2233. res.set_content("Hello World!\n", "text/plain");
  2234. });
  2235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2236. auto se = detail::scope_exit([&] {
  2237. svr.stop();
  2238. thread.join();
  2239. ASSERT_FALSE(svr.is_running());
  2240. });
  2241. svr.wait_until_ready();
  2242. {
  2243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2244. SSLClient cli(HOST, PORT);
  2245. cli.enable_server_certificate_verification(false);
  2246. #else
  2247. Client cli(HOST, PORT);
  2248. #endif
  2249. auto res = cli.Get("/routing_handler");
  2250. ASSERT_TRUE(res);
  2251. EXPECT_EQ(StatusCode::OK_200, res->status);
  2252. EXPECT_EQ("Routing Handler", res->body);
  2253. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2254. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2255. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2256. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2257. }
  2258. {
  2259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2260. SSLClient cli(HOST, PORT);
  2261. cli.enable_server_certificate_verification(false);
  2262. #else
  2263. Client cli(HOST, PORT);
  2264. #endif
  2265. auto res = cli.Get("/hi");
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(StatusCode::OK_200, res->status);
  2268. EXPECT_EQ("Hello World!\n", res->body);
  2269. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2270. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2271. }
  2272. {
  2273. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2274. SSLClient cli(HOST, PORT);
  2275. cli.enable_server_certificate_verification(false);
  2276. #else
  2277. Client cli(HOST, PORT);
  2278. #endif
  2279. auto res = cli.Get("/aaa");
  2280. ASSERT_TRUE(res);
  2281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2282. EXPECT_EQ("Error", res->body);
  2283. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2284. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2285. }
  2286. }
  2287. TEST(RequestHandlerTest, PreRequestHandler) {
  2288. auto route_path = "/user/:user";
  2289. Server svr;
  2290. svr.Get("/hi", [](const Request &, Response &res) {
  2291. res.set_content("hi", "text/plain");
  2292. });
  2293. svr.Get(route_path, [](const Request &req, Response &res) {
  2294. res.set_content(req.path_params.at("user"), "text/plain");
  2295. });
  2296. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2297. if (req.matched_route == route_path) {
  2298. auto user = req.path_params.at("user");
  2299. if (user != "john") {
  2300. res.status = StatusCode::Forbidden_403;
  2301. res.set_content("error", "text/html");
  2302. return Server::HandlerResponse::Handled;
  2303. }
  2304. }
  2305. return Server::HandlerResponse::Unhandled;
  2306. });
  2307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2308. auto se = detail::scope_exit([&] {
  2309. svr.stop();
  2310. thread.join();
  2311. ASSERT_FALSE(svr.is_running());
  2312. });
  2313. svr.wait_until_ready();
  2314. Client cli(HOST, PORT);
  2315. {
  2316. auto res = cli.Get("/hi");
  2317. ASSERT_TRUE(res);
  2318. EXPECT_EQ(StatusCode::OK_200, res->status);
  2319. EXPECT_EQ("hi", res->body);
  2320. }
  2321. {
  2322. auto res = cli.Get("/user/john");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(StatusCode::OK_200, res->status);
  2325. EXPECT_EQ("john", res->body);
  2326. }
  2327. {
  2328. auto res = cli.Get("/user/invalid-user");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2331. EXPECT_EQ("error", res->body);
  2332. }
  2333. }
  2334. TEST(InvalidFormatTest, StatusCode) {
  2335. Server svr;
  2336. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!\n", "text/plain");
  2338. res.status = 9999; // Status should be a three-digit code...
  2339. });
  2340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2341. auto se = detail::scope_exit([&] {
  2342. svr.stop();
  2343. thread.join();
  2344. ASSERT_FALSE(svr.is_running());
  2345. });
  2346. svr.wait_until_ready();
  2347. {
  2348. Client cli(HOST, PORT);
  2349. auto res = cli.Get("/hi");
  2350. ASSERT_FALSE(res);
  2351. }
  2352. }
  2353. TEST(URLFragmentTest, WithFragment) {
  2354. Server svr;
  2355. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2356. EXPECT_TRUE(req.target == "/hi");
  2357. });
  2358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2359. auto se = detail::scope_exit([&] {
  2360. svr.stop();
  2361. thread.join();
  2362. ASSERT_FALSE(svr.is_running());
  2363. });
  2364. svr.wait_until_ready();
  2365. {
  2366. Client cli(HOST, PORT);
  2367. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2368. EXPECT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. res = cli.Get("/hi%23key1=val1=key2=val2");
  2371. EXPECT_TRUE(res);
  2372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2373. }
  2374. }
  2375. TEST(HeaderWriter, SetHeaderWriter) {
  2376. Server svr;
  2377. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2378. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2379. return detail::write_headers(strm, hdrs);
  2380. });
  2381. svr.Get("/hi", [](const Request &req, Response &res) {
  2382. auto it = req.headers.find("CustomClientHeader");
  2383. EXPECT_TRUE(it != req.headers.end());
  2384. EXPECT_EQ(it->second, "CustomClientValue");
  2385. res.set_content("Hello World!\n", "text/plain");
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. {
  2395. Client cli(HOST, PORT);
  2396. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2397. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2398. return detail::write_headers(strm, hdrs);
  2399. });
  2400. auto res = cli.Get("/hi");
  2401. EXPECT_TRUE(res);
  2402. EXPECT_EQ(StatusCode::OK_200, res->status);
  2403. auto it = res->headers.find("CustomServerHeader");
  2404. EXPECT_TRUE(it != res->headers.end());
  2405. EXPECT_EQ(it->second, "CustomServerValue");
  2406. }
  2407. }
  2408. class ServerTest : public ::testing::Test {
  2409. protected:
  2410. ServerTest()
  2411. : cli_(HOST, PORT)
  2412. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2413. ,
  2414. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2415. #endif
  2416. {
  2417. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2418. cli_.enable_server_certificate_verification(false);
  2419. #endif
  2420. }
  2421. virtual void SetUp() {
  2422. svr_.set_mount_point("/", "./www");
  2423. svr_.set_mount_point("/mount", "./www2");
  2424. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2425. svr_.Get("/hi",
  2426. [&](const Request & /*req*/, Response &res) {
  2427. res.set_content("Hello World!", "text/plain");
  2428. })
  2429. .Get("/file_content",
  2430. [&](const Request & /*req*/, Response &res) {
  2431. res.set_file_content("./www/dir/test.html");
  2432. })
  2433. .Get("/file_content_with_content_type",
  2434. [&](const Request & /*req*/, Response &res) {
  2435. res.set_file_content("./www/file", "text/plain");
  2436. })
  2437. .Get("/invalid_file_content",
  2438. [&](const Request & /*req*/, Response &res) {
  2439. res.set_file_content("./www/dir/invalid_file_path");
  2440. })
  2441. .Get("/http_response_splitting",
  2442. [&](const Request & /*req*/, Response &res) {
  2443. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2444. EXPECT_EQ(0U, res.headers.size());
  2445. EXPECT_FALSE(res.has_header("a"));
  2446. res.set_header("a", "1\nSet-Cookie: a=1");
  2447. EXPECT_EQ(0U, res.headers.size());
  2448. EXPECT_FALSE(res.has_header("a"));
  2449. res.set_header("a", "1\rSet-Cookie: a=1");
  2450. EXPECT_EQ(0U, res.headers.size());
  2451. EXPECT_FALSE(res.has_header("a"));
  2452. res.set_header("a\r\nb", "0");
  2453. EXPECT_EQ(0U, res.headers.size());
  2454. EXPECT_FALSE(res.has_header("a"));
  2455. res.set_header("a\rb", "0");
  2456. EXPECT_EQ(0U, res.headers.size());
  2457. EXPECT_FALSE(res.has_header("a"));
  2458. res.set_header("a\nb", "0");
  2459. EXPECT_EQ(0U, res.headers.size());
  2460. EXPECT_FALSE(res.has_header("a"));
  2461. res.set_redirect("1\r\nSet-Cookie: a=1");
  2462. EXPECT_EQ(0U, res.headers.size());
  2463. EXPECT_FALSE(res.has_header("Location"));
  2464. })
  2465. .Get("/slow",
  2466. [&](const Request & /*req*/, Response &res) {
  2467. std::this_thread::sleep_for(std::chrono::seconds(2));
  2468. res.set_content("slow", "text/plain");
  2469. })
  2470. #if 0
  2471. .Post("/slowpost",
  2472. [&](const Request & /*req*/, Response &res) {
  2473. std::this_thread::sleep_for(std::chrono::seconds(2));
  2474. res.set_content("slow", "text/plain");
  2475. })
  2476. #endif
  2477. .Get("/remote_addr",
  2478. [&](const Request &req, Response &res) {
  2479. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2480. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2481. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2482. EXPECT_EQ(req.remote_port,
  2483. std::stoi(req.get_header_value("REMOTE_PORT")));
  2484. res.set_content(remote_addr.c_str(), "text/plain");
  2485. })
  2486. .Get("/local_addr",
  2487. [&](const Request &req, Response &res) {
  2488. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2489. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2490. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2491. auto local_port = req.get_header_value("LOCAL_PORT");
  2492. EXPECT_EQ(req.local_addr, local_addr);
  2493. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2494. res.set_content(local_addr.append(":").append(local_port),
  2495. "text/plain");
  2496. })
  2497. .Get("/endwith%",
  2498. [&](const Request & /*req*/, Response &res) {
  2499. res.set_content("Hello World!", "text/plain");
  2500. })
  2501. .Get("/a\\+\\+b",
  2502. [&](const Request &req, Response &res) {
  2503. ASSERT_TRUE(req.has_param("a +b"));
  2504. auto val = req.get_param_value("a +b");
  2505. res.set_content(val, "text/plain");
  2506. })
  2507. .Get("/", [&](const Request & /*req*/,
  2508. Response &res) { res.set_redirect("/hi"); })
  2509. .Post("/1",
  2510. [](const Request & /*req*/, Response &res) {
  2511. res.set_redirect("/2", StatusCode::SeeOther_303);
  2512. })
  2513. .Get("/2",
  2514. [](const Request & /*req*/, Response &res) {
  2515. res.set_content("redirected.", "text/plain");
  2516. res.status = StatusCode::OK_200;
  2517. })
  2518. .Post("/person",
  2519. [&](const Request &req, Response &res) {
  2520. if (req.has_param("name") && req.has_param("note")) {
  2521. persons_[req.get_param_value("name")] =
  2522. req.get_param_value("note");
  2523. } else {
  2524. res.status = StatusCode::BadRequest_400;
  2525. }
  2526. })
  2527. .Put("/person",
  2528. [&](const Request &req, Response &res) {
  2529. if (req.has_param("name") && req.has_param("note")) {
  2530. persons_[req.get_param_value("name")] =
  2531. req.get_param_value("note");
  2532. } else {
  2533. res.status = StatusCode::BadRequest_400;
  2534. }
  2535. })
  2536. .Get("/person/(.*)",
  2537. [&](const Request &req, Response &res) {
  2538. string name = req.matches[1];
  2539. if (persons_.find(name) != persons_.end()) {
  2540. auto note = persons_[name];
  2541. res.set_content(note, "text/plain");
  2542. } else {
  2543. res.status = StatusCode::NotFound_404;
  2544. }
  2545. })
  2546. .Delete("/person",
  2547. [&](const Request &req, Response &res) {
  2548. if (req.has_param("name")) {
  2549. string name = req.get_param_value("name");
  2550. if (persons_.find(name) != persons_.end()) {
  2551. persons_.erase(name);
  2552. res.set_content("DELETED", "text/plain");
  2553. } else {
  2554. res.status = StatusCode::NotFound_404;
  2555. }
  2556. } else {
  2557. res.status = StatusCode::BadRequest_400;
  2558. }
  2559. })
  2560. .Post("/x-www-form-urlencoded-json",
  2561. [&](const Request &req, Response &res) {
  2562. auto json = req.get_param_value("json");
  2563. ASSERT_EQ(JSON_DATA, json);
  2564. res.set_content(json, "appliation/json");
  2565. res.status = StatusCode::OK_200;
  2566. })
  2567. .Get("/streamed-chunked",
  2568. [&](const Request & /*req*/, Response &res) {
  2569. res.set_chunked_content_provider(
  2570. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2571. sink.os << "123";
  2572. sink.os << "456";
  2573. sink.os << "789";
  2574. sink.done();
  2575. return true;
  2576. });
  2577. })
  2578. .Get("/streamed-chunked2",
  2579. [&](const Request & /*req*/, Response &res) {
  2580. auto i = new int(0);
  2581. res.set_chunked_content_provider(
  2582. "text/plain",
  2583. [i](size_t /*offset*/, DataSink &sink) {
  2584. switch (*i) {
  2585. case 0: sink.os << "123"; break;
  2586. case 1: sink.os << "456"; break;
  2587. case 2: sink.os << "789"; break;
  2588. case 3: sink.done(); break;
  2589. }
  2590. (*i)++;
  2591. return true;
  2592. },
  2593. [i](bool success) {
  2594. EXPECT_TRUE(success);
  2595. delete i;
  2596. });
  2597. })
  2598. .Get("/streamed-chunked-with-trailer",
  2599. [&](const Request & /*req*/, Response &res) {
  2600. auto i = new int(0);
  2601. res.set_header("Trailer", "Dummy1, Dummy2");
  2602. res.set_chunked_content_provider(
  2603. "text/plain",
  2604. [i](size_t /*offset*/, DataSink &sink) {
  2605. switch (*i) {
  2606. case 0: sink.os << "123"; break;
  2607. case 1: sink.os << "456"; break;
  2608. case 2: sink.os << "789"; break;
  2609. case 3: {
  2610. sink.done_with_trailer(
  2611. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2612. } break;
  2613. }
  2614. (*i)++;
  2615. return true;
  2616. },
  2617. [i](bool success) {
  2618. EXPECT_TRUE(success);
  2619. delete i;
  2620. });
  2621. })
  2622. .Get("/streamed",
  2623. [&](const Request & /*req*/, Response &res) {
  2624. res.set_content_provider(
  2625. 6, "text/plain",
  2626. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2627. sink.os << (offset < 3 ? "a" : "b");
  2628. return true;
  2629. });
  2630. })
  2631. .Get("/streamed-with-range",
  2632. [&](const Request &req, Response &res) {
  2633. auto data = new std::string("abcdefg");
  2634. res.set_content_provider(
  2635. data->size(), "text/plain",
  2636. [data](size_t offset, size_t length, DataSink &sink) {
  2637. size_t DATA_CHUNK_SIZE = 4;
  2638. const auto &d = *data;
  2639. auto out_len =
  2640. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2641. auto ret =
  2642. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2643. EXPECT_TRUE(ret);
  2644. return true;
  2645. },
  2646. [data, &req](bool success) {
  2647. EXPECT_EQ(success, !req.has_param("error"));
  2648. delete data;
  2649. });
  2650. })
  2651. .Get("/streamed-cancel",
  2652. [&](const Request & /*req*/, Response &res) {
  2653. res.set_content_provider(
  2654. size_t(-1), "text/plain",
  2655. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2656. sink.os << "data_chunk";
  2657. return true;
  2658. });
  2659. })
  2660. .Get("/regex-with-delimiter",
  2661. [&](const Request &req, Response & /*res*/) {
  2662. ASSERT_TRUE(req.has_param("key"));
  2663. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2664. })
  2665. .Get("/with-range",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. res.set_content("abcdefg", "text/plain");
  2668. })
  2669. .Get("/test-start-time",
  2670. [&](const Request &req, Response & /*res*/) {
  2671. EXPECT_NE(req.start_time_,
  2672. std::chrono::steady_clock::time_point::min());
  2673. })
  2674. .Get("/with-range-customized-response",
  2675. [&](const Request & /*req*/, Response &res) {
  2676. res.status = StatusCode::BadRequest_400;
  2677. res.set_content(JSON_DATA, "application/json");
  2678. })
  2679. .Post("/chunked",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(req.body, "dechunked post body");
  2682. })
  2683. .Post("/large-chunked",
  2684. [&](const Request &req, Response & /*res*/) {
  2685. std::string expected(6 * 30 * 1024u, 'a');
  2686. EXPECT_EQ(req.body, expected);
  2687. })
  2688. .Post("/multipart",
  2689. [&](const Request &req, Response & /*res*/) {
  2690. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2691. req.form.get_field_count("text2") +
  2692. req.form.get_field_count("file3") +
  2693. req.form.get_field_count("file4"));
  2694. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2695. req.form.get_file_count("file2"));
  2696. ASSERT_TRUE(!req.form.has_file("???"));
  2697. ASSERT_TRUE(!req.form.has_field("???"));
  2698. ASSERT_TRUE(req.body.empty());
  2699. {
  2700. const auto &text = req.form.get_field("text1");
  2701. EXPECT_EQ("text default", text);
  2702. }
  2703. {
  2704. const auto &text = req.form.get_field("text2");
  2705. EXPECT_EQ("aωb", text);
  2706. }
  2707. {
  2708. const auto &file = req.form.get_file("file1");
  2709. EXPECT_EQ("hello.txt", file.filename);
  2710. EXPECT_EQ("text/plain", file.content_type);
  2711. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2712. }
  2713. {
  2714. const auto &file = req.form.get_file("file2");
  2715. EXPECT_EQ("world.json", file.filename);
  2716. EXPECT_EQ("application/json", file.content_type);
  2717. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2718. }
  2719. {
  2720. const auto &text = req.form.get_field("file3");
  2721. EXPECT_EQ(0u, text.size());
  2722. }
  2723. {
  2724. const auto &text = req.form.get_field("file4");
  2725. EXPECT_EQ(0u, text.size());
  2726. }
  2727. })
  2728. .Post("/multipart/multi_file_values",
  2729. [&](const Request &req, Response & /*res*/) {
  2730. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2731. req.form.get_field_count("multi_text1"));
  2732. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2733. ASSERT_TRUE(!req.form.has_file("???"));
  2734. ASSERT_TRUE(!req.form.has_field("???"));
  2735. ASSERT_TRUE(req.body.empty());
  2736. {
  2737. const auto &text = req.form.get_field("text");
  2738. EXPECT_EQ("default text", text);
  2739. }
  2740. {
  2741. const auto &text1_values = req.form.get_fields("multi_text1");
  2742. EXPECT_EQ(2u, text1_values.size());
  2743. EXPECT_EQ("aaaaa", text1_values[0]);
  2744. EXPECT_EQ("bbbbb", text1_values[1]);
  2745. }
  2746. {
  2747. const auto &file1_values = req.form.get_files("multi_file1");
  2748. EXPECT_EQ(2u, file1_values.size());
  2749. auto file1 = file1_values[0];
  2750. EXPECT_EQ(file1.filename, "hello.txt");
  2751. EXPECT_EQ(file1.content_type, "text/plain");
  2752. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2753. auto file2 = file1_values[1];
  2754. EXPECT_EQ(file2.filename, "world.json");
  2755. EXPECT_EQ(file2.content_type, "application/json");
  2756. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2757. }
  2758. })
  2759. .Post("/empty",
  2760. [&](const Request &req, Response &res) {
  2761. EXPECT_EQ(req.body, "");
  2762. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2763. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2764. res.set_content("empty", "text/plain");
  2765. })
  2766. .Post("/empty-no-content-type",
  2767. [&](const Request &req, Response &res) {
  2768. EXPECT_EQ(req.body, "");
  2769. EXPECT_FALSE(req.has_header("Content-Type"));
  2770. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2771. res.set_content("empty-no-content-type", "text/plain");
  2772. })
  2773. .Post("/path-only",
  2774. [&](const Request &req, Response &res) {
  2775. EXPECT_EQ(req.body, "");
  2776. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2777. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2778. res.set_content("path-only", "text/plain");
  2779. })
  2780. .Post("/path-headers-only",
  2781. [&](const Request &req, Response &res) {
  2782. EXPECT_EQ(req.body, "");
  2783. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2784. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2785. EXPECT_EQ("world", req.get_header_value("hello"));
  2786. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2787. res.set_content("path-headers-only", "text/plain");
  2788. })
  2789. .Post("/post-large",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, LARGE_DATA);
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Put("/empty-no-content-type",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(req.body, "");
  2797. EXPECT_FALSE(req.has_header("Content-Type"));
  2798. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2799. res.set_content("empty-no-content-type", "text/plain");
  2800. })
  2801. .Put("/put",
  2802. [&](const Request &req, Response &res) {
  2803. EXPECT_EQ(req.body, "PUT");
  2804. res.set_content(req.body, "text/plain");
  2805. })
  2806. .Put("/put-large",
  2807. [&](const Request &req, Response &res) {
  2808. EXPECT_EQ(req.body, LARGE_DATA);
  2809. res.set_content(req.body, "text/plain");
  2810. })
  2811. .Patch("/patch",
  2812. [&](const Request &req, Response &res) {
  2813. EXPECT_EQ(req.body, "PATCH");
  2814. res.set_content(req.body, "text/plain");
  2815. })
  2816. .Delete("/delete",
  2817. [&](const Request & /*req*/, Response &res) {
  2818. res.set_content("DELETE", "text/plain");
  2819. })
  2820. .Delete("/delete-body",
  2821. [&](const Request &req, Response &res) {
  2822. EXPECT_EQ(req.body, "content");
  2823. res.set_content(req.body, "text/plain");
  2824. })
  2825. .Options(R"(\*)",
  2826. [&](const Request & /*req*/, Response &res) {
  2827. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2828. })
  2829. .Get("/request-target",
  2830. [&](const Request &req, Response & /*res*/) {
  2831. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2832. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2833. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2834. })
  2835. .Get("/long-query-value",
  2836. [&](const Request &req, Response & /*res*/) {
  2837. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2838. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2839. })
  2840. .Get("/too-long-query-value",
  2841. [&](const Request &req, Response & /*res*/) {
  2842. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2843. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2844. })
  2845. .Get("/array-param",
  2846. [&](const Request &req, Response & /*res*/) {
  2847. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2848. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2849. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2850. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2851. })
  2852. .Post("/validate-no-multiple-headers",
  2853. [&](const Request &req, Response & /*res*/) {
  2854. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2855. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2856. })
  2857. .Post("/content_receiver",
  2858. [&](const Request &req, Response &res,
  2859. const ContentReader &content_reader) {
  2860. if (req.is_multipart_form_data()) {
  2861. std::vector<FormData> items;
  2862. content_reader(
  2863. [&](const FormData &file) {
  2864. items.push_back(file);
  2865. return true;
  2866. },
  2867. [&](const char *data, size_t data_length) {
  2868. items.back().content.append(data, data_length);
  2869. return true;
  2870. });
  2871. EXPECT_EQ(5u, items.size());
  2872. {
  2873. const auto &file = get_file_value(items, "text1");
  2874. EXPECT_TRUE(file.filename.empty());
  2875. EXPECT_EQ("text default", file.content);
  2876. }
  2877. {
  2878. const auto &file = get_file_value(items, "text2");
  2879. EXPECT_TRUE(file.filename.empty());
  2880. EXPECT_EQ("aωb", file.content);
  2881. }
  2882. {
  2883. const auto &file = get_file_value(items, "file1");
  2884. EXPECT_EQ("hello.txt", file.filename);
  2885. EXPECT_EQ("text/plain", file.content_type);
  2886. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2887. }
  2888. {
  2889. const auto &file = get_file_value(items, "file2");
  2890. EXPECT_EQ("world.json", file.filename);
  2891. EXPECT_EQ("application/json", file.content_type);
  2892. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2893. }
  2894. {
  2895. const auto &file = get_file_value(items, "file3");
  2896. EXPECT_TRUE(file.filename.empty());
  2897. EXPECT_EQ("application/octet-stream", file.content_type);
  2898. EXPECT_EQ(0u, file.content.size());
  2899. }
  2900. } else {
  2901. std::string body;
  2902. content_reader([&](const char *data, size_t data_length) {
  2903. EXPECT_EQ(7U, data_length);
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. EXPECT_EQ(body, "content");
  2908. res.set_content(body, "text/plain");
  2909. }
  2910. })
  2911. .Put("/content_receiver",
  2912. [&](const Request & /*req*/, Response &res,
  2913. const ContentReader &content_reader) {
  2914. std::string body;
  2915. content_reader([&](const char *data, size_t data_length) {
  2916. body.append(data, data_length);
  2917. return true;
  2918. });
  2919. EXPECT_EQ(body, "content");
  2920. res.set_content(body, "text/plain");
  2921. })
  2922. .Patch("/content_receiver",
  2923. [&](const Request & /*req*/, Response &res,
  2924. const ContentReader &content_reader) {
  2925. std::string body;
  2926. content_reader([&](const char *data, size_t data_length) {
  2927. body.append(data, data_length);
  2928. return true;
  2929. });
  2930. EXPECT_EQ(body, "content");
  2931. res.set_content(body, "text/plain");
  2932. })
  2933. .Post("/query-string-and-body",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. ASSERT_TRUE(req.has_param("key"));
  2936. EXPECT_EQ(req.get_param_value("key"), "value");
  2937. EXPECT_EQ(req.body, "content");
  2938. })
  2939. .Get("/last-request",
  2940. [&](const Request &req, Response & /*res*/) {
  2941. EXPECT_EQ("close", req.get_header_value("Connection"));
  2942. })
  2943. .Get(R"(/redirect/(\d+))",
  2944. [&](const Request &req, Response &res) {
  2945. auto num = std::stoi(req.matches[1]) + 1;
  2946. std::string url = "/redirect/" + std::to_string(num);
  2947. res.set_redirect(url);
  2948. })
  2949. .Post("/binary",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(4U, req.body.size());
  2952. EXPECT_EQ("application/octet-stream",
  2953. req.get_header_value("Content-Type"));
  2954. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2955. res.set_content(req.body, "application/octet-stream");
  2956. })
  2957. .Put("/binary",
  2958. [&](const Request &req, Response &res) {
  2959. EXPECT_EQ(4U, req.body.size());
  2960. EXPECT_EQ("application/octet-stream",
  2961. req.get_header_value("Content-Type"));
  2962. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2963. res.set_content(req.body, "application/octet-stream");
  2964. })
  2965. .Patch("/binary",
  2966. [&](const Request &req, Response &res) {
  2967. EXPECT_EQ(4U, req.body.size());
  2968. EXPECT_EQ("application/octet-stream",
  2969. req.get_header_value("Content-Type"));
  2970. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2971. res.set_content(req.body, "application/octet-stream");
  2972. })
  2973. .Delete("/binary",
  2974. [&](const Request &req, Response &res) {
  2975. EXPECT_EQ(4U, req.body.size());
  2976. EXPECT_EQ("application/octet-stream",
  2977. req.get_header_value("Content-Type"));
  2978. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2979. res.set_content(req.body, "application/octet-stream");
  2980. })
  2981. .Get("/issue1772",
  2982. [&](const Request & /*req*/, Response &res) {
  2983. res.status = 401;
  2984. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2985. })
  2986. .Delete("/issue609",
  2987. [](const httplib::Request &, httplib::Response &res,
  2988. const httplib::ContentReader &) {
  2989. res.set_content("ok", "text/plain");
  2990. })
  2991. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2992. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2993. .Get("/compress",
  2994. [&](const Request & /*req*/, Response &res) {
  2995. res.set_content(
  2996. "12345678901234567890123456789012345678901234567890123456789"
  2997. "01234567890123456789012345678901234567890",
  2998. "text/plain");
  2999. })
  3000. .Get("/nocompress",
  3001. [&](const Request & /*req*/, Response &res) {
  3002. res.set_content(
  3003. "12345678901234567890123456789012345678901234567890123456789"
  3004. "01234567890123456789012345678901234567890",
  3005. "application/octet-stream");
  3006. })
  3007. .Post("/compress-multipart",
  3008. [&](const Request &req, Response & /*res*/) {
  3009. EXPECT_EQ(2u, req.form.fields.size());
  3010. ASSERT_TRUE(!req.form.has_field("???"));
  3011. {
  3012. const auto &text = req.form.get_field("key1");
  3013. EXPECT_EQ("test", text);
  3014. }
  3015. {
  3016. const auto &text = req.form.get_field("key2");
  3017. EXPECT_EQ("--abcdefg123", text);
  3018. }
  3019. })
  3020. #endif
  3021. ;
  3022. persons_["john"] = "programmer";
  3023. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3024. svr_.wait_until_ready();
  3025. }
  3026. virtual void TearDown() {
  3027. svr_.stop();
  3028. if (!request_threads_.empty()) {
  3029. std::this_thread::sleep_for(std::chrono::seconds(1));
  3030. for (auto &t : request_threads_) {
  3031. t.join();
  3032. }
  3033. }
  3034. t_.join();
  3035. }
  3036. map<string, string> persons_;
  3037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3038. SSLClient cli_;
  3039. SSLServer svr_;
  3040. #else
  3041. Client cli_;
  3042. Server svr_;
  3043. #endif
  3044. thread t_;
  3045. std::vector<thread> request_threads_;
  3046. };
  3047. TEST_F(ServerTest, GetMethod200) {
  3048. auto res = cli_.Get("/hi");
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ("HTTP/1.1", res->version);
  3051. EXPECT_EQ(StatusCode::OK_200, res->status);
  3052. EXPECT_EQ("OK", res->reason);
  3053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3054. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3055. EXPECT_EQ("Hello World!", res->body);
  3056. }
  3057. void performance_test(const char *host) {
  3058. auto port = 1234;
  3059. Server svr;
  3060. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3061. res.set_content("Benchmark Response", "text/plain");
  3062. });
  3063. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. listen_thread.join();
  3067. ASSERT_FALSE(svr.is_running());
  3068. });
  3069. svr.wait_until_ready();
  3070. Client cli(host, port);
  3071. auto start = std::chrono::high_resolution_clock::now();
  3072. auto res = cli.Get("/benchmark");
  3073. ASSERT_TRUE(res);
  3074. EXPECT_EQ(StatusCode::OK_200, res->status);
  3075. auto end = std::chrono::high_resolution_clock::now();
  3076. auto elapsed =
  3077. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3078. .count();
  3079. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3080. << "ms (Issue #1777)";
  3081. }
  3082. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3083. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3084. TEST_F(ServerTest, GetEmptyFile) {
  3085. auto res = cli_.Get("/empty_file");
  3086. ASSERT_TRUE(res);
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3089. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3090. EXPECT_EQ("", res->body);
  3091. }
  3092. TEST_F(ServerTest, GetFileContent) {
  3093. auto res = cli_.Get("/file_content");
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::OK_200, res->status);
  3096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3097. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3098. EXPECT_EQ("test.html", res->body);
  3099. }
  3100. TEST_F(ServerTest, GetFileContentWithRange) {
  3101. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3104. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3105. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3106. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3107. EXPECT_EQ("est", res->body);
  3108. }
  3109. TEST_F(ServerTest, GetFileContentWithContentType) {
  3110. auto res = cli_.Get("/file_content_with_content_type");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::OK_200, res->status);
  3113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3114. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3115. EXPECT_EQ("file\n", res->body);
  3116. }
  3117. TEST_F(ServerTest, GetInvalidFileContent) {
  3118. auto res = cli_.Get("/invalid_file_content");
  3119. ASSERT_TRUE(res);
  3120. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3121. }
  3122. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3123. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3124. ASSERT_TRUE(res);
  3125. EXPECT_EQ("HTTP/1.1", res->version);
  3126. EXPECT_EQ(StatusCode::OK_200, res->status);
  3127. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3128. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3129. EXPECT_EQ("Hello World!", res->body);
  3130. }
  3131. TEST_F(ServerTest, GetMethod302) {
  3132. auto res = cli_.Get("/");
  3133. ASSERT_TRUE(res);
  3134. EXPECT_EQ(StatusCode::Found_302, res->status);
  3135. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3136. }
  3137. TEST_F(ServerTest, GetMethod302Redirect) {
  3138. cli_.set_follow_location(true);
  3139. auto res = cli_.Get("/");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("Hello World!", res->body);
  3143. EXPECT_EQ("/hi", res->location);
  3144. }
  3145. TEST_F(ServerTest, GetMethod404) {
  3146. auto res = cli_.Get("/invalid");
  3147. ASSERT_TRUE(res);
  3148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3149. }
  3150. TEST_F(ServerTest, HeadMethod200) {
  3151. auto res = cli_.Head("/hi");
  3152. ASSERT_TRUE(res);
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3155. EXPECT_TRUE(res->body.empty());
  3156. }
  3157. TEST_F(ServerTest, HeadMethod200Static) {
  3158. auto res = cli_.Head("/mount/dir/index.html");
  3159. ASSERT_TRUE(res);
  3160. EXPECT_EQ(StatusCode::OK_200, res->status);
  3161. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3162. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3163. EXPECT_TRUE(res->body.empty());
  3164. }
  3165. TEST_F(ServerTest, HeadMethod404) {
  3166. auto res = cli_.Head("/invalid");
  3167. ASSERT_TRUE(res);
  3168. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3169. EXPECT_TRUE(res->body.empty());
  3170. }
  3171. TEST_F(ServerTest, GetMethodPersonJohn) {
  3172. auto res = cli_.Get("/person/john");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3176. EXPECT_EQ("programmer", res->body);
  3177. }
  3178. TEST_F(ServerTest, PostMethod1) {
  3179. auto res = cli_.Get("/person/john1");
  3180. ASSERT_TRUE(res);
  3181. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3182. res = cli_.Post("/person", "name=john1&note=coder",
  3183. "application/x-www-form-urlencoded");
  3184. ASSERT_TRUE(res);
  3185. ASSERT_EQ(StatusCode::OK_200, res->status);
  3186. res = cli_.Get("/person/john1");
  3187. ASSERT_TRUE(res);
  3188. ASSERT_EQ(StatusCode::OK_200, res->status);
  3189. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3190. ASSERT_EQ("coder", res->body);
  3191. }
  3192. TEST_F(ServerTest, PostMethod2) {
  3193. auto res = cli_.Get("/person/john2");
  3194. ASSERT_TRUE(res);
  3195. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3196. Params params;
  3197. params.emplace("name", "john2");
  3198. params.emplace("note", "coder");
  3199. res = cli_.Post("/person", params);
  3200. ASSERT_TRUE(res);
  3201. ASSERT_EQ(StatusCode::OK_200, res->status);
  3202. res = cli_.Get("/person/john2");
  3203. ASSERT_TRUE(res);
  3204. ASSERT_EQ(StatusCode::OK_200, res->status);
  3205. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3206. ASSERT_EQ("coder", res->body);
  3207. }
  3208. TEST_F(ServerTest, PutMethod3) {
  3209. auto res = cli_.Get("/person/john3");
  3210. ASSERT_TRUE(res);
  3211. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3212. Params params;
  3213. params.emplace("name", "john3");
  3214. params.emplace("note", "coder");
  3215. res = cli_.Put("/person", params);
  3216. ASSERT_TRUE(res);
  3217. ASSERT_EQ(StatusCode::OK_200, res->status);
  3218. res = cli_.Get("/person/john3");
  3219. ASSERT_TRUE(res);
  3220. ASSERT_EQ(StatusCode::OK_200, res->status);
  3221. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. ASSERT_EQ("coder", res->body);
  3223. }
  3224. TEST_F(ServerTest, DeleteMethod1) {
  3225. auto res = cli_.Get("/person/john4");
  3226. ASSERT_TRUE(res);
  3227. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3228. Params params;
  3229. params.emplace("name", "john4");
  3230. params.emplace("note", "coder");
  3231. res = cli_.Post("/person", params);
  3232. ASSERT_TRUE(res);
  3233. ASSERT_EQ(StatusCode::OK_200, res->status);
  3234. res = cli_.Get("/person/john4");
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(StatusCode::OK_200, res->status);
  3237. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3238. ASSERT_EQ("coder", res->body);
  3239. Params delete_params;
  3240. delete_params.emplace("name", "john4");
  3241. res = cli_.Delete("/person", delete_params);
  3242. ASSERT_TRUE(res);
  3243. ASSERT_EQ(StatusCode::OK_200, res->status);
  3244. ASSERT_EQ("DELETED", res->body);
  3245. res = cli_.Get("/person/john4");
  3246. ASSERT_TRUE(res);
  3247. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3248. }
  3249. TEST_F(ServerTest, DeleteMethod2) {
  3250. auto res = cli_.Get("/person/john5");
  3251. ASSERT_TRUE(res);
  3252. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3253. Params params;
  3254. params.emplace("name", "john5");
  3255. params.emplace("note", "developer");
  3256. res = cli_.Post("/person", params);
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. res = cli_.Get("/person/john5");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::OK_200, res->status);
  3262. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. ASSERT_EQ("developer", res->body);
  3264. Params delete_params;
  3265. delete_params.emplace("name", "john5");
  3266. Headers headers;
  3267. headers.emplace("Custom-Header", "test-value");
  3268. res = cli_.Delete("/person", headers, delete_params);
  3269. ASSERT_TRUE(res);
  3270. ASSERT_EQ(StatusCode::OK_200, res->status);
  3271. ASSERT_EQ("DELETED", res->body);
  3272. res = cli_.Get("/person/john5");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3275. }
  3276. TEST_F(ServerTest, DeleteMethod3) {
  3277. auto res = cli_.Get("/person/john6");
  3278. ASSERT_TRUE(res);
  3279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3280. Params params;
  3281. params.emplace("name", "john6");
  3282. params.emplace("note", "tester");
  3283. res = cli_.Post("/person", params);
  3284. ASSERT_TRUE(res);
  3285. ASSERT_EQ(StatusCode::OK_200, res->status);
  3286. res = cli_.Get("/person/john6");
  3287. ASSERT_TRUE(res);
  3288. ASSERT_EQ(StatusCode::OK_200, res->status);
  3289. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3290. ASSERT_EQ("tester", res->body);
  3291. Params delete_params;
  3292. delete_params.emplace("name", "john6");
  3293. Headers headers;
  3294. headers.emplace("Custom-Header", "test-value");
  3295. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john6");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3304. Params params;
  3305. params.emplace("json", JSON_DATA);
  3306. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3307. ASSERT_TRUE(res);
  3308. ASSERT_EQ(StatusCode::OK_200, res->status);
  3309. ASSERT_EQ(JSON_DATA, res->body);
  3310. }
  3311. TEST_F(ServerTest, PostEmptyContent) {
  3312. auto res = cli_.Post("/empty", "", "text/plain");
  3313. ASSERT_TRUE(res);
  3314. ASSERT_EQ(StatusCode::OK_200, res->status);
  3315. ASSERT_EQ("empty", res->body);
  3316. }
  3317. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3318. auto res = cli_.Post("/empty-no-content-type");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("empty-no-content-type", res->body);
  3322. }
  3323. TEST_F(ServerTest, PostPathOnly) {
  3324. auto res = cli_.Post("/path-only");
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::OK_200, res->status);
  3327. ASSERT_EQ("path-only", res->body);
  3328. }
  3329. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3330. auto res = cli_.Post("/path-headers-only",
  3331. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. ASSERT_EQ("path-headers-only", res->body);
  3335. }
  3336. TEST_F(ServerTest, PostLarge) {
  3337. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. EXPECT_EQ(LARGE_DATA, res->body);
  3341. }
  3342. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3343. auto res = cli_.Put("/empty-no-content-type");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("empty-no-content-type", res->body);
  3347. }
  3348. TEST_F(ServerTest, GetMethodDir) {
  3349. auto res = cli_.Get("/dir/");
  3350. ASSERT_TRUE(res);
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3353. auto body = R"(<html>
  3354. <head>
  3355. </head>
  3356. <body>
  3357. <a href="/dir/test.html">Test</a>
  3358. <a href="/hi">hi</a>
  3359. </body>
  3360. </html>
  3361. )";
  3362. EXPECT_EQ(body, res->body);
  3363. }
  3364. TEST_F(ServerTest, GetMethodDirTest) {
  3365. auto res = cli_.Get("/dir/test.html");
  3366. ASSERT_TRUE(res);
  3367. EXPECT_EQ(StatusCode::OK_200, res->status);
  3368. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3369. EXPECT_EQ("test.html", res->body);
  3370. }
  3371. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3372. auto res = cli_.Get("/dir/../dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3376. EXPECT_EQ("test.html", res->body);
  3377. }
  3378. TEST_F(ServerTest, GetMethodInvalidPath) {
  3379. auto res = cli_.Get("/dir/../test.html");
  3380. ASSERT_TRUE(res);
  3381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3382. }
  3383. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3384. auto res = cli_.Get("/../www/dir/test.html");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3387. }
  3388. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3389. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3392. }
  3393. TEST_F(ServerTest, GetMethodDirMountTest) {
  3394. auto res = cli_.Get("/mount/dir/test.html");
  3395. ASSERT_TRUE(res);
  3396. EXPECT_EQ(StatusCode::OK_200, res->status);
  3397. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3398. EXPECT_EQ("test.html", res->body);
  3399. }
  3400. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3401. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::OK_200, res->status);
  3404. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3405. EXPECT_EQ("test.html", res->body);
  3406. }
  3407. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3408. auto res = cli_.Get("/mount/dir/../test.html");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3413. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3418. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3421. }
  3422. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3423. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3424. ASSERT_TRUE(res);
  3425. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3426. }
  3427. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3428. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3429. ASSERT_TRUE(res);
  3430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3431. }
  3432. TEST_F(ServerTest, PostMethod303) {
  3433. auto res = cli_.Post("/1", "body", "text/plain");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3436. EXPECT_EQ("/2", res->get_header_value("Location"));
  3437. }
  3438. TEST_F(ServerTest, PostMethod303Redirect) {
  3439. cli_.set_follow_location(true);
  3440. auto res = cli_.Post("/1", "body", "text/plain");
  3441. ASSERT_TRUE(res);
  3442. EXPECT_EQ(StatusCode::OK_200, res->status);
  3443. EXPECT_EQ("redirected.", res->body);
  3444. EXPECT_EQ("/2", res->location);
  3445. }
  3446. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3447. auto res = cli_.Get("/dir/test.abcde");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::OK_200, res->status);
  3450. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3451. EXPECT_EQ("abcde", res->body);
  3452. }
  3453. TEST_F(ServerTest, StaticFileRange) {
  3454. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3457. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ(true, res->has_header("Content-Range"));
  3460. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3461. EXPECT_EQ(std::string("cd"), res->body);
  3462. }
  3463. TEST_F(ServerTest, StaticFileRanges) {
  3464. auto res =
  3465. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3468. EXPECT_TRUE(
  3469. res->get_header_value("Content-Type")
  3470. .find(
  3471. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3472. 0);
  3473. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3474. }
  3475. TEST_F(ServerTest, StaticFileRangeHead) {
  3476. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3477. ASSERT_TRUE(res);
  3478. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3479. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3480. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3481. EXPECT_EQ(true, res->has_header("Content-Range"));
  3482. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3483. }
  3484. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3485. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3486. ASSERT_TRUE(res);
  3487. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3488. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3489. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3490. EXPECT_EQ(true, res->has_header("Content-Range"));
  3491. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3492. res->get_header_value("Content-Range"));
  3493. EXPECT_EQ("LAST\n", res->body);
  3494. }
  3495. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3496. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3500. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3501. EXPECT_EQ(true, res->has_header("Content-Range"));
  3502. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3503. }
  3504. TEST_F(ServerTest, StaticFileBigFile) {
  3505. auto res = cli_.Get("/dir/1MB.txt");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3509. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3510. }
  3511. TEST_F(ServerTest, InvalidBaseDirMount) {
  3512. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3513. }
  3514. TEST_F(ServerTest, Binary) {
  3515. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3516. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3517. "application/octet-stream");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. ASSERT_EQ(4U, res->body.size());
  3521. res = cli_.Put("/binary", binary.data(), binary.size(),
  3522. "application/octet-stream");
  3523. ASSERT_TRUE(res);
  3524. ASSERT_EQ(StatusCode::OK_200, res->status);
  3525. ASSERT_EQ(4U, res->body.size());
  3526. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3527. "application/octet-stream");
  3528. ASSERT_TRUE(res);
  3529. ASSERT_EQ(StatusCode::OK_200, res->status);
  3530. ASSERT_EQ(4U, res->body.size());
  3531. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3532. "application/octet-stream");
  3533. ASSERT_TRUE(res);
  3534. ASSERT_EQ(StatusCode::OK_200, res->status);
  3535. ASSERT_EQ(4U, res->body.size());
  3536. }
  3537. TEST_F(ServerTest, BinaryString) {
  3538. auto binary = std::string("\x00\x01\x02\x03", 4);
  3539. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3540. ASSERT_TRUE(res);
  3541. ASSERT_EQ(StatusCode::OK_200, res->status);
  3542. ASSERT_EQ(4U, res->body.size());
  3543. res = cli_.Put("/binary", binary, "application/octet-stream");
  3544. ASSERT_TRUE(res);
  3545. ASSERT_EQ(StatusCode::OK_200, res->status);
  3546. ASSERT_EQ(4U, res->body.size());
  3547. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3548. ASSERT_TRUE(res);
  3549. ASSERT_EQ(StatusCode::OK_200, res->status);
  3550. ASSERT_EQ(4U, res->body.size());
  3551. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ(4U, res->body.size());
  3555. }
  3556. TEST_F(ServerTest, EmptyRequest) {
  3557. auto res = cli_.Get("");
  3558. ASSERT_TRUE(!res);
  3559. EXPECT_EQ(Error::Connection, res.error());
  3560. }
  3561. TEST_F(ServerTest, LongRequest) {
  3562. std::string request;
  3563. for (size_t i = 0; i < 545; i++) {
  3564. request += "/TooLongRequest";
  3565. }
  3566. request += "OK";
  3567. auto res = cli_.Get(request.c_str());
  3568. ASSERT_TRUE(res);
  3569. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3570. }
  3571. TEST_F(ServerTest, TooLongRequest) {
  3572. std::string request;
  3573. for (size_t i = 0; i < 546; i++) {
  3574. request += "/TooLongRequest";
  3575. }
  3576. request += "_NG";
  3577. auto res = cli_.Get(request.c_str());
  3578. ASSERT_TRUE(res);
  3579. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3580. }
  3581. TEST_F(ServerTest, AlmostTooLongRequest) {
  3582. // test for #2046 - URI length check shouldn't include other content on req
  3583. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3584. // leading /, space, HTTP/1.1)
  3585. std::string request =
  3586. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3587. auto res = cli_.Get(request.c_str());
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3590. }
  3591. TEST_F(ServerTest, LongHeader) {
  3592. Request req;
  3593. req.method = "GET";
  3594. req.path = "/hi";
  3595. std::string host_and_port;
  3596. host_and_port += HOST;
  3597. host_and_port += ":";
  3598. host_and_port += std::to_string(PORT);
  3599. req.headers.emplace("Host", host_and_port.c_str());
  3600. req.headers.emplace("Accept", "*/*");
  3601. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3602. req.headers.emplace(
  3603. "Header-Name",
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@");
  3633. auto res = std::make_shared<Response>();
  3634. auto error = Error::Success;
  3635. auto ret = cli_.send(req, *res, error);
  3636. ASSERT_TRUE(ret);
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. }
  3639. TEST_F(ServerTest, LongQueryValue) {
  3640. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3643. }
  3644. TEST_F(ServerTest, TooLongQueryValue) {
  3645. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3646. ASSERT_FALSE(res);
  3647. EXPECT_EQ(Error::Read, res.error());
  3648. }
  3649. TEST_F(ServerTest, TooLongHeader) {
  3650. Request req;
  3651. req.method = "GET";
  3652. req.path = "/hi";
  3653. std::string host_and_port;
  3654. host_and_port += HOST;
  3655. host_and_port += ":";
  3656. host_and_port += std::to_string(PORT);
  3657. req.headers.emplace("Host", host_and_port.c_str());
  3658. req.headers.emplace("Accept", "*/*");
  3659. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3660. req.headers.emplace(
  3661. "Header-Name",
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@");
  3691. auto res = std::make_shared<Response>();
  3692. auto error = Error::Success;
  3693. auto ret = cli_.send(req, *res, error);
  3694. ASSERT_TRUE(ret);
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. }
  3697. TEST_F(ServerTest, HeaderCountAtLimit) {
  3698. // Test with headers just under the 100 limit
  3699. httplib::Headers headers;
  3700. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3701. // This should keep us just under the 100 header limit
  3702. for (int i = 0; i < 95; i++) {
  3703. std::string name = "X-Test-Header-" + std::to_string(i);
  3704. std::string value = "value" + std::to_string(i);
  3705. headers.emplace(name, value);
  3706. }
  3707. // This should work fine as we're under the limit
  3708. auto res = cli_.Get("/hi", headers);
  3709. EXPECT_TRUE(res);
  3710. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3711. }
  3712. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3713. // Test with many headers to exceed the 100 limit
  3714. httplib::Headers headers;
  3715. // Add 150 headers to definitely exceed the 100 limit
  3716. for (int i = 0; i < 150; i++) {
  3717. std::string name = "X-Test-Header-" + std::to_string(i);
  3718. std::string value = "value" + std::to_string(i);
  3719. headers.emplace(name, value);
  3720. }
  3721. // This should fail due to exceeding header count limit
  3722. auto res = cli_.Get("/hi", headers);
  3723. // The request should either fail or return 400 Bad Request
  3724. if (res) {
  3725. // If we get a response, it should be 400 Bad Request
  3726. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3727. } else {
  3728. // Or the request should fail entirely
  3729. EXPECT_FALSE(res);
  3730. }
  3731. }
  3732. TEST_F(ServerTest, PercentEncoding) {
  3733. auto res = cli_.Get("/e%6edwith%");
  3734. ASSERT_TRUE(res);
  3735. EXPECT_EQ(StatusCode::OK_200, res->status);
  3736. }
  3737. TEST_F(ServerTest, PercentEncodingUnicode) {
  3738. auto res = cli_.Get("/e%u006edwith%");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, InvalidPercentEncoding) {
  3743. auto res = cli_.Get("/%endwith%");
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3746. }
  3747. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3748. auto res = cli_.Get("/%uendwith%");
  3749. ASSERT_TRUE(res);
  3750. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3751. }
  3752. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3753. auto res = cli_.Get("/hello?aaa=bbb%");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3756. }
  3757. TEST_F(ServerTest, PlusSignEncoding) {
  3758. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3759. ASSERT_TRUE(res);
  3760. EXPECT_EQ(StatusCode::OK_200, res->status);
  3761. EXPECT_EQ("a +b", res->body);
  3762. }
  3763. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3764. // This test simulates a potential DoS attack using many headers
  3765. // to verify our security fix prevents memory exhaustion
  3766. httplib::Headers attack_headers;
  3767. // Attempt to add many headers like an attacker would (200 headers to far
  3768. // exceed limit)
  3769. for (int i = 0; i < 200; i++) {
  3770. std::string name = "X-Attack-Header-" + std::to_string(i);
  3771. std::string value = "attack_payload_" + std::to_string(i);
  3772. attack_headers.emplace(name, value);
  3773. }
  3774. // Try to POST with excessive headers
  3775. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3776. // Should either fail or return 400 Bad Request due to security limit
  3777. if (res) {
  3778. // If we get a response, it should be 400 Bad Request
  3779. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3780. } else {
  3781. // Request failed, which is the expected behavior for DoS protection
  3782. EXPECT_FALSE(res);
  3783. }
  3784. }
  3785. TEST_F(ServerTest, MultipartFormData) {
  3786. UploadFormDataItems items = {
  3787. {"text1", "text default", "", ""},
  3788. {"text2", "aωb", "", ""},
  3789. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3790. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3791. {"file3", "", "", "application/octet-stream"},
  3792. {"file4", "", "", " application/json tmp-string "}};
  3793. auto res = cli_.Post("/multipart", items);
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::OK_200, res->status);
  3796. }
  3797. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3798. UploadFormDataItems items = {
  3799. {"text", "default text", "", ""},
  3800. {"multi_text1", "aaaaa", "", ""},
  3801. {"multi_text1", "bbbbb", "", ""},
  3802. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3803. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3804. "application/json"},
  3805. };
  3806. auto res = cli_.Post("/multipart/multi_file_values", items);
  3807. ASSERT_TRUE(res);
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. }
  3810. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3811. auto res = cli_.Get("/hi");
  3812. ASSERT_TRUE(res);
  3813. EXPECT_EQ(StatusCode::OK_200, res->status);
  3814. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3815. EXPECT_EQ("Hello World!", res->body);
  3816. }
  3817. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3818. Request req;
  3819. req.method = "POST";
  3820. req.path = "/chunked";
  3821. std::string host_and_port;
  3822. host_and_port += HOST;
  3823. host_and_port += ":";
  3824. host_and_port += std::to_string(PORT);
  3825. req.headers.emplace("Host", host_and_port.c_str());
  3826. req.headers.emplace("Accept", "*/*");
  3827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3828. req.headers.emplace("Content-Type", "text/plain");
  3829. req.headers.emplace("Content-Length", "0");
  3830. req.headers.emplace(
  3831. "Transfer-Encoding",
  3832. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3833. // Client does not chunk, so make a chunked body manually.
  3834. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3835. auto res = std::make_shared<Response>();
  3836. auto error = Error::Success;
  3837. auto ret = cli_.send(req, *res, error);
  3838. ASSERT_TRUE(ret);
  3839. EXPECT_EQ(StatusCode::OK_200, res->status);
  3840. }
  3841. TEST_F(ServerTest, GetStreamed2) {
  3842. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3843. ASSERT_TRUE(res);
  3844. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3845. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3846. EXPECT_EQ(true, res->has_header("Content-Range"));
  3847. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3848. EXPECT_EQ(std::string("ab"), res->body);
  3849. }
  3850. TEST_F(ServerTest, GetStreamed) {
  3851. auto res = cli_.Get("/streamed");
  3852. ASSERT_TRUE(res);
  3853. EXPECT_EQ(StatusCode::OK_200, res->status);
  3854. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3855. EXPECT_EQ(std::string("aaabbb"), res->body);
  3856. }
  3857. TEST_F(ServerTest, GetStreamedWithRange1) {
  3858. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3859. ASSERT_TRUE(res);
  3860. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3861. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3862. EXPECT_EQ(true, res->has_header("Content-Range"));
  3863. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3864. EXPECT_EQ(std::string("def"), res->body);
  3865. }
  3866. TEST_F(ServerTest, GetStreamedWithRange2) {
  3867. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3870. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3871. EXPECT_EQ(true, res->has_header("Content-Range"));
  3872. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3873. EXPECT_EQ(std::string("bcdefg"), res->body);
  3874. }
  3875. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3876. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3879. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3880. EXPECT_EQ(true, res->has_header("Content-Range"));
  3881. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3882. EXPECT_EQ(std::string("efg"), res->body);
  3883. }
  3884. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3885. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3888. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(false, res->has_header("Content-Range"));
  3890. EXPECT_EQ(0U, res->body.size());
  3891. }
  3892. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3893. auto res = cli_.Get("/streamed-with-range",
  3894. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3895. "92233720368547758079223372036854775807"}});
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3898. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3899. EXPECT_EQ(false, res->has_header("Content-Range"));
  3900. EXPECT_EQ(0U, res->body.size());
  3901. }
  3902. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3903. auto res = cli_.Get(
  3904. "/with-range",
  3905. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3906. {"Accept-Encoding", ""}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(true, res->has_header("Content-Range"));
  3911. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3912. EXPECT_EQ(std::string("abcdefg"), res->body);
  3913. }
  3914. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3915. auto res = cli_.Get("/with-range", {
  3916. {"Range", "bytes=0-"},
  3917. {"Accept-Encoding", ""},
  3918. });
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3921. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3922. EXPECT_EQ(true, res->has_header("Content-Range"));
  3923. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3924. EXPECT_EQ(std::string("abcdefg"), res->body);
  3925. }
  3926. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3927. auto res =
  3928. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3929. ASSERT_TRUE(res);
  3930. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3931. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ(false, res->has_header("Content-Range"));
  3933. EXPECT_EQ(267U, res->body.size());
  3934. // Check that both range contents are present
  3935. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3936. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3937. // Check that Content-Range headers are present for both ranges
  3938. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3939. std::string::npos);
  3940. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3941. std::string::npos);
  3942. }
  3943. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3944. Ranges ranges;
  3945. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3946. ranges.emplace_back(0, -1);
  3947. }
  3948. auto res =
  3949. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3952. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3953. EXPECT_EQ(false, res->has_header("Content-Range"));
  3954. EXPECT_EQ(0U, res->body.size());
  3955. }
  3956. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3957. auto res =
  3958. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3959. ASSERT_TRUE(res);
  3960. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3961. EXPECT_EQ(5U, res->body.size());
  3962. // Check that overlapping ranges are coalesced into a single range
  3963. EXPECT_EQ("bcdef", res->body);
  3964. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3965. // Should be single range, not multipart
  3966. EXPECT_TRUE(res->has_header("Content-Range"));
  3967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3968. }
  3969. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3970. auto res =
  3971. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3974. EXPECT_EQ(268U, res->body.size());
  3975. // Check that both range contents are present
  3976. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3977. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3978. // Check that Content-Range headers are present for both ranges
  3979. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3980. std::string::npos);
  3981. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3982. std::string::npos);
  3983. }
  3984. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3985. auto res =
  3986. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3987. ASSERT_TRUE(res);
  3988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3989. EXPECT_EQ(269U, res->body.size());
  3990. // Check that both duplicate range contents are present
  3991. size_t first_abc = res->body.find("abc\r\n");
  3992. EXPECT_TRUE(first_abc != std::string::npos);
  3993. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3994. EXPECT_TRUE(second_abc != std::string::npos);
  3995. // Check that Content-Range headers are present for both ranges
  3996. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3997. EXPECT_TRUE(first_range != std::string::npos);
  3998. size_t second_range =
  3999. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4000. EXPECT_TRUE(second_range != std::string::npos);
  4001. }
  4002. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4003. auto res = cli_.Get("/streamed-with-range?error",
  4004. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4005. ASSERT_TRUE(res);
  4006. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4007. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4008. EXPECT_EQ(false, res->has_header("Content-Range"));
  4009. EXPECT_EQ(0U, res->body.size());
  4010. }
  4011. TEST_F(ServerTest, GetStreamedEndless) {
  4012. uint64_t offset = 0;
  4013. auto res = cli_.Get("/streamed-cancel",
  4014. [&](const char * /*data*/, uint64_t data_length) {
  4015. if (offset < 100) {
  4016. offset += data_length;
  4017. return true;
  4018. }
  4019. return false;
  4020. });
  4021. ASSERT_TRUE(!res);
  4022. EXPECT_EQ(Error::Canceled, res.error());
  4023. }
  4024. TEST_F(ServerTest, ClientStop) {
  4025. std::atomic_size_t count{4};
  4026. std::vector<std::thread> threads;
  4027. for (auto i = count.load(); i != 0; --i) {
  4028. threads.emplace_back([&]() {
  4029. auto res = cli_.Get("/streamed-cancel",
  4030. [&](const char *, uint64_t) { return true; });
  4031. --count;
  4032. ASSERT_TRUE(!res);
  4033. EXPECT_TRUE(res.error() == Error::Canceled ||
  4034. res.error() == Error::Read || res.error() == Error::Write);
  4035. });
  4036. }
  4037. std::this_thread::sleep_for(std::chrono::seconds(2));
  4038. while (count != 0) {
  4039. cli_.stop();
  4040. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4041. }
  4042. for (auto &t : threads) {
  4043. t.join();
  4044. }
  4045. }
  4046. TEST_F(ServerTest, GetWithRange1) {
  4047. auto res = cli_.Get("/with-range", {
  4048. make_range_header({{3, 5}}),
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("def"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetWithRange2) {
  4059. auto res = cli_.Get("/with-range", {
  4060. make_range_header({{1, -1}}),
  4061. {"Accept-Encoding", ""},
  4062. });
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4068. EXPECT_EQ(std::string("bcdefg"), res->body);
  4069. }
  4070. TEST_F(ServerTest, GetWithRange3) {
  4071. auto res = cli_.Get("/with-range", {
  4072. make_range_header({{0, 0}}),
  4073. {"Accept-Encoding", ""},
  4074. });
  4075. ASSERT_TRUE(res);
  4076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4077. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4078. EXPECT_EQ(true, res->has_header("Content-Range"));
  4079. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4080. EXPECT_EQ(std::string("a"), res->body);
  4081. }
  4082. TEST_F(ServerTest, GetWithRange4) {
  4083. auto res = cli_.Get("/with-range", {
  4084. make_range_header({{-1, 2}}),
  4085. {"Accept-Encoding", ""},
  4086. });
  4087. ASSERT_TRUE(res);
  4088. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4089. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4090. EXPECT_EQ(true, res->has_header("Content-Range"));
  4091. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4092. EXPECT_EQ(std::string("fg"), res->body);
  4093. }
  4094. TEST_F(ServerTest, GetWithRange5) {
  4095. auto res = cli_.Get("/with-range", {
  4096. make_range_header({{0, 5}}),
  4097. {"Accept-Encoding", ""},
  4098. });
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("abcdef"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4107. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4108. ASSERT_TRUE(res);
  4109. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4110. }
  4111. TEST_F(ServerTest, GetWithRangeMultipart) {
  4112. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4113. ASSERT_TRUE(res);
  4114. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4115. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4116. EXPECT_EQ(false, res->has_header("Content-Range"));
  4117. EXPECT_EQ(267U, res->body.size());
  4118. }
  4119. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4120. auto res =
  4121. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4122. ASSERT_TRUE(res);
  4123. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4124. }
  4125. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4126. auto res = cli_.Get("/with-range-customized-response",
  4127. {{make_range_header({{1, 2}})}});
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4130. EXPECT_EQ(true, res->has_header("Content-Length"));
  4131. EXPECT_EQ(false, res->has_header("Content-Range"));
  4132. EXPECT_EQ(JSON_DATA, res->body);
  4133. }
  4134. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4135. auto res = cli_.Get("/with-range-customized-response",
  4136. {{make_range_header({{1, 2}, {4, 5}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4139. EXPECT_EQ(true, res->has_header("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(JSON_DATA, res->body);
  4142. }
  4143. TEST_F(ServerTest, Issue1772) {
  4144. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4147. }
  4148. TEST_F(ServerTest, Issue609) {
  4149. auto res = cli_.Delete("/issue609");
  4150. ASSERT_TRUE(res);
  4151. EXPECT_EQ(StatusCode::OK_200, res->status);
  4152. EXPECT_EQ(std::string("ok"), res->body);
  4153. }
  4154. TEST_F(ServerTest, GetStreamedChunked) {
  4155. auto res = cli_.Get("/streamed-chunked");
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::OK_200, res->status);
  4158. EXPECT_EQ(std::string("123456789"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetStreamedChunked2) {
  4161. auto res = cli_.Get("/streamed-chunked2");
  4162. ASSERT_TRUE(res);
  4163. EXPECT_EQ(StatusCode::OK_200, res->status);
  4164. EXPECT_EQ(std::string("123456789"), res->body);
  4165. }
  4166. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4167. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4168. ASSERT_TRUE(res);
  4169. EXPECT_EQ(StatusCode::OK_200, res->status);
  4170. EXPECT_EQ(std::string("123456789"), res->body);
  4171. EXPECT_TRUE(res->has_header("Trailer"));
  4172. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4173. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4174. // Trailers are now stored separately from headers (security fix)
  4175. EXPECT_EQ(2U, res->trailers.size());
  4176. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4177. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4178. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4179. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4180. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4181. // Verify trailers are NOT in headers (security verification)
  4182. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4183. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4184. }
  4185. TEST_F(ServerTest, LargeChunkedPost) {
  4186. Request req;
  4187. req.method = "POST";
  4188. req.path = "/large-chunked";
  4189. std::string host_and_port;
  4190. host_and_port += HOST;
  4191. host_and_port += ":";
  4192. host_and_port += std::to_string(PORT);
  4193. req.headers.emplace("Host", host_and_port.c_str());
  4194. req.headers.emplace("Accept", "*/*");
  4195. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4196. req.headers.emplace("Content-Type", "text/plain");
  4197. req.headers.emplace("Content-Length", "0");
  4198. req.headers.emplace("Transfer-Encoding", "chunked");
  4199. std::string long_string(30 * 1024u, 'a');
  4200. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4201. // Attempt to make a large enough post to exceed OS buffers, to test that
  4202. // the server handles short reads if the full chunk data isn't available.
  4203. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4204. auto res = std::make_shared<Response>();
  4205. auto error = Error::Success;
  4206. auto ret = cli_.send(req, *res, error);
  4207. ASSERT_TRUE(ret);
  4208. EXPECT_EQ(StatusCode::OK_200, res->status);
  4209. }
  4210. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4211. auto res = cli_.Get("/remote_addr");
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::OK_200, res->status);
  4214. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4215. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4216. }
  4217. TEST_F(ServerTest, GetMethodLocalAddr) {
  4218. auto res = cli_.Get("/local_addr");
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::OK_200, res->status);
  4221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4222. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4223. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4224. }
  4225. TEST_F(ServerTest, HTTPResponseSplitting) {
  4226. auto res = cli_.Get("/http_response_splitting");
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. }
  4230. TEST_F(ServerTest, SlowRequest) {
  4231. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4232. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4233. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4234. }
  4235. #if 0
  4236. TEST_F(ServerTest, SlowPost) {
  4237. char buffer[64 * 1024];
  4238. memset(buffer, 0x42, sizeof(buffer));
  4239. auto res = cli_.Post(
  4240. "/slowpost", 64 * 1024 * 1024,
  4241. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4242. auto ret = sink.write(buffer, sizeof(buffer));
  4243. EXPECT_TRUE(ret);
  4244. return true;
  4245. },
  4246. "text/plain");
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(StatusCode::OK_200, res->status);
  4249. }
  4250. TEST_F(ServerTest, SlowPostFail) {
  4251. char buffer[64 * 1024];
  4252. memset(buffer, 0x42, sizeof(buffer));
  4253. cli_.set_write_timeout(std::chrono::seconds(0));
  4254. auto res = cli_.Post(
  4255. "/slowpost", 64 * 1024 * 1024,
  4256. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4257. sink.write(buffer, sizeof(buffer));
  4258. return true;
  4259. },
  4260. "text/plain");
  4261. ASSERT_TRUE(!res);
  4262. EXPECT_EQ(Error::Write, res.error());
  4263. }
  4264. #endif
  4265. TEST_F(ServerTest, Put) {
  4266. auto res = cli_.Put("/put", "PUT", "text/plain");
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::OK_200, res->status);
  4269. EXPECT_EQ("PUT", res->body);
  4270. }
  4271. TEST_F(ServerTest, PutWithContentProvider) {
  4272. auto res = cli_.Put(
  4273. "/put", 3,
  4274. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4275. sink.os << "PUT";
  4276. return true;
  4277. },
  4278. "text/plain");
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::OK_200, res->status);
  4281. EXPECT_EQ("PUT", res->body);
  4282. }
  4283. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4284. auto res = cli_.Post(
  4285. "/post", 42,
  4286. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4287. return false;
  4288. },
  4289. "text/plain");
  4290. ASSERT_TRUE(!res);
  4291. EXPECT_EQ(Error::Canceled, res.error());
  4292. }
  4293. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4294. auto res = cli_.Put(
  4295. "/put",
  4296. [](size_t /*offset*/, DataSink &sink) {
  4297. sink.os << "PUT";
  4298. sink.done();
  4299. return true;
  4300. },
  4301. "text/plain");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ("PUT", res->body);
  4305. }
  4306. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4307. auto res = cli_.Post(
  4308. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4309. "text/plain");
  4310. ASSERT_TRUE(!res);
  4311. EXPECT_EQ(Error::Canceled, res.error());
  4312. }
  4313. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4314. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4315. cli_.set_compress(true);
  4316. auto res = cli_.Put(
  4317. "/put", 3,
  4318. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4319. sink.os << "PUT";
  4320. return true;
  4321. },
  4322. "text/plain");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("PUT", res->body);
  4326. }
  4327. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4328. cli_.set_compress(true);
  4329. auto res = cli_.Post(
  4330. "/post", 42,
  4331. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4332. return false;
  4333. },
  4334. "text/plain");
  4335. ASSERT_TRUE(!res);
  4336. EXPECT_EQ(Error::Canceled, res.error());
  4337. }
  4338. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4339. cli_.set_compress(true);
  4340. auto res = cli_.Put(
  4341. "/put",
  4342. [](size_t /*offset*/, DataSink &sink) {
  4343. sink.os << "PUT";
  4344. sink.done();
  4345. return true;
  4346. },
  4347. "text/plain");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("PUT", res->body);
  4351. }
  4352. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4353. cli_.set_compress(true);
  4354. auto res = cli_.Post(
  4355. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4356. "text/plain");
  4357. ASSERT_TRUE(!res);
  4358. EXPECT_EQ(Error::Canceled, res.error());
  4359. }
  4360. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4361. cli_.set_compress(true);
  4362. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4363. ASSERT_TRUE(res);
  4364. EXPECT_EQ(StatusCode::OK_200, res->status);
  4365. EXPECT_EQ(LARGE_DATA, res->body);
  4366. }
  4367. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4368. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4369. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4370. Client cli(s.c_str());
  4371. cli.enable_server_certificate_verification(false);
  4372. #else
  4373. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4374. Client cli(s.c_str());
  4375. #endif
  4376. cli.set_compress(true);
  4377. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4378. ASSERT_TRUE(res);
  4379. EXPECT_EQ(StatusCode::OK_200, res->status);
  4380. EXPECT_EQ(LARGE_DATA, res->body);
  4381. // The compressed size should be less than a 10th of the original. May vary
  4382. // depending on the zlib library.
  4383. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4384. static_cast<uint64_t>(10 * 1024 * 1024));
  4385. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4386. }
  4387. TEST_F(ServerTest, PutContentWithDeflate) {
  4388. cli_.set_compress(false);
  4389. Headers headers;
  4390. headers.emplace("Content-Encoding", "deflate");
  4391. // PUT in deflate format:
  4392. auto res = cli_.Put("/put", headers,
  4393. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("PUT", res->body);
  4397. }
  4398. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4399. Headers headers;
  4400. headers.emplace("Accept-Encoding", "gzip, deflate");
  4401. auto res = cli_.Get("/streamed-chunked", headers);
  4402. ASSERT_TRUE(res);
  4403. EXPECT_EQ(StatusCode::OK_200, res->status);
  4404. EXPECT_EQ(std::string("123456789"), res->body);
  4405. }
  4406. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4407. Headers headers;
  4408. headers.emplace("Accept-Encoding", "gzip, deflate");
  4409. auto res = cli_.Get("/streamed-chunked2", headers);
  4410. ASSERT_TRUE(res);
  4411. EXPECT_EQ(StatusCode::OK_200, res->status);
  4412. EXPECT_EQ(std::string("123456789"), res->body);
  4413. }
  4414. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4415. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. }
  4419. TEST(GzipDecompressor, ChunkedDecompression) {
  4420. std::string data;
  4421. for (size_t i = 0; i < 32 * 1024; ++i) {
  4422. data.push_back(static_cast<char>('a' + i % 26));
  4423. }
  4424. std::string compressed_data;
  4425. {
  4426. httplib::detail::gzip_compressor compressor;
  4427. bool result = compressor.compress(
  4428. data.data(), data.size(),
  4429. /*last=*/true,
  4430. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4431. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4432. compressed_data_size);
  4433. return true;
  4434. });
  4435. ASSERT_TRUE(result);
  4436. }
  4437. std::string decompressed_data;
  4438. {
  4439. httplib::detail::gzip_decompressor decompressor;
  4440. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4441. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4442. size_t chunk_size = 130;
  4443. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4444. chunk_begin += chunk_size) {
  4445. size_t current_chunk_size =
  4446. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4447. bool result = decompressor.decompress(
  4448. compressed_data.data() + chunk_begin, current_chunk_size,
  4449. [&](const char *decompressed_data_chunk,
  4450. size_t decompressed_data_chunk_size) {
  4451. decompressed_data.insert(decompressed_data.size(),
  4452. decompressed_data_chunk,
  4453. decompressed_data_chunk_size);
  4454. return true;
  4455. });
  4456. ASSERT_TRUE(result);
  4457. }
  4458. }
  4459. ASSERT_EQ(data, decompressed_data);
  4460. }
  4461. TEST(GzipDecompressor, DeflateDecompression) {
  4462. std::string original_text = "Raw deflate without gzip";
  4463. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4464. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4465. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4466. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4467. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4468. std::string decompressed_data;
  4469. {
  4470. httplib::detail::gzip_decompressor decompressor;
  4471. bool result = decompressor.decompress(
  4472. compressed_data.data(), compressed_data.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. ASSERT_EQ(original_text, decompressed_data);
  4483. }
  4484. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4485. std::string original_text = "Raw deflate without gzip";
  4486. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4487. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4488. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4489. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4490. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  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. #ifdef _WIN32
  4509. TEST(GzipDecompressor, LargeRandomData) {
  4510. // prepare large random data that is difficult to be compressed and is
  4511. // expected to have large size even when compressed
  4512. std::random_device seed_gen;
  4513. std::mt19937 random(seed_gen());
  4514. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4515. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4516. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4517. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4518. // compress data over 4GiB
  4519. std::string compressed_data;
  4520. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4521. httplib::detail::gzip_compressor compressor;
  4522. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4523. data.size() * sizeof(std::uint32_t), true,
  4524. [&](const char *data, size_t size) {
  4525. compressed_data.insert(
  4526. compressed_data.size(), data, size);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(result);
  4530. // FIXME: compressed data size is expected to be greater than 4GiB,
  4531. // but there is no guarantee
  4532. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4533. // decompress data over 4GiB
  4534. std::string decompressed_data;
  4535. decompressed_data.reserve(data_size);
  4536. httplib::detail::gzip_decompressor decompressor;
  4537. result = decompressor.decompress(
  4538. compressed_data.data(), compressed_data.size(),
  4539. [&](const char *data, size_t size) {
  4540. decompressed_data.insert(decompressed_data.size(), data, size);
  4541. return true;
  4542. });
  4543. ASSERT_TRUE(result);
  4544. // compare
  4545. ASSERT_EQ(data_size, decompressed_data.size());
  4546. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4547. 0);
  4548. }
  4549. #endif
  4550. #endif
  4551. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4552. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4553. Headers headers;
  4554. headers.emplace("Accept-Encoding", "br");
  4555. auto res = cli_.Get("/streamed-chunked", headers);
  4556. ASSERT_TRUE(res);
  4557. EXPECT_EQ(StatusCode::OK_200, res->status);
  4558. EXPECT_EQ(std::string("123456789"), res->body);
  4559. }
  4560. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4561. Headers headers;
  4562. headers.emplace("Accept-Encoding", "br");
  4563. auto res = cli_.Get("/streamed-chunked2", headers);
  4564. ASSERT_TRUE(res);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. EXPECT_EQ(std::string("123456789"), res->body);
  4567. }
  4568. #endif
  4569. TEST_F(ServerTest, Patch) {
  4570. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4571. ASSERT_TRUE(res);
  4572. EXPECT_EQ(StatusCode::OK_200, res->status);
  4573. EXPECT_EQ("PATCH", res->body);
  4574. }
  4575. TEST_F(ServerTest, Delete) {
  4576. auto res = cli_.Delete("/delete");
  4577. ASSERT_TRUE(res);
  4578. EXPECT_EQ(StatusCode::OK_200, res->status);
  4579. EXPECT_EQ("DELETE", res->body);
  4580. }
  4581. TEST_F(ServerTest, DeleteContentReceiver) {
  4582. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ("content", res->body);
  4586. }
  4587. TEST_F(ServerTest, Options) {
  4588. auto res = cli_.Options("*");
  4589. ASSERT_TRUE(res);
  4590. EXPECT_EQ(StatusCode::OK_200, res->status);
  4591. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4592. EXPECT_TRUE(res->body.empty());
  4593. }
  4594. TEST_F(ServerTest, URL) {
  4595. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4596. ASSERT_TRUE(res);
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. }
  4599. TEST_F(ServerTest, ArrayParam) {
  4600. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4601. ASSERT_TRUE(res);
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. }
  4604. TEST_F(ServerTest, NoMultipleHeaders) {
  4605. Headers headers = {{"Content-Length", "5"}};
  4606. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4607. "text/plain");
  4608. ASSERT_TRUE(res);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. TEST_F(ServerTest, PostContentReceiver) {
  4612. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4613. ASSERT_TRUE(res);
  4614. ASSERT_EQ(StatusCode::OK_200, res->status);
  4615. ASSERT_EQ("content", res->body);
  4616. }
  4617. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4618. UploadFormDataItems items = {
  4619. {"text1", "text default", "", ""},
  4620. {"text2", "aωb", "", ""},
  4621. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4622. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4623. {"file3", "", "", "application/octet-stream"},
  4624. };
  4625. auto res = cli_.Post("/content_receiver", items);
  4626. ASSERT_TRUE(res);
  4627. EXPECT_EQ(StatusCode::OK_200, res->status);
  4628. }
  4629. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4630. UploadFormDataItems items = {
  4631. {"text1", "text default", "", ""},
  4632. {"text2", "aωb", "", ""},
  4633. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4634. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4635. {"file3", "", "", "application/octet-stream"},
  4636. };
  4637. auto boundary = std::string("+++++");
  4638. std::string body;
  4639. for (const auto &item : items) {
  4640. body += "--" + boundary + "\r\n";
  4641. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4642. if (!item.filename.empty()) {
  4643. body += "; filename=\"" + item.filename + "\"";
  4644. }
  4645. body += "\r\n";
  4646. if (!item.content_type.empty()) {
  4647. body += "Content-Type: " + item.content_type + "\r\n";
  4648. }
  4649. body += "\r\n";
  4650. body += item.content + "\r\n";
  4651. }
  4652. body += "--" + boundary + "--\r\n";
  4653. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4654. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4655. ASSERT_TRUE(res);
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. }
  4658. TEST_F(ServerTest, PostContentReceiverGzip) {
  4659. cli_.set_compress(true);
  4660. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4661. ASSERT_TRUE(res);
  4662. ASSERT_EQ(StatusCode::OK_200, res->status);
  4663. ASSERT_EQ("content", res->body);
  4664. }
  4665. TEST_F(ServerTest, PutContentReceiver) {
  4666. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4667. ASSERT_TRUE(res);
  4668. ASSERT_EQ(StatusCode::OK_200, res->status);
  4669. ASSERT_EQ("content", res->body);
  4670. }
  4671. TEST_F(ServerTest, PatchContentReceiver) {
  4672. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4673. ASSERT_TRUE(res);
  4674. ASSERT_EQ(StatusCode::OK_200, res->status);
  4675. ASSERT_EQ("content", res->body);
  4676. }
  4677. template <typename ClientType>
  4678. void TestWithHeadersAndContentReceiver(
  4679. ClientType &cli,
  4680. std::function<Result(ClientType &, const std::string &, const Headers &,
  4681. const std::string &, const std::string &,
  4682. ContentReceiver, DownloadProgress)>
  4683. request_func) {
  4684. Headers headers;
  4685. headers.emplace("X-Custom-Header", "test-value");
  4686. std::string received_body;
  4687. auto res = request_func(
  4688. cli, "/content_receiver", headers, "content", "application/json",
  4689. [&](const char *data, size_t data_length) {
  4690. received_body.append(data, data_length);
  4691. return true;
  4692. },
  4693. nullptr);
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ("content", received_body);
  4697. }
  4698. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4699. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4700. using ClientT = SSLClient;
  4701. #else
  4702. using ClientT = Client;
  4703. #endif
  4704. TestWithHeadersAndContentReceiver<ClientT>(
  4705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4706. const std::string &body, const std::string &content_type,
  4707. ContentReceiver receiver, DownloadProgress progress) {
  4708. return cli.Post(path, headers, body, content_type, receiver, progress);
  4709. });
  4710. }
  4711. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4712. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4713. using ClientT = SSLClient;
  4714. #else
  4715. using ClientT = Client;
  4716. #endif
  4717. TestWithHeadersAndContentReceiver<ClientT>(
  4718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4719. const std::string &body, const std::string &content_type,
  4720. ContentReceiver receiver, DownloadProgress progress) {
  4721. return cli.Put(path, headers, body, content_type, receiver, progress);
  4722. });
  4723. }
  4724. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4726. using ClientT = SSLClient;
  4727. #else
  4728. using ClientT = Client;
  4729. #endif
  4730. TestWithHeadersAndContentReceiver<ClientT>(
  4731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4732. const std::string &body, const std::string &content_type,
  4733. ContentReceiver receiver, DownloadProgress progress) {
  4734. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4735. });
  4736. }
  4737. template <typename ClientType>
  4738. void TestWithHeadersAndContentReceiverWithProgress(
  4739. ClientType &cli,
  4740. std::function<Result(ClientType &, const std::string &, const Headers &,
  4741. const std::string &, const std::string &,
  4742. ContentReceiver, DownloadProgress)>
  4743. request_func) {
  4744. Headers headers;
  4745. headers.emplace("X-Test-Header", "progress-test");
  4746. std::string received_body;
  4747. auto progress_called = false;
  4748. auto res = request_func(
  4749. cli, "/content_receiver", headers, "content", "text/plain",
  4750. [&](const char *data, size_t data_length) {
  4751. received_body.append(data, data_length);
  4752. return true;
  4753. },
  4754. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4755. progress_called = true;
  4756. return true;
  4757. });
  4758. ASSERT_TRUE(res);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. EXPECT_EQ("content", received_body);
  4761. EXPECT_TRUE(progress_called);
  4762. }
  4763. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4765. using ClientT = SSLClient;
  4766. #else
  4767. using ClientT = Client;
  4768. #endif
  4769. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4770. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4771. const std::string &body, const std::string &content_type,
  4772. ContentReceiver receiver, DownloadProgress progress) {
  4773. return cli.Post(path, headers, body, content_type, receiver, progress);
  4774. });
  4775. }
  4776. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4777. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4778. using ClientT = SSLClient;
  4779. #else
  4780. using ClientT = Client;
  4781. #endif
  4782. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4783. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4784. const std::string &body, const std::string &content_type,
  4785. ContentReceiver receiver, DownloadProgress progress) {
  4786. return cli.Put(path, headers, body, content_type, receiver, progress);
  4787. });
  4788. }
  4789. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4791. using ClientT = SSLClient;
  4792. #else
  4793. using ClientT = Client;
  4794. #endif
  4795. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4796. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4797. const std::string &body, const std::string &content_type,
  4798. ContentReceiver receiver, DownloadProgress progress) {
  4799. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4800. });
  4801. }
  4802. template <typename ClientType>
  4803. void TestWithHeadersAndContentReceiverError(
  4804. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4805. const Headers &, const std::string &,
  4806. const std::string &, ContentReceiver)>
  4807. request_func) {
  4808. Headers headers;
  4809. headers.emplace("X-Error-Test", "true");
  4810. std::string received_body;
  4811. auto receiver_failed = false;
  4812. auto res =
  4813. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4814. [&](const char *data, size_t data_length) {
  4815. received_body.append(data, data_length);
  4816. receiver_failed = true;
  4817. return false;
  4818. });
  4819. ASSERT_FALSE(res);
  4820. EXPECT_TRUE(receiver_failed);
  4821. }
  4822. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4823. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4824. using ClientT = SSLClient;
  4825. #else
  4826. using ClientT = Client;
  4827. #endif
  4828. TestWithHeadersAndContentReceiverError<ClientT>(
  4829. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4830. const std::string &body, const std::string &content_type,
  4831. ContentReceiver receiver) {
  4832. return cli.Post(path, headers, body, content_type, receiver);
  4833. });
  4834. }
  4835. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4837. using ClientT = SSLClient;
  4838. #else
  4839. using ClientT = Client;
  4840. #endif
  4841. TestWithHeadersAndContentReceiverError<ClientT>(
  4842. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4843. const std::string &body, const std::string &content_type,
  4844. ContentReceiver receiver) {
  4845. return cli.Put(path, headers, body, content_type, receiver);
  4846. });
  4847. }
  4848. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4849. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4850. using ClientT = SSLClient;
  4851. #else
  4852. using ClientT = Client;
  4853. #endif
  4854. TestWithHeadersAndContentReceiverError<ClientT>(
  4855. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4856. const std::string &body, const std::string &content_type,
  4857. ContentReceiver receiver) {
  4858. return cli.Patch(path, headers, body, content_type, receiver);
  4859. });
  4860. }
  4861. TEST_F(ServerTest, PostQueryStringAndBody) {
  4862. auto res =
  4863. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4864. ASSERT_TRUE(res);
  4865. ASSERT_EQ(StatusCode::OK_200, res->status);
  4866. }
  4867. TEST_F(ServerTest, HTTP2Magic) {
  4868. Request req;
  4869. req.method = "PRI";
  4870. req.path = "*";
  4871. req.body = "SM";
  4872. auto res = std::make_shared<Response>();
  4873. auto error = Error::Success;
  4874. auto ret = cli_.send(req, *res, error);
  4875. ASSERT_TRUE(ret);
  4876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4877. }
  4878. TEST_F(ServerTest, KeepAlive) {
  4879. auto res = cli_.Get("/hi");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4883. EXPECT_EQ("Hello World!", res->body);
  4884. res = cli_.Get("/hi");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4888. EXPECT_EQ("Hello World!", res->body);
  4889. res = cli_.Get("/hi");
  4890. ASSERT_TRUE(res);
  4891. EXPECT_EQ(StatusCode::OK_200, res->status);
  4892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4893. EXPECT_EQ("Hello World!", res->body);
  4894. res = cli_.Get("/not-exist");
  4895. ASSERT_TRUE(res);
  4896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4897. res = cli_.Post("/empty", "", "text/plain");
  4898. ASSERT_TRUE(res);
  4899. EXPECT_EQ(StatusCode::OK_200, res->status);
  4900. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4901. EXPECT_EQ("empty", res->body);
  4902. EXPECT_EQ("close", res->get_header_value("Connection"));
  4903. res = cli_.Post(
  4904. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4905. "text/plain");
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("empty", res->body);
  4910. cli_.set_keep_alive(false);
  4911. res = cli_.Get("/last-request");
  4912. ASSERT_TRUE(res);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. EXPECT_EQ("close", res->get_header_value("Connection"));
  4915. }
  4916. TEST_F(ServerTest, TooManyRedirect) {
  4917. cli_.set_follow_location(true);
  4918. auto res = cli_.Get("/redirect/0");
  4919. ASSERT_TRUE(!res);
  4920. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4921. }
  4922. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4924. TEST_F(ServerTest, Gzip) {
  4925. Headers headers;
  4926. headers.emplace("Accept-Encoding", "gzip, deflate");
  4927. auto res = cli_.Get("/compress", headers);
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4933. "7890123456789012345678901234567890",
  4934. res->body);
  4935. EXPECT_EQ(StatusCode::OK_200, res->status);
  4936. }
  4937. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4938. Headers headers;
  4939. headers.emplace("Accept-Encoding", "");
  4940. auto res = cli_.Get("/compress", headers);
  4941. ASSERT_TRUE(res);
  4942. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4944. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4946. "7890123456789012345678901234567890",
  4947. res->body);
  4948. EXPECT_EQ(StatusCode::OK_200, res->status);
  4949. }
  4950. TEST_F(ServerTest, GzipWithContentReceiver) {
  4951. Headers headers;
  4952. headers.emplace("Accept-Encoding", "gzip, deflate");
  4953. std::string body;
  4954. auto res = cli_.Get("/compress", headers,
  4955. [&](const char *data, uint64_t data_length) {
  4956. EXPECT_EQ(100U, data_length);
  4957. body.append(data, data_length);
  4958. return true;
  4959. });
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4962. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4963. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4964. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4965. "7890123456789012345678901234567890",
  4966. body);
  4967. EXPECT_EQ(StatusCode::OK_200, res->status);
  4968. }
  4969. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4970. Headers headers;
  4971. headers.emplace("Accept-Encoding", "gzip, deflate");
  4972. cli_.set_decompress(false);
  4973. auto res = cli_.Get("/compress", headers);
  4974. ASSERT_TRUE(res);
  4975. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4977. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4978. EXPECT_EQ(33U, res->body.size());
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. }
  4981. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4982. Headers headers;
  4983. headers.emplace("Accept-Encoding", "");
  4984. std::string body;
  4985. auto res = cli_.Get("/compress", headers,
  4986. [&](const char *data, uint64_t data_length) {
  4987. EXPECT_EQ(100U, data_length);
  4988. body.append(data, data_length);
  4989. return true;
  4990. });
  4991. ASSERT_TRUE(res);
  4992. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4994. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4996. "7890123456789012345678901234567890",
  4997. body);
  4998. EXPECT_EQ(StatusCode::OK_200, res->status);
  4999. }
  5000. TEST_F(ServerTest, NoGzip) {
  5001. Headers headers;
  5002. headers.emplace("Accept-Encoding", "gzip, deflate");
  5003. auto res = cli_.Get("/nocompress", headers);
  5004. ASSERT_TRUE(res);
  5005. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5006. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5007. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5009. "7890123456789012345678901234567890",
  5010. res->body);
  5011. EXPECT_EQ(StatusCode::OK_200, res->status);
  5012. }
  5013. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5014. Headers headers;
  5015. headers.emplace("Accept-Encoding", "gzip, deflate");
  5016. std::string body;
  5017. auto res = cli_.Get("/nocompress", headers,
  5018. [&](const char *data, uint64_t data_length) {
  5019. EXPECT_EQ(100U, data_length);
  5020. body.append(data, data_length);
  5021. return true;
  5022. });
  5023. ASSERT_TRUE(res);
  5024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5028. "7890123456789012345678901234567890",
  5029. body);
  5030. EXPECT_EQ(StatusCode::OK_200, res->status);
  5031. }
  5032. TEST_F(ServerTest, MultipartFormDataGzip) {
  5033. UploadFormDataItems items = {
  5034. {"key1", "test", "", ""},
  5035. {"key2", "--abcdefg123", "", ""},
  5036. };
  5037. cli_.set_compress(true);
  5038. auto res = cli_.Post("/compress-multipart", items);
  5039. ASSERT_TRUE(res);
  5040. EXPECT_EQ(StatusCode::OK_200, res->status);
  5041. }
  5042. #endif
  5043. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5044. TEST_F(ServerTest, Brotli) {
  5045. Headers headers;
  5046. headers.emplace("Accept-Encoding", "br");
  5047. auto res = cli_.Get("/compress", headers);
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5053. "7890123456789012345678901234567890",
  5054. res->body);
  5055. EXPECT_EQ(StatusCode::OK_200, res->status);
  5056. }
  5057. #endif
  5058. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5059. TEST_F(ServerTest, Zstd) {
  5060. Headers headers;
  5061. headers.emplace("Accept-Encoding", "zstd");
  5062. auto res = cli_.Get("/compress", headers);
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5068. "7890123456789012345678901234567890",
  5069. res->body);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5073. Headers headers;
  5074. headers.emplace("Accept-Encoding", "");
  5075. auto res = cli_.Get("/compress", headers);
  5076. ASSERT_TRUE(res);
  5077. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5079. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5080. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5081. "7890123456789012345678901234567890",
  5082. res->body);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. }
  5085. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5086. Headers headers;
  5087. headers.emplace("Accept-Encoding", "zstd");
  5088. std::string body;
  5089. auto res = cli_.Get("/compress", headers,
  5090. [&](const char *data, uint64_t data_length) {
  5091. EXPECT_EQ(100U, data_length);
  5092. body.append(data, data_length);
  5093. return true;
  5094. });
  5095. ASSERT_TRUE(res);
  5096. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5098. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5100. "7890123456789012345678901234567890",
  5101. body);
  5102. EXPECT_EQ(StatusCode::OK_200, res->status);
  5103. }
  5104. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5105. Headers headers;
  5106. headers.emplace("Accept-Encoding", "zstd");
  5107. cli_.set_decompress(false);
  5108. auto res = cli_.Get("/compress", headers);
  5109. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5110. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5111. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5112. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5113. ASSERT_TRUE(res);
  5114. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5116. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. ASSERT_EQ(26U, res->body.size());
  5119. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5120. 0);
  5121. }
  5122. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5123. Headers headers;
  5124. headers.emplace("Accept-Encoding", "");
  5125. std::string body;
  5126. auto res = cli_.Get("/compress", headers,
  5127. [&](const char *data, uint64_t data_length) {
  5128. EXPECT_EQ(100U, data_length);
  5129. body.append(data, data_length);
  5130. return true;
  5131. });
  5132. ASSERT_TRUE(res);
  5133. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5135. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5136. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5137. "7890123456789012345678901234567890",
  5138. body);
  5139. EXPECT_EQ(StatusCode::OK_200, res->status);
  5140. }
  5141. TEST_F(ServerTest, NoZstd) {
  5142. Headers headers;
  5143. headers.emplace("Accept-Encoding", "zstd");
  5144. auto res = cli_.Get("/nocompress", headers);
  5145. ASSERT_TRUE(res);
  5146. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5147. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5148. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5149. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5150. "7890123456789012345678901234567890",
  5151. res->body);
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. }
  5154. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5155. Headers headers;
  5156. headers.emplace("Accept-Encoding", "zstd");
  5157. std::string body;
  5158. auto res = cli_.Get("/nocompress", headers,
  5159. [&](const char *data, uint64_t data_length) {
  5160. EXPECT_EQ(100U, data_length);
  5161. body.append(data, data_length);
  5162. return true;
  5163. });
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5166. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. // TODO: How to enable zstd ??
  5174. TEST_F(ServerTest, MultipartFormDataZstd) {
  5175. UploadFormDataItems items = {
  5176. {"key1", "test", "", ""},
  5177. {"key2", "--abcdefg123", "", ""},
  5178. };
  5179. Headers headers;
  5180. headers.emplace("Accept-Encoding", "zstd");
  5181. cli_.set_compress(true);
  5182. auto res = cli_.Post("/compress-multipart", headers, items);
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ(StatusCode::OK_200, res->status);
  5185. }
  5186. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5187. Headers headers;
  5188. headers.emplace("Accept-Encoding", "zstd");
  5189. cli_.set_compress(true);
  5190. auto res = cli_.Put(
  5191. "/put", headers, 3,
  5192. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5193. sink.os << "PUT";
  5194. return true;
  5195. },
  5196. "text/plain");
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. EXPECT_EQ("PUT", res->body);
  5200. }
  5201. // Pre-compression logging tests
  5202. TEST_F(ServerTest, PreCompressionLogging) {
  5203. // Test data for compression (matches the actual /compress endpoint content)
  5204. const std::string test_content =
  5205. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5206. "3456789012345678901234567890";
  5207. // Variables to capture logging data
  5208. std::string pre_compression_body;
  5209. std::string pre_compression_content_type;
  5210. std::string pre_compression_content_encoding;
  5211. std::string post_compression_body;
  5212. std::string post_compression_content_type;
  5213. std::string post_compression_content_encoding;
  5214. // Set up pre-compression logger
  5215. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5216. const Response &res) {
  5217. pre_compression_body = res.body;
  5218. pre_compression_content_type = res.get_header_value("Content-Type");
  5219. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5220. });
  5221. // Set up post-compression logger
  5222. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5223. post_compression_body = res.body;
  5224. post_compression_content_type = res.get_header_value("Content-Type");
  5225. post_compression_content_encoding =
  5226. res.get_header_value("Content-Encoding");
  5227. });
  5228. // Test with gzip compression
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "gzip");
  5231. auto res = cli_.Get("/compress", headers);
  5232. // Verify response was compressed
  5233. ASSERT_TRUE(res);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5236. // Verify pre-compression logger captured uncompressed content
  5237. EXPECT_EQ(test_content, pre_compression_body);
  5238. EXPECT_EQ("text/plain", pre_compression_content_type);
  5239. EXPECT_TRUE(pre_compression_content_encoding
  5240. .empty()); // No encoding header before compression
  5241. // Verify post-compression logger captured compressed content
  5242. EXPECT_NE(test_content,
  5243. post_compression_body); // Should be different after compression
  5244. EXPECT_EQ("text/plain", post_compression_content_type);
  5245. EXPECT_EQ("gzip", post_compression_content_encoding);
  5246. // Verify compressed content is smaller
  5247. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5248. }
  5249. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5250. const std::string test_content =
  5251. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5252. "3456789012345678901234567890";
  5253. std::string pre_compression_body;
  5254. std::string post_compression_body;
  5255. svr_.set_pre_compression_logger(
  5256. [&](const Request & /*req*/, const Response &res) {
  5257. pre_compression_body = res.body;
  5258. });
  5259. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5260. post_compression_body = res.body;
  5261. });
  5262. Headers headers;
  5263. headers.emplace("Accept-Encoding", "br");
  5264. auto res = cli_.Get("/compress", headers);
  5265. ASSERT_TRUE(res);
  5266. EXPECT_EQ(StatusCode::OK_200, res->status);
  5267. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5268. // Verify pre-compression content is uncompressed
  5269. EXPECT_EQ(test_content, pre_compression_body);
  5270. // Verify post-compression content is compressed
  5271. EXPECT_NE(test_content, post_compression_body);
  5272. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5273. }
  5274. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5275. const std::string test_content =
  5276. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5277. "3456789012345678901234567890";
  5278. std::string pre_compression_body;
  5279. std::string post_compression_body;
  5280. svr_.set_pre_compression_logger(
  5281. [&](const Request & /*req*/, const Response &res) {
  5282. pre_compression_body = res.body;
  5283. });
  5284. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5285. post_compression_body = res.body;
  5286. });
  5287. // Request without compression (use /nocompress endpoint)
  5288. Headers headers;
  5289. auto res = cli_.Get("/nocompress", headers);
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5293. // Pre-compression logger should not be called when no compression is applied
  5294. EXPECT_TRUE(
  5295. pre_compression_body.empty()); // Pre-compression logger not called
  5296. EXPECT_EQ(
  5297. test_content,
  5298. post_compression_body); // Post-compression logger captures final content
  5299. }
  5300. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5301. const std::string test_content =
  5302. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5303. "3456789012345678901234567890";
  5304. std::string pre_compression_body;
  5305. bool pre_logger_called = false;
  5306. // Set only pre-compression logger
  5307. svr_.set_pre_compression_logger(
  5308. [&](const Request & /*req*/, const Response &res) {
  5309. pre_compression_body = res.body;
  5310. pre_logger_called = true;
  5311. });
  5312. Headers headers;
  5313. headers.emplace("Accept-Encoding", "gzip");
  5314. auto res = cli_.Get("/compress", headers);
  5315. ASSERT_TRUE(res);
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5318. // Verify pre-compression logger was called
  5319. EXPECT_TRUE(pre_logger_called);
  5320. EXPECT_EQ(test_content, pre_compression_body);
  5321. }
  5322. TEST(ZstdDecompressor, ChunkedDecompression) {
  5323. std::string data;
  5324. for (size_t i = 0; i < 32 * 1024; ++i) {
  5325. data.push_back(static_cast<char>('a' + i % 26));
  5326. }
  5327. std::string compressed_data;
  5328. {
  5329. httplib::detail::zstd_compressor compressor;
  5330. bool result = compressor.compress(
  5331. data.data(), data.size(),
  5332. /*last=*/true,
  5333. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5334. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5335. compressed_data_size);
  5336. return true;
  5337. });
  5338. ASSERT_TRUE(result);
  5339. }
  5340. std::string decompressed_data;
  5341. {
  5342. httplib::detail::zstd_decompressor decompressor;
  5343. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5344. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5345. size_t chunk_size = 130;
  5346. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5347. chunk_begin += chunk_size) {
  5348. size_t current_chunk_size =
  5349. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5350. bool result = decompressor.decompress(
  5351. compressed_data.data() + chunk_begin, current_chunk_size,
  5352. [&](const char *decompressed_data_chunk,
  5353. size_t decompressed_data_chunk_size) {
  5354. decompressed_data.insert(decompressed_data.size(),
  5355. decompressed_data_chunk,
  5356. decompressed_data_chunk_size);
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(result);
  5360. }
  5361. }
  5362. ASSERT_EQ(data, decompressed_data);
  5363. }
  5364. TEST(ZstdDecompressor, Decompress) {
  5365. std::string original_text = "Compressed with ZSTD";
  5366. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5367. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5368. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5369. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5370. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5371. std::string decompressed_data;
  5372. {
  5373. httplib::detail::zstd_decompressor decompressor;
  5374. bool result = decompressor.decompress(
  5375. compressed_data.data(), compressed_data.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. ASSERT_EQ(original_text, decompressed_data);
  5386. }
  5387. #endif
  5388. // Sends a raw request to a server listening at HOST:PORT.
  5389. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5390. std::string *resp = nullptr) {
  5391. auto error = Error::Success;
  5392. auto client_sock = detail::create_client_socket(
  5393. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5394. /*connection_timeout_sec=*/5, 0,
  5395. /*read_timeout_sec=*/5, 0,
  5396. /*write_timeout_sec=*/5, 0, std::string(), error);
  5397. if (client_sock == INVALID_SOCKET) { return false; }
  5398. auto ret = detail::process_client_socket(
  5399. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5400. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5401. if (req.size() !=
  5402. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5403. return false;
  5404. }
  5405. char buf[512];
  5406. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5407. while (line_reader.getline()) {
  5408. if (resp) { *resp += line_reader.ptr(); }
  5409. }
  5410. return true;
  5411. });
  5412. detail::close_socket(client_sock);
  5413. return ret;
  5414. }
  5415. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5416. Server svr;
  5417. std::string header_value;
  5418. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5419. header_value = req.get_header_value("foo");
  5420. res.set_content("ok", "text/plain");
  5421. });
  5422. thread t = thread([&] { svr.listen(HOST, PORT); });
  5423. auto se = detail::scope_exit([&] {
  5424. svr.stop();
  5425. t.join();
  5426. ASSERT_FALSE(svr.is_running());
  5427. });
  5428. svr.wait_until_ready();
  5429. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5430. // like characters are not treated the same - use vertical tab and escape.
  5431. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5432. "foo: \t \v bar \x1B\t \r\n"
  5433. "Connection: close\r\n"
  5434. "\r\n";
  5435. std::string res;
  5436. ASSERT_TRUE(send_request(5, req, &res));
  5437. EXPECT_EQ(header_value, "");
  5438. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5439. }
  5440. // Sends a raw request and verifies that there isn't a crash or exception.
  5441. static void test_raw_request(const std::string &req,
  5442. std::string *out = nullptr) {
  5443. Server svr;
  5444. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5445. res.set_content("ok", "text/plain");
  5446. });
  5447. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5448. res.set_content("ok", "text/plain");
  5449. });
  5450. svr.Get("/header_field_value_check",
  5451. [&](const Request & /*req*/, Response &res) {
  5452. res.set_content("ok", "text/plain");
  5453. });
  5454. // Server read timeout must be longer than the client read timeout for the
  5455. // bug to reproduce, probably to force the server to process a request
  5456. // without a trailing blank line.
  5457. const time_t client_read_timeout_sec = 1;
  5458. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5459. bool listen_thread_ok = false;
  5460. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5461. auto se = detail::scope_exit([&] {
  5462. svr.stop();
  5463. t.join();
  5464. ASSERT_FALSE(svr.is_running());
  5465. EXPECT_TRUE(listen_thread_ok);
  5466. });
  5467. svr.wait_until_ready();
  5468. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5469. }
  5470. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5471. // A certain header line causes an exception if the header property is parsed
  5472. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5473. test_raw_request(
  5474. "GET /hi HTTP/1.1\r\n"
  5475. " : "
  5476. " "
  5477. " ");
  5478. }
  5479. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5480. // A certain header line causes an exception if the header property *name* is
  5481. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5482. // greedy matcher and requires backtracking when there are a lot of ":"
  5483. // characters.
  5484. // This occurs with libc++ but not libstdc++.
  5485. test_raw_request(
  5486. "GET /hi HTTP/1.1\r\n"
  5487. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5488. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5489. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5490. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5491. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5492. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5493. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5494. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5495. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5496. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5497. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5498. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5499. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5500. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5501. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5502. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5503. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5504. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5505. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5506. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5507. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5508. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5509. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5510. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5511. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5512. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5513. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5514. "&&&%%%");
  5515. }
  5516. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5517. // Make sure this doesn't crash the server.
  5518. // In a previous version of the header line regex, the "\r" rendered the line
  5519. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5520. // a new position where the leading white space ended and the field value
  5521. // began.
  5522. // The crash occurs with libc++ but not libstdc++.
  5523. test_raw_request("GET /hi HTTP/1.1\r\n"
  5524. "a:" +
  5525. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5526. "\r\n"
  5527. "\r\n");
  5528. }
  5529. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5530. std::string out;
  5531. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5532. "Content-Type: text/plain\r\n"
  5533. "Transfer-Encoding: chunked\r\n"
  5534. "\r\n"
  5535. "nothex\r\n",
  5536. &out);
  5537. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5538. }
  5539. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5540. std::string out;
  5541. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5542. "Content-Type: text/plain\r\n"
  5543. "Transfer-Encoding: chunked\r\n"
  5544. "\r\n"
  5545. "3\r\n"
  5546. "xyz\r\n"
  5547. "NaN\r\n",
  5548. &out);
  5549. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5550. }
  5551. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5552. std::string out;
  5553. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5554. "Content-Type: text/plain\r\n"
  5555. "Transfer-Encoding: chunked\r\n"
  5556. "\r\n"
  5557. // Length is too large for 64 bits.
  5558. "1ffffffffffffffff\r\n"
  5559. "xyz\r\n",
  5560. &out);
  5561. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5562. }
  5563. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5564. test_raw_request("GET /hi HTTP/1.1\r\n"
  5565. "Content-Type: text/plain\r\n\r");
  5566. }
  5567. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5568. std::string out;
  5569. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5570. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5571. }
  5572. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5573. std::string out;
  5574. std::string request(
  5575. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5576. test_raw_request(request, &out);
  5577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5578. }
  5579. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5580. std::string out;
  5581. std::string request(
  5582. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5583. test_raw_request(request, &out);
  5584. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5585. }
  5586. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5587. std::string out;
  5588. std::string request(
  5589. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5590. test_raw_request(request, &out);
  5591. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5592. }
  5593. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5594. std::string out;
  5595. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5596. "Test: \r\n\r\n",
  5597. &out);
  5598. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5599. }
  5600. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5601. Server svr;
  5602. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5603. res.set_header("Cache-Control", "no-cache");
  5604. res.set_chunked_content_provider(
  5605. "text/event-stream", [](size_t offset, DataSink &sink) {
  5606. std::string s = "data:";
  5607. s += std::to_string(offset);
  5608. s += "\n\n";
  5609. auto ret = sink.write(s.data(), s.size());
  5610. EXPECT_TRUE(ret);
  5611. std::this_thread::sleep_for(std::chrono::seconds(1));
  5612. return true;
  5613. });
  5614. });
  5615. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5616. svr.wait_until_ready();
  5617. Client client(HOST, PORT);
  5618. const Headers headers = {{"Accept", "text/event-stream"}};
  5619. auto get_thread = std::thread([&client, &headers]() {
  5620. auto res = client.Get(
  5621. "/events", headers,
  5622. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5623. });
  5624. auto se = detail::scope_exit([&] {
  5625. svr.stop();
  5626. get_thread.join();
  5627. listen_thread.join();
  5628. ASSERT_FALSE(svr.is_running());
  5629. });
  5630. // Give GET time to get a few messages.
  5631. std::this_thread::sleep_for(std::chrono::seconds(2));
  5632. }
  5633. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5634. httplib::Server svr;
  5635. svr.Post("/hi",
  5636. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5637. res.status = StatusCode::OK_200;
  5638. });
  5639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5640. svr.wait_until_ready();
  5641. Client cli(HOST, PORT);
  5642. auto res = cli.Post("/hi", "data", "text/plain");
  5643. ASSERT_TRUE(res);
  5644. EXPECT_EQ(StatusCode::OK_200, res->status);
  5645. svr.stop();
  5646. thread.join();
  5647. ASSERT_FALSE(svr.is_running());
  5648. res = cli.Post("/hi", "data", "text/plain");
  5649. ASSERT_FALSE(res);
  5650. }
  5651. TEST(ServerStopTest, ListenFailure) {
  5652. Server svr;
  5653. auto t = thread([&]() {
  5654. auto ret = svr.listen("????", PORT);
  5655. EXPECT_FALSE(ret);
  5656. });
  5657. svr.wait_until_ready();
  5658. svr.stop();
  5659. t.join();
  5660. }
  5661. TEST(ServerStopTest, Decommision) {
  5662. Server svr;
  5663. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5664. for (int i = 0; i < 4; i++) {
  5665. auto is_even = !(i % 2);
  5666. std::thread t{[&] {
  5667. try {
  5668. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5669. if (is_even) {
  5670. throw std::runtime_error("Some thing that happens to go wrong.");
  5671. }
  5672. svr.listen(HOST, PORT);
  5673. } catch (...) { svr.decommission(); }
  5674. }};
  5675. svr.wait_until_ready();
  5676. // Server is up
  5677. {
  5678. Client cli(HOST, PORT);
  5679. auto res = cli.Get("/hi");
  5680. if (is_even) {
  5681. EXPECT_FALSE(res);
  5682. } else {
  5683. EXPECT_TRUE(res);
  5684. EXPECT_EQ("hi...", res->body);
  5685. }
  5686. }
  5687. svr.stop();
  5688. t.join();
  5689. // Server is down...
  5690. {
  5691. Client cli(HOST, PORT);
  5692. auto res = cli.Get("/hi");
  5693. EXPECT_FALSE(res);
  5694. }
  5695. }
  5696. }
  5697. // Helper function for string body upload progress tests
  5698. template <typename SetupHandler, typename ClientCall>
  5699. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5700. ClientCall &&client_call,
  5701. const string &body) {
  5702. Server svr;
  5703. setup_handler(svr);
  5704. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5705. auto se = detail::scope_exit([&] {
  5706. svr.stop();
  5707. t.join();
  5708. });
  5709. svr.wait_until_ready();
  5710. Client cli(HOST, PORT);
  5711. vector<uint64_t> progress_values;
  5712. bool progress_called = false;
  5713. auto res =
  5714. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5715. progress_values.push_back(current);
  5716. progress_called = true;
  5717. return true;
  5718. });
  5719. ASSERT_TRUE(res);
  5720. EXPECT_EQ(200, res->status);
  5721. EXPECT_TRUE(progress_called);
  5722. }
  5723. TEST(UploadProgressTest, PostStringBodyBasic) {
  5724. TestStringBodyUploadProgress(
  5725. [](Server &svr) {
  5726. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5727. res.set_content("received", "text/plain");
  5728. });
  5729. },
  5730. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5731. return cli.Post("/test", body, "text/plain", progress_callback);
  5732. },
  5733. "test data for upload progress");
  5734. }
  5735. TEST(UploadProgressTest, PutStringBodyBasic) {
  5736. TestStringBodyUploadProgress(
  5737. [](Server &svr) {
  5738. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5739. res.set_content("put received", "text/plain");
  5740. });
  5741. },
  5742. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5743. return cli.Put("/test", body, "text/plain", progress_callback);
  5744. },
  5745. "put test data for upload progress");
  5746. }
  5747. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5748. TestStringBodyUploadProgress(
  5749. [](Server &svr) {
  5750. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5751. res.set_content("patch received", "text/plain");
  5752. });
  5753. },
  5754. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5755. return cli.Patch("/test", body, "text/plain", progress_callback);
  5756. },
  5757. "patch test data for upload progress");
  5758. }
  5759. // Helper function for content provider upload progress tests
  5760. template <typename SetupHandler, typename ClientCall>
  5761. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5762. ClientCall &&client_call) {
  5763. Server svr;
  5764. setup_handler(svr);
  5765. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5766. auto se = detail::scope_exit([&] {
  5767. svr.stop();
  5768. t.join();
  5769. });
  5770. svr.wait_until_ready();
  5771. Client cli(HOST, PORT);
  5772. vector<uint64_t> progress_values;
  5773. auto res =
  5774. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5775. progress_values.push_back(current);
  5776. return true;
  5777. });
  5778. ASSERT_TRUE(res);
  5779. EXPECT_EQ(200, res->status);
  5780. EXPECT_FALSE(progress_values.empty());
  5781. }
  5782. TEST(UploadProgressTest, PostContentProviderProgress) {
  5783. TestContentProviderUploadProgress(
  5784. [](Server &svr) {
  5785. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5786. res.set_content("provider received", "text/plain");
  5787. });
  5788. },
  5789. [](Client &cli, UploadProgress progress_callback) {
  5790. return cli.Post(
  5791. "/test", 10,
  5792. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5793. sink.os << "test data";
  5794. return true;
  5795. },
  5796. "text/plain", progress_callback);
  5797. });
  5798. }
  5799. // Helper function for multipart upload progress tests
  5800. template <typename SetupHandler, typename ClientCall>
  5801. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5802. ClientCall &&client_call,
  5803. const string &endpoint) {
  5804. Server svr;
  5805. setup_handler(svr);
  5806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5807. auto se = detail::scope_exit([&] {
  5808. svr.stop();
  5809. t.join();
  5810. });
  5811. svr.wait_until_ready();
  5812. Client cli(HOST, PORT);
  5813. vector<uint64_t> progress_values;
  5814. UploadFormDataItems items = {
  5815. {"field1", "value1", "", ""},
  5816. {"field2", "longer value for progress tracking test", "", ""},
  5817. {"file1", "file content data for upload progress", "test.txt",
  5818. "text/plain"}};
  5819. auto res = client_call(cli, endpoint, items,
  5820. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5821. progress_values.push_back(current);
  5822. return true;
  5823. });
  5824. ASSERT_TRUE(res);
  5825. EXPECT_EQ(200, res->status);
  5826. EXPECT_FALSE(progress_values.empty());
  5827. }
  5828. TEST(UploadProgressTest, PostMultipartProgress) {
  5829. TestMultipartUploadProgress(
  5830. [](Server &svr) {
  5831. svr.Post("/multipart", [](const Request &req, Response &res) {
  5832. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5833. res.set_content("multipart received", "text/plain");
  5834. });
  5835. },
  5836. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5837. UploadProgress progress_callback) {
  5838. return cli.Post(endpoint, items, progress_callback);
  5839. },
  5840. "/multipart");
  5841. }
  5842. // Helper function for basic download progress tests
  5843. template <typename SetupHandler, typename ClientCall>
  5844. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5845. ClientCall &&client_call, const string &endpoint,
  5846. size_t expected_content_size) {
  5847. Server svr;
  5848. setup_handler(svr);
  5849. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5850. auto se = detail::scope_exit([&] {
  5851. svr.stop();
  5852. t.join();
  5853. });
  5854. svr.wait_until_ready();
  5855. Client cli(HOST, PORT);
  5856. vector<uint64_t> progress_values;
  5857. auto res = client_call(cli, endpoint,
  5858. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5859. progress_values.push_back(current);
  5860. return true;
  5861. });
  5862. ASSERT_TRUE(res);
  5863. EXPECT_EQ(200, res->status);
  5864. EXPECT_FALSE(progress_values.empty());
  5865. EXPECT_EQ(expected_content_size, res->body.size());
  5866. }
  5867. TEST(DownloadProgressTest, GetBasic) {
  5868. TestBasicDownloadProgress(
  5869. [](Server &svr) {
  5870. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5871. string content(1000, 'D');
  5872. res.set_content(content, "text/plain");
  5873. });
  5874. },
  5875. [](Client &cli, const string &endpoint,
  5876. DownloadProgress progress_callback) {
  5877. return cli.Get(endpoint, progress_callback);
  5878. },
  5879. "/download", 1000u);
  5880. }
  5881. // Helper function for content receiver download progress tests
  5882. template <typename SetupHandler, typename ClientCall>
  5883. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5884. ClientCall &&client_call,
  5885. const string &endpoint,
  5886. size_t expected_content_size) {
  5887. Server svr;
  5888. setup_handler(svr);
  5889. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5890. auto se = detail::scope_exit([&] {
  5891. svr.stop();
  5892. t.join();
  5893. });
  5894. svr.wait_until_ready();
  5895. Client cli(HOST, PORT);
  5896. vector<uint64_t> progress_values;
  5897. string received_body;
  5898. auto res = client_call(
  5899. cli, endpoint,
  5900. [&](const char *data, size_t data_length) -> bool {
  5901. received_body.append(data, data_length);
  5902. return true;
  5903. },
  5904. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5905. progress_values.push_back(current);
  5906. return true;
  5907. });
  5908. ASSERT_TRUE(res);
  5909. EXPECT_EQ(200, res->status);
  5910. EXPECT_FALSE(progress_values.empty());
  5911. EXPECT_EQ(expected_content_size, received_body.size());
  5912. EXPECT_TRUE(res->body.empty());
  5913. }
  5914. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5915. TestContentReceiverDownloadProgress(
  5916. [](Server &svr) {
  5917. svr.Get("/download-receiver",
  5918. [](const Request & /*req*/, Response &res) {
  5919. string content(2000, 'R');
  5920. res.set_content(content, "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5924. DownloadProgress progress_callback) {
  5925. return cli.Get(endpoint, content_receiver, progress_callback);
  5926. },
  5927. "/download-receiver", 2000u);
  5928. }
  5929. TEST(StreamingTest, NoContentLengthStreaming) {
  5930. Server svr;
  5931. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5932. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5933. if (offset < 6) {
  5934. sink.os << (offset < 3 ? "a" : "b");
  5935. } else {
  5936. sink.done();
  5937. }
  5938. return true;
  5939. });
  5940. });
  5941. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5942. auto listen_se = detail::scope_exit([&] {
  5943. svr.stop();
  5944. listen_thread.join();
  5945. ASSERT_FALSE(svr.is_running());
  5946. });
  5947. svr.wait_until_ready();
  5948. Client client(HOST, PORT);
  5949. auto get_thread = std::thread([&client]() {
  5950. std::string s;
  5951. auto res =
  5952. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5953. s += std::string(data, len);
  5954. return true;
  5955. });
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. EXPECT_EQ("aaabbb", s);
  5959. });
  5960. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5961. // Give GET time to get a few messages.
  5962. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5963. }
  5964. TEST(MountTest, Unmount) {
  5965. Server svr;
  5966. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. listen_thread.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. Client cli("localhost", PORT);
  5974. svr.set_mount_point("/mount2", "./www2");
  5975. auto res = cli.Get("/");
  5976. ASSERT_TRUE(res);
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. res = cli.Get("/mount2/dir/test.html");
  5979. ASSERT_TRUE(res);
  5980. EXPECT_EQ(StatusCode::OK_200, res->status);
  5981. svr.set_mount_point("/", "./www");
  5982. res = cli.Get("/dir/");
  5983. ASSERT_TRUE(res);
  5984. EXPECT_EQ(StatusCode::OK_200, res->status);
  5985. svr.remove_mount_point("/");
  5986. res = cli.Get("/dir/");
  5987. ASSERT_TRUE(res);
  5988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5989. svr.remove_mount_point("/mount2");
  5990. res = cli.Get("/mount2/dir/test.html");
  5991. ASSERT_TRUE(res);
  5992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5993. }
  5994. TEST(MountTest, Redicect) {
  5995. Server svr;
  5996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5997. auto se = detail::scope_exit([&] {
  5998. svr.stop();
  5999. listen_thread.join();
  6000. ASSERT_FALSE(svr.is_running());
  6001. });
  6002. svr.set_mount_point("/", "./www");
  6003. svr.wait_until_ready();
  6004. Client cli("localhost", PORT);
  6005. auto res = cli.Get("/dir/");
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(StatusCode::OK_200, res->status);
  6008. res = cli.Get("/dir");
  6009. ASSERT_TRUE(res);
  6010. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6011. res = cli.Get("/file");
  6012. ASSERT_TRUE(res);
  6013. EXPECT_EQ(StatusCode::OK_200, res->status);
  6014. res = cli.Get("/file/");
  6015. ASSERT_TRUE(res);
  6016. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6017. cli.set_follow_location(true);
  6018. res = cli.Get("/dir");
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(StatusCode::OK_200, res->status);
  6021. }
  6022. TEST(MountTest, MultibytesPathName) {
  6023. Server svr;
  6024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6025. auto se = detail::scope_exit([&] {
  6026. svr.stop();
  6027. listen_thread.join();
  6028. ASSERT_FALSE(svr.is_running());
  6029. });
  6030. svr.set_mount_point("/", "./www");
  6031. svr.wait_until_ready();
  6032. Client cli("localhost", PORT);
  6033. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6034. ASSERT_TRUE(res);
  6035. EXPECT_EQ(StatusCode::OK_200, res->status);
  6036. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6037. }
  6038. TEST(KeepAliveTest, ReadTimeout) {
  6039. Server svr;
  6040. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6041. std::this_thread::sleep_for(std::chrono::seconds(2));
  6042. res.set_content("a", "text/plain");
  6043. });
  6044. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6045. res.set_content("b", "text/plain");
  6046. });
  6047. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. listen_thread.join();
  6051. ASSERT_FALSE(svr.is_running());
  6052. });
  6053. svr.wait_until_ready();
  6054. Client cli("localhost", PORT);
  6055. cli.set_keep_alive(true);
  6056. cli.set_read_timeout(std::chrono::seconds(1));
  6057. auto resa = cli.Get("/a");
  6058. ASSERT_FALSE(resa);
  6059. EXPECT_EQ(Error::Read, resa.error());
  6060. auto resb = cli.Get("/b");
  6061. ASSERT_TRUE(resb);
  6062. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6063. EXPECT_EQ("b", resb->body);
  6064. }
  6065. TEST(KeepAliveTest, MaxCount) {
  6066. size_t keep_alive_max_count = 3;
  6067. Server svr;
  6068. svr.set_keep_alive_max_count(keep_alive_max_count);
  6069. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6070. res.set_content("Hello World!", "text/plain");
  6071. });
  6072. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. listen_thread.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli(HOST, PORT);
  6080. cli.set_keep_alive(true);
  6081. for (size_t i = 0; i < 5; i++) {
  6082. auto result = cli.Get("/hi");
  6083. ASSERT_TRUE(result);
  6084. EXPECT_EQ(StatusCode::OK_200, result->status);
  6085. if (i == keep_alive_max_count - 1) {
  6086. EXPECT_EQ("close", result->get_header_value("Connection"));
  6087. } else {
  6088. EXPECT_FALSE(result->has_header("Connection"));
  6089. }
  6090. }
  6091. }
  6092. TEST(KeepAliveTest, Issue1041) {
  6093. Server svr;
  6094. svr.set_keep_alive_timeout(3);
  6095. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6096. res.set_content("Hello World!", "text/plain");
  6097. });
  6098. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6099. auto se = detail::scope_exit([&] {
  6100. svr.stop();
  6101. listen_thread.join();
  6102. ASSERT_FALSE(svr.is_running());
  6103. });
  6104. svr.wait_until_ready();
  6105. Client cli(HOST, PORT);
  6106. cli.set_keep_alive(true);
  6107. auto result = cli.Get("/hi");
  6108. ASSERT_TRUE(result);
  6109. EXPECT_EQ(StatusCode::OK_200, result->status);
  6110. std::this_thread::sleep_for(std::chrono::seconds(5));
  6111. result = cli.Get("/hi");
  6112. ASSERT_TRUE(result);
  6113. EXPECT_EQ(StatusCode::OK_200, result->status);
  6114. }
  6115. TEST(KeepAliveTest, Issue1959) {
  6116. Server svr;
  6117. svr.set_keep_alive_timeout(5);
  6118. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6119. res.set_content("a", "text/plain");
  6120. });
  6121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6122. auto se = detail::scope_exit([&] {
  6123. if (!svr.is_running()) return;
  6124. svr.stop();
  6125. listen_thread.join();
  6126. ASSERT_FALSE(svr.is_running());
  6127. });
  6128. svr.wait_until_ready();
  6129. Client cli("localhost", PORT);
  6130. cli.set_keep_alive(true);
  6131. using namespace std::chrono;
  6132. auto start = steady_clock::now();
  6133. cli.Get("/a");
  6134. svr.stop();
  6135. listen_thread.join();
  6136. auto end = steady_clock::now();
  6137. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6138. EXPECT_LT(elapsed, 5000);
  6139. }
  6140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6141. TEST(KeepAliveTest, SSLClientReconnection) {
  6142. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6143. ASSERT_TRUE(svr.is_valid());
  6144. svr.set_keep_alive_timeout(1);
  6145. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6146. res.set_content("Hello World!", "text/plain");
  6147. });
  6148. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6149. auto se = detail::scope_exit([&] {
  6150. svr.stop();
  6151. listen_thread.join();
  6152. ASSERT_FALSE(svr.is_running());
  6153. });
  6154. svr.wait_until_ready();
  6155. SSLClient cli(HOST, PORT);
  6156. cli.enable_server_certificate_verification(false);
  6157. cli.set_keep_alive(true);
  6158. auto result = cli.Get("/hi");
  6159. ASSERT_TRUE(result);
  6160. EXPECT_EQ(StatusCode::OK_200, result->status);
  6161. result = cli.Get("/hi");
  6162. ASSERT_TRUE(result);
  6163. EXPECT_EQ(StatusCode::OK_200, result->status);
  6164. std::this_thread::sleep_for(std::chrono::seconds(2));
  6165. // Recoonect
  6166. result = cli.Get("/hi");
  6167. ASSERT_TRUE(result);
  6168. EXPECT_EQ(StatusCode::OK_200, result->status);
  6169. result = cli.Get("/hi");
  6170. ASSERT_TRUE(result);
  6171. EXPECT_EQ(StatusCode::OK_200, result->status);
  6172. }
  6173. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6175. ASSERT_TRUE(svr.is_valid());
  6176. svr.set_keep_alive_timeout(1);
  6177. std::string content = "reconnect";
  6178. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6179. res.set_content("Hello World!", "text/plain");
  6180. });
  6181. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6182. auto se = detail::scope_exit([&] {
  6183. svr.stop();
  6184. listen_thread.join();
  6185. ASSERT_FALSE(svr.is_running());
  6186. });
  6187. svr.wait_until_ready();
  6188. SSLClient cli(HOST, PORT);
  6189. cli.enable_server_certificate_verification(false);
  6190. cli.set_keep_alive(true);
  6191. auto result = cli.Post(
  6192. "/hi", content.size(),
  6193. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6194. sink.write(content.c_str(), content.size());
  6195. return true;
  6196. },
  6197. "text/plain");
  6198. ASSERT_TRUE(result);
  6199. EXPECT_EQ(200, result->status);
  6200. std::this_thread::sleep_for(std::chrono::seconds(2));
  6201. // Recoonect
  6202. result = cli.Post(
  6203. "/hi", content.size(),
  6204. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6205. sink.write(content.c_str(), content.size());
  6206. return true;
  6207. },
  6208. "text/plain");
  6209. ASSERT_TRUE(result);
  6210. EXPECT_EQ(200, result->status);
  6211. result = cli.Post(
  6212. "/hi", content.size(),
  6213. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6214. sink.write(content.c_str(), content.size());
  6215. return true;
  6216. },
  6217. "text/plain");
  6218. ASSERT_TRUE(result);
  6219. EXPECT_EQ(200, result->status);
  6220. }
  6221. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6222. {
  6223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6224. ASSERT_TRUE(svr.is_valid());
  6225. svr.Get("/sni", [&](const Request &req, Response &res) {
  6226. std::string expected;
  6227. if (req.ssl) {
  6228. if (const char *sni =
  6229. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6230. expected = sni;
  6231. }
  6232. }
  6233. EXPECT_EQ(expected, req.get_param_value("expected"));
  6234. res.set_content("ok", "text/plain");
  6235. });
  6236. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6237. auto se = detail::scope_exit([&] {
  6238. svr.stop();
  6239. listen_thread.join();
  6240. ASSERT_FALSE(svr.is_running());
  6241. });
  6242. svr.wait_until_ready();
  6243. {
  6244. SSLClient cli("localhost", PORT);
  6245. cli.enable_server_certificate_verification(false);
  6246. auto res = cli.Get("/sni?expected=localhost");
  6247. ASSERT_TRUE(res);
  6248. }
  6249. {
  6250. SSLClient cli("::1", PORT);
  6251. cli.enable_server_certificate_verification(false);
  6252. auto res = cli.Get("/sni?expected=");
  6253. ASSERT_TRUE(res);
  6254. }
  6255. }
  6256. }
  6257. #endif
  6258. TEST(ClientProblemDetectionTest, ContentProvider) {
  6259. Server svr;
  6260. size_t content_length = 1024 * 1024;
  6261. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6262. res.set_content_provider(
  6263. content_length, "text/plain",
  6264. [&](size_t offset, size_t length, DataSink &sink) {
  6265. auto out_len = std::min(length, static_cast<size_t>(1024));
  6266. std::string out(out_len, '@');
  6267. sink.write(out.data(), out_len);
  6268. return offset < 4096;
  6269. },
  6270. [](bool success) { ASSERT_FALSE(success); });
  6271. });
  6272. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6273. res.set_content_provider(
  6274. 0, "text/plain",
  6275. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6276. EXPECT_TRUE(false);
  6277. return true;
  6278. },
  6279. [](bool success) { ASSERT_FALSE(success); });
  6280. });
  6281. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6282. auto se = detail::scope_exit([&] {
  6283. svr.stop();
  6284. listen_thread.join();
  6285. ASSERT_FALSE(svr.is_running());
  6286. });
  6287. svr.wait_until_ready();
  6288. Client cli("localhost", PORT);
  6289. {
  6290. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6291. size_t /*data_length*/) { return false; });
  6292. ASSERT_FALSE(res);
  6293. }
  6294. {
  6295. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6296. size_t /*data_length*/) { return false; });
  6297. ASSERT_TRUE(res);
  6298. }
  6299. }
  6300. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6301. Server svr;
  6302. svr.set_error_handler([](Request const &, Response &res) -> void {
  6303. res.set_chunked_content_provider(
  6304. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6305. sink.os << "hello";
  6306. sink.os << "world";
  6307. sink.done();
  6308. return true;
  6309. });
  6310. });
  6311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6312. auto se = detail::scope_exit([&] {
  6313. svr.stop();
  6314. listen_thread.join();
  6315. ASSERT_FALSE(svr.is_running());
  6316. });
  6317. svr.wait_until_ready();
  6318. Client cli("localhost", PORT);
  6319. auto res = cli.Get("/");
  6320. ASSERT_TRUE(res);
  6321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6322. EXPECT_EQ("helloworld", res->body);
  6323. }
  6324. TEST(LongPollingTest, ClientCloseDetection) {
  6325. Server svr;
  6326. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6327. res.set_chunked_content_provider(
  6328. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6329. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6330. sink.os << "hello";
  6331. auto count = 10;
  6332. while (count > 0 && sink.is_writable()) {
  6333. this_thread::sleep_for(chrono::milliseconds(10));
  6334. count--;
  6335. }
  6336. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6337. return true;
  6338. });
  6339. });
  6340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. listen_thread.join();
  6344. ASSERT_FALSE(svr.is_running());
  6345. });
  6346. svr.wait_until_ready();
  6347. Client cli("localhost", PORT);
  6348. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6349. EXPECT_EQ("hello", string(data, data_length));
  6350. return false; // close the socket immediately.
  6351. });
  6352. ASSERT_FALSE(res);
  6353. }
  6354. TEST(GetWithParametersTest, GetWithParameters) {
  6355. Server svr;
  6356. svr.Get("/", [&](const Request &req, Response &) {
  6357. EXPECT_EQ("world", req.get_param_value("hello"));
  6358. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6359. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6360. });
  6361. svr.Get("/params", [&](const Request &req, Response &) {
  6362. EXPECT_EQ("world", req.get_param_value("hello"));
  6363. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6364. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6365. });
  6366. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6367. EXPECT_EQ("resource-id", req.matches[1]);
  6368. EXPECT_EQ("foo", req.get_param_value("param1"));
  6369. EXPECT_EQ("bar", req.get_param_value("param2"));
  6370. });
  6371. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6372. EXPECT_EQ("user-id", req.path_params.at("id"));
  6373. EXPECT_EQ("foo", req.get_param_value("param1"));
  6374. EXPECT_EQ("bar", req.get_param_value("param2"));
  6375. });
  6376. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. ASSERT_FALSE(svr.is_running());
  6381. });
  6382. svr.wait_until_ready();
  6383. {
  6384. Client cli(HOST, PORT);
  6385. Params params;
  6386. params.emplace("hello", "world");
  6387. params.emplace("hello2", "world2");
  6388. params.emplace("hello3", "world3");
  6389. auto res = cli.Get("/", params, Headers{});
  6390. ASSERT_TRUE(res);
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. {
  6394. Client cli(HOST, PORT);
  6395. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ(StatusCode::OK_200, res->status);
  6398. }
  6399. {
  6400. Client cli(HOST, PORT);
  6401. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6402. ASSERT_TRUE(res);
  6403. EXPECT_EQ(StatusCode::OK_200, res->status);
  6404. }
  6405. {
  6406. Client cli(HOST, PORT);
  6407. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6408. ASSERT_TRUE(res);
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. }
  6412. TEST(GetWithParametersTest, GetWithParameters2) {
  6413. Server svr;
  6414. svr.Get("/", [&](const Request &req, Response &res) {
  6415. auto text = req.get_param_value("hello");
  6416. res.set_content(text, "text/plain");
  6417. });
  6418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6419. auto se = detail::scope_exit([&] {
  6420. svr.stop();
  6421. listen_thread.join();
  6422. ASSERT_FALSE(svr.is_running());
  6423. });
  6424. svr.wait_until_ready();
  6425. Client cli("localhost", PORT);
  6426. Params params;
  6427. params.emplace("hello", "world");
  6428. std::string body;
  6429. auto res = cli.Get("/", params, Headers{},
  6430. [&](const char *data, size_t data_length) {
  6431. body.append(data, data_length);
  6432. return true;
  6433. });
  6434. ASSERT_TRUE(res);
  6435. EXPECT_EQ(StatusCode::OK_200, res->status);
  6436. EXPECT_EQ("world", body);
  6437. }
  6438. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6439. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6440. auto host = "httpbin.org";
  6441. auto path = std::string{"/range/32"};
  6442. #else
  6443. auto host = "nghttp2.org";
  6444. auto path = std::string{"/httpbin/range/32"};
  6445. #endif
  6446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6447. SSLClient cli(host);
  6448. #else
  6449. Client cli(host);
  6450. #endif
  6451. cli.set_default_headers({make_range_header({{1, 10}})});
  6452. cli.set_connection_timeout(5);
  6453. {
  6454. auto res = cli.Get(path);
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ("bcdefghijk", res->body);
  6457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6458. }
  6459. {
  6460. auto res = cli.Get(path);
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ("bcdefghijk", res->body);
  6463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6464. }
  6465. }
  6466. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6467. Server svr;
  6468. svr.set_default_headers({{"Hello", "World"}});
  6469. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6470. res.set_content("ok", "text/plain");
  6471. });
  6472. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6473. auto se = detail::scope_exit([&] {
  6474. svr.stop();
  6475. listen_thread.join();
  6476. ASSERT_FALSE(svr.is_running());
  6477. });
  6478. svr.wait_until_ready();
  6479. Client cli("localhost", PORT);
  6480. auto res = cli.Get("/");
  6481. ASSERT_TRUE(res);
  6482. EXPECT_EQ(StatusCode::OK_200, res->status);
  6483. EXPECT_EQ("ok", res->body);
  6484. EXPECT_EQ("World", res->get_header_value("Hello"));
  6485. }
  6486. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6487. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6489. ASSERT_TRUE(svr.is_valid());
  6490. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6491. std::this_thread::sleep_for(std::chrono::seconds(2));
  6492. res.set_content("a", "text/plain");
  6493. });
  6494. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6495. res.set_content("b", "text/plain");
  6496. });
  6497. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. listen_thread.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. SSLClient cli("localhost", PORT);
  6505. cli.enable_server_certificate_verification(false);
  6506. cli.set_keep_alive(true);
  6507. cli.set_read_timeout(std::chrono::seconds(1));
  6508. auto resa = cli.Get("/a");
  6509. ASSERT_TRUE(!resa);
  6510. EXPECT_EQ(Error::Read, resa.error());
  6511. auto resb = cli.Get("/b");
  6512. ASSERT_TRUE(resb);
  6513. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6514. EXPECT_EQ("b", resb->body);
  6515. }
  6516. #endif
  6517. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6518. protected:
  6519. ServerTestWithAI_PASSIVE()
  6520. : cli_(HOST, PORT)
  6521. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6522. ,
  6523. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6524. #endif
  6525. {
  6526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6527. cli_.enable_server_certificate_verification(false);
  6528. #endif
  6529. }
  6530. virtual void SetUp() {
  6531. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6532. res.set_content("Hello World!", "text/plain");
  6533. });
  6534. t_ = thread(
  6535. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6536. svr_.wait_until_ready();
  6537. }
  6538. virtual void TearDown() {
  6539. svr_.stop();
  6540. t_.join();
  6541. }
  6542. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6543. SSLClient cli_;
  6544. SSLServer svr_;
  6545. #else
  6546. Client cli_;
  6547. Server svr_;
  6548. #endif
  6549. thread t_;
  6550. };
  6551. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6552. auto res = cli_.Get("/hi");
  6553. ASSERT_TRUE(res);
  6554. EXPECT_EQ(StatusCode::OK_200, res->status);
  6555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6556. EXPECT_EQ("Hello World!", res->body);
  6557. }
  6558. class ServerUpDownTest : public ::testing::Test {
  6559. protected:
  6560. ServerUpDownTest() : cli_(HOST, PORT) {}
  6561. virtual void SetUp() {
  6562. t_ = thread([&]() {
  6563. svr_.bind_to_any_port(HOST);
  6564. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6565. ASSERT_TRUE(svr_.listen_after_bind());
  6566. });
  6567. svr_.wait_until_ready();
  6568. }
  6569. virtual void TearDown() {
  6570. svr_.stop();
  6571. t_.join();
  6572. }
  6573. Client cli_;
  6574. Server svr_;
  6575. thread t_;
  6576. };
  6577. TEST_F(ServerUpDownTest, QuickStartStop) {
  6578. // Should not crash, especially when run with
  6579. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6580. }
  6581. class PayloadMaxLengthTest : public ::testing::Test {
  6582. protected:
  6583. PayloadMaxLengthTest()
  6584. : cli_(HOST, PORT)
  6585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6586. ,
  6587. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6588. #endif
  6589. {
  6590. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6591. cli_.enable_server_certificate_verification(false);
  6592. #endif
  6593. }
  6594. virtual void SetUp() {
  6595. svr_.set_payload_max_length(8);
  6596. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6597. res.set_content("test", "text/plain");
  6598. });
  6599. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6600. svr_.wait_until_ready();
  6601. }
  6602. virtual void TearDown() {
  6603. svr_.stop();
  6604. t_.join();
  6605. }
  6606. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6607. SSLClient cli_;
  6608. SSLServer svr_;
  6609. #else
  6610. Client cli_;
  6611. Server svr_;
  6612. #endif
  6613. thread t_;
  6614. };
  6615. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6616. auto res = cli_.Post("/test", "123456789", "text/plain");
  6617. ASSERT_TRUE(res);
  6618. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6619. res = cli_.Post("/test", "12345678", "text/plain");
  6620. ASSERT_TRUE(res);
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. }
  6623. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6624. // Test chunked encoding with payload exceeding the 8-byte limit
  6625. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6626. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6627. ASSERT_TRUE(res);
  6628. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6629. }
  6630. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6631. // Test chunked encoding with payload within the 8-byte limit
  6632. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6633. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6634. ASSERT_TRUE(res);
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. }
  6637. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6638. // Test using send_request to send chunked data exceeding payload limit
  6639. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6640. "Host: " +
  6641. std::string(HOST) + ":" + std::to_string(PORT) +
  6642. "\r\n"
  6643. "Transfer-Encoding: chunked\r\n"
  6644. "Connection: close\r\n"
  6645. "\r\n"
  6646. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6647. "0123456789\r\n"
  6648. "0\r\n" // End chunk
  6649. "\r\n";
  6650. std::string response;
  6651. bool result = send_request(1, chunked_request, &response);
  6652. if (!result) {
  6653. // If send_request fails, it might be because the server closed the
  6654. // connection due to payload limit enforcement, which is acceptable
  6655. SUCCEED()
  6656. << "Server rejected oversized chunked request (connection closed)";
  6657. } else {
  6658. // If we got a response, check if it's an error response or connection was
  6659. // closed early Short response length indicates connection was closed due to
  6660. // payload limit
  6661. if (response.length() <= 10) {
  6662. SUCCEED() << "Server closed connection for oversized chunked request";
  6663. } else {
  6664. // Check for error status codes
  6665. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6666. response.find("Payload Too Large") != std::string::npos ||
  6667. response.find("400") != std::string::npos);
  6668. }
  6669. }
  6670. }
  6671. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6672. // Test request without Content-Length header exceeding payload limit
  6673. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6674. "Host: " +
  6675. std::string(HOST) + ":" +
  6676. std::to_string(PORT) +
  6677. "\r\n"
  6678. "Connection: close\r\n"
  6679. "\r\n";
  6680. // Add payload exceeding the 8-byte limit
  6681. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6682. request_without_content_length += large_payload;
  6683. std::string response;
  6684. bool result = send_request(1, request_without_content_length, &response);
  6685. if (!result) {
  6686. // If send_request fails, server likely closed connection due to payload
  6687. // limit
  6688. SUCCEED() << "Server rejected oversized request without Content-Length "
  6689. "(connection closed)";
  6690. } else {
  6691. // Check if server responded with error or closed connection early
  6692. if (response.length() <= 10) {
  6693. SUCCEED() << "Server closed connection for oversized request without "
  6694. "Content-Length";
  6695. } else {
  6696. // Check for error status codes
  6697. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6698. response.find("Payload Too Large") != std::string::npos ||
  6699. response.find("400") != std::string::npos);
  6700. }
  6701. }
  6702. }
  6703. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6704. // Test request without Content-Length header within payload limit
  6705. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6706. "Host: " +
  6707. std::string(HOST) + ":" +
  6708. std::to_string(PORT) +
  6709. "\r\n"
  6710. "Connection: close\r\n"
  6711. "\r\n";
  6712. // Add payload within the 8-byte limit
  6713. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6714. request_without_content_length += small_payload;
  6715. std::string response;
  6716. bool result = send_request(1, request_without_content_length, &response);
  6717. // For requests without Content-Length, the server may have different behavior
  6718. // The key is that it should not reject due to payload limit for small
  6719. // payloads
  6720. if (result) {
  6721. // Check for any HTTP response (success or error, but not connection closed)
  6722. if (response.length() > 10) {
  6723. SUCCEED()
  6724. << "Server processed request without Content-Length within limit";
  6725. } else {
  6726. // Short response might indicate connection closed, which is acceptable
  6727. SUCCEED() << "Server closed connection for request without "
  6728. "Content-Length (acceptable behavior)";
  6729. }
  6730. } else {
  6731. // Connection failure might be due to protocol requirements
  6732. SUCCEED() << "Connection issue with request without Content-Length "
  6733. "(environment-specific)";
  6734. }
  6735. }
  6736. class LargePayloadMaxLengthTest : public ::testing::Test {
  6737. protected:
  6738. LargePayloadMaxLengthTest()
  6739. : cli_(HOST, PORT)
  6740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6741. ,
  6742. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6743. #endif
  6744. {
  6745. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6746. cli_.enable_server_certificate_verification(false);
  6747. #endif
  6748. }
  6749. virtual void SetUp() {
  6750. // Set 10MB payload limit
  6751. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6752. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6753. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6754. res.set_content("Large payload test", "text/plain");
  6755. });
  6756. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6757. svr_.wait_until_ready();
  6758. }
  6759. virtual void TearDown() {
  6760. svr_.stop();
  6761. t_.join();
  6762. }
  6763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6764. SSLClient cli_;
  6765. SSLServer svr_;
  6766. #else
  6767. Client cli_;
  6768. Server svr_;
  6769. #endif
  6770. thread t_;
  6771. };
  6772. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6773. // Test chunked encoding with payload within 10MB limit
  6774. std::string medium_payload(5 * 1024 * 1024,
  6775. 'A'); // 5MB payload, within 10MB limit
  6776. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6777. ASSERT_TRUE(res);
  6778. EXPECT_EQ(StatusCode::OK_200, res->status);
  6779. }
  6780. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6781. // Test chunked encoding with payload exceeding 10MB limit
  6782. std::string large_payload(12 * 1024 * 1024,
  6783. 'B'); // 12MB payload, exceeds 10MB limit
  6784. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6785. ASSERT_TRUE(res);
  6786. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6787. }
  6788. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6789. // Test request without Content-Length header within 10MB limit
  6790. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6791. "Host: " +
  6792. std::string(HOST) + ":" +
  6793. std::to_string(PORT) +
  6794. "\r\n"
  6795. "Connection: close\r\n"
  6796. "\r\n";
  6797. // Add 1MB payload (within 10MB limit)
  6798. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6799. request_without_content_length += medium_payload;
  6800. std::string response;
  6801. bool result = send_request(5, request_without_content_length, &response);
  6802. if (result) {
  6803. // Should get a proper HTTP response for payloads within limit
  6804. if (response.length() > 10) {
  6805. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6806. "10MB limit";
  6807. } else {
  6808. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6809. "Content-Length)";
  6810. }
  6811. } else {
  6812. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6813. }
  6814. }
  6815. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6816. // Test request without Content-Length header exceeding 10MB limit
  6817. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6818. "Host: " +
  6819. std::string(HOST) + ":" +
  6820. std::to_string(PORT) +
  6821. "\r\n"
  6822. "Connection: close\r\n"
  6823. "\r\n";
  6824. // Add 12MB payload (exceeds 10MB limit)
  6825. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6826. request_without_content_length += large_payload;
  6827. std::string response;
  6828. bool result = send_request(10, request_without_content_length, &response);
  6829. if (!result) {
  6830. // Server should close connection due to payload limit
  6831. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6832. "(connection closed)";
  6833. } else {
  6834. // Check for error response
  6835. if (response.length() <= 10) {
  6836. SUCCEED()
  6837. << "Server closed connection for 12MB request exceeding 10MB limit";
  6838. } else {
  6839. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6840. response.find("Payload Too Large") != std::string::npos ||
  6841. response.find("400") != std::string::npos);
  6842. }
  6843. }
  6844. }
  6845. TEST(HostAndPortPropertiesTest, NoSSL) {
  6846. httplib::Client cli("www.google.com", 1234);
  6847. ASSERT_EQ("www.google.com", cli.host());
  6848. ASSERT_EQ(1234, cli.port());
  6849. }
  6850. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6851. httplib::Client cli("www.google.com:1234");
  6852. ASSERT_EQ("www.google.com", cli.host());
  6853. ASSERT_EQ(1234, cli.port());
  6854. }
  6855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6856. TEST(HostAndPortPropertiesTest, SSL) {
  6857. httplib::SSLClient cli("www.google.com");
  6858. ASSERT_EQ("www.google.com", cli.host());
  6859. ASSERT_EQ(443, cli.port());
  6860. }
  6861. #endif
  6862. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6863. TEST(SSLClientTest, UpdateCAStore) {
  6864. httplib::SSLClient httplib_client("www.google.com");
  6865. auto ca_store_1 = X509_STORE_new();
  6866. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6867. nullptr);
  6868. httplib_client.set_ca_cert_store(ca_store_1);
  6869. auto ca_store_2 = X509_STORE_new();
  6870. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6871. nullptr);
  6872. httplib_client.set_ca_cert_store(ca_store_2);
  6873. }
  6874. TEST(SSLClientTest, ServerNameIndication_Online) {
  6875. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6876. auto host = "httpbin.org";
  6877. auto path = std::string{"/get"};
  6878. #else
  6879. auto host = "nghttp2.org";
  6880. auto path = std::string{"/httpbin/get"};
  6881. #endif
  6882. SSLClient cli(host, 443);
  6883. auto res = cli.Get(path);
  6884. ASSERT_TRUE(res);
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. }
  6887. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6888. // Use a site that will cause SSL verification failure due to self-signed cert
  6889. SSLClient cli("self-signed.badssl.com", 443);
  6890. cli.enable_server_certificate_verification(true);
  6891. auto res = cli.Get("/");
  6892. ASSERT_TRUE(!res);
  6893. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6894. // For SSL server verification errors, ssl_error should be 0, only
  6895. // ssl_openssl_error should be set
  6896. EXPECT_EQ(0, res.ssl_error());
  6897. // Verify OpenSSL error is captured for SSLServerVerification
  6898. // This occurs when SSL_get_verify_result() returns a verification failure
  6899. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6900. res.ssl_openssl_error());
  6901. }
  6902. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6903. // Use a site where hostname doesn't match the certificate
  6904. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6905. SSLClient cli("wrong.host.badssl.com", 443);
  6906. cli.enable_server_certificate_verification(true);
  6907. cli.enable_server_hostname_verification(true);
  6908. auto res = cli.Get("/");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6911. // For SSL hostname verification errors, ssl_error should be 0, only
  6912. // ssl_openssl_error should be set
  6913. EXPECT_EQ(0, res.ssl_error());
  6914. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6915. // This occurs when verify_host() fails due to hostname mismatch
  6916. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6917. res.ssl_openssl_error());
  6918. }
  6919. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6920. Client cli("https://google.com");
  6921. auto res = cli.Get("/");
  6922. ASSERT_TRUE(res);
  6923. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6924. }
  6925. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6926. SSLClient cli("google.com");
  6927. cli.set_ca_cert_path(CA_CERT_FILE);
  6928. auto res = cli.Get("/");
  6929. ASSERT_TRUE(res);
  6930. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6931. }
  6932. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6933. SSLClient cli("google.com");
  6934. cli.enable_server_certificate_verification(true);
  6935. cli.set_ca_cert_path("hello");
  6936. auto res = cli.Get("/");
  6937. ASSERT_TRUE(!res);
  6938. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6939. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6940. // should be set
  6941. EXPECT_EQ(0, res.ssl_error());
  6942. // Verify OpenSSL error is captured for SSLLoadingCerts
  6943. // This error occurs when SSL_CTX_load_verify_locations() fails
  6944. // > openssl errstr 0x80000002
  6945. // error:80000002:system library::No such file or directory
  6946. // > openssl errstr 0xA000126
  6947. // error:0A000126:SSL routines::unexpected eof while reading
  6948. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6949. res.ssl_openssl_error() == 0xA000126);
  6950. }
  6951. TEST(SSLClientTest, ServerCertificateVerification4) {
  6952. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6953. ASSERT_TRUE(svr.is_valid());
  6954. svr.Get("/test", [&](const Request &, Response &res) {
  6955. res.set_content("test", "text/plain");
  6956. svr.stop();
  6957. ASSERT_TRUE(true);
  6958. });
  6959. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6960. auto se = detail::scope_exit([&] {
  6961. t.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. SSLClient cli("127.0.0.1", PORT);
  6966. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6967. cli.enable_server_certificate_verification(true);
  6968. cli.set_connection_timeout(30);
  6969. auto res = cli.Get("/test");
  6970. ASSERT_TRUE(res);
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. }
  6973. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6974. std::string cert;
  6975. read_file(CA_CERT_FILE, cert);
  6976. SSLClient cli("google.com");
  6977. cli.load_ca_cert_store(cert.data(), cert.size());
  6978. const auto res = cli.Get("/");
  6979. ASSERT_TRUE(res);
  6980. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6981. }
  6982. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6983. // clang-format off
  6984. static constexpr char cert[] =
  6985. "GlobalSign Root CA\n"
  6986. "==================\n"
  6987. "-----BEGIN CERTIFICATE-----\n"
  6988. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6989. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6990. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6991. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6992. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6993. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6994. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6995. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6996. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6997. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6998. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6999. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7000. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7001. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7002. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7003. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7004. "-----END CERTIFICATE-----\n";
  7005. // clang-format on
  7006. SSLClient cli("google.com");
  7007. cli.load_ca_cert_store(cert, sizeof(cert));
  7008. const auto res = cli.Get("/");
  7009. ASSERT_TRUE(res);
  7010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7011. }
  7012. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7013. SSLClient cli("www.youtube.com");
  7014. cli.set_ca_cert_path(CA_CERT_FILE);
  7015. cli.enable_server_certificate_verification(true);
  7016. cli.set_follow_location(true);
  7017. auto res = cli.Get("/");
  7018. ASSERT_TRUE(res);
  7019. ASSERT_EQ(StatusCode::OK_200, res->status);
  7020. }
  7021. TEST(SSLClientTest, Issue2004_Online) {
  7022. Client client("https://google.com");
  7023. client.set_follow_location(true);
  7024. auto res = client.Get("/");
  7025. ASSERT_TRUE(res);
  7026. ASSERT_EQ(StatusCode::OK_200, res->status);
  7027. auto body = res->body;
  7028. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7029. }
  7030. #if 0
  7031. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7032. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7033. ASSERT_TRUE(cli != nullptr);
  7034. cli->set_address_family(AF_INET6);
  7035. cli->set_interface("en0");
  7036. auto res = cli->Get("/get");
  7037. ASSERT_TRUE(res);
  7038. ASSERT_EQ(StatusCode::OK_200, res->status);
  7039. }
  7040. #endif
  7041. void ClientCertPresent(
  7042. const std::string &client_cert_file,
  7043. const std::string &client_private_key_file,
  7044. const std::string &client_encrypted_private_key_pass = std::string()) {
  7045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7046. CLIENT_CA_CERT_DIR);
  7047. ASSERT_TRUE(svr.is_valid());
  7048. svr.Get("/test", [&](const Request &req, Response &res) {
  7049. res.set_content("test", "text/plain");
  7050. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7051. ASSERT_TRUE(peer_cert != nullptr);
  7052. auto subject_name = X509_get_subject_name(peer_cert);
  7053. ASSERT_TRUE(subject_name != nullptr);
  7054. std::string common_name;
  7055. {
  7056. char name[BUFSIZ];
  7057. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7058. name, sizeof(name));
  7059. common_name.assign(name, static_cast<size_t>(name_len));
  7060. }
  7061. EXPECT_EQ("Common Name", common_name);
  7062. X509_free(peer_cert);
  7063. });
  7064. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7065. auto se = detail::scope_exit([&] {
  7066. svr.stop();
  7067. t.join();
  7068. ASSERT_FALSE(svr.is_running());
  7069. });
  7070. svr.wait_until_ready();
  7071. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7072. client_encrypted_private_key_pass);
  7073. cli.enable_server_certificate_verification(false);
  7074. cli.set_connection_timeout(30);
  7075. auto res = cli.Get("/test");
  7076. ASSERT_TRUE(res);
  7077. ASSERT_EQ(StatusCode::OK_200, res->status);
  7078. }
  7079. TEST(SSLClientServerTest, ClientCertPresent) {
  7080. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7081. }
  7082. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7083. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7084. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7085. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7086. }
  7087. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7088. void MemoryClientCertPresent(
  7089. const std::string &client_cert_file,
  7090. const std::string &client_private_key_file,
  7091. const std::string &client_encrypted_private_key_pass = std::string()) {
  7092. auto f = fopen(SERVER_CERT_FILE, "r+");
  7093. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7094. fclose(f);
  7095. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7096. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7097. fclose(f);
  7098. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7099. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7100. auto client_ca_cert_store = X509_STORE_new();
  7101. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7102. X509_free(client_cert);
  7103. fclose(f);
  7104. f = fopen(client_cert_file.c_str(), "r+");
  7105. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7106. fclose(f);
  7107. f = fopen(client_private_key_file.c_str(), "r+");
  7108. auto client_private_key = PEM_read_PrivateKey(
  7109. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7110. fclose(f);
  7111. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7112. ASSERT_TRUE(svr.is_valid());
  7113. svr.Get("/test", [&](const Request &req, Response &res) {
  7114. res.set_content("test", "text/plain");
  7115. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7116. ASSERT_TRUE(peer_cert != nullptr);
  7117. auto subject_name = X509_get_subject_name(peer_cert);
  7118. ASSERT_TRUE(subject_name != nullptr);
  7119. std::string common_name;
  7120. {
  7121. char name[BUFSIZ];
  7122. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7123. name, sizeof(name));
  7124. common_name.assign(name, static_cast<size_t>(name_len));
  7125. }
  7126. EXPECT_EQ("Common Name", common_name);
  7127. X509_free(peer_cert);
  7128. });
  7129. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7130. auto se = detail::scope_exit([&] {
  7131. svr.stop();
  7132. t.join();
  7133. ASSERT_FALSE(svr.is_running());
  7134. });
  7135. svr.wait_until_ready();
  7136. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7137. client_encrypted_private_key_pass);
  7138. cli.enable_server_certificate_verification(false);
  7139. cli.set_connection_timeout(30);
  7140. auto res = cli.Get("/test");
  7141. ASSERT_TRUE(res);
  7142. ASSERT_EQ(StatusCode::OK_200, res->status);
  7143. X509_free(server_cert);
  7144. EVP_PKEY_free(server_private_key);
  7145. X509_free(client_cert);
  7146. EVP_PKEY_free(client_private_key);
  7147. }
  7148. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7149. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7150. }
  7151. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7152. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7153. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7154. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7155. }
  7156. #endif
  7157. TEST(SSLClientServerTest, ClientCertMissing) {
  7158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7159. CLIENT_CA_CERT_DIR);
  7160. ASSERT_TRUE(svr.is_valid());
  7161. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7162. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7163. auto se = detail::scope_exit([&] {
  7164. svr.stop();
  7165. t.join();
  7166. ASSERT_FALSE(svr.is_running());
  7167. });
  7168. svr.wait_until_ready();
  7169. SSLClient cli(HOST, PORT);
  7170. cli.set_connection_timeout(30);
  7171. auto res = cli.Get("/test");
  7172. ASSERT_TRUE(!res);
  7173. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7174. // For SSL server verification errors, ssl_error should be 0, only
  7175. // ssl_openssl_error should be set
  7176. EXPECT_EQ(0, res.ssl_error());
  7177. // Verify OpenSSL error is captured for SSLServerVerification
  7178. // Note: This test may have different error codes depending on the exact
  7179. // verification failure
  7180. EXPECT_NE(0UL, res.ssl_openssl_error());
  7181. }
  7182. TEST(SSLClientServerTest, TrustDirOptional) {
  7183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7184. ASSERT_TRUE(svr.is_valid());
  7185. svr.Get("/test", [&](const Request &, Response &res) {
  7186. res.set_content("test", "text/plain");
  7187. });
  7188. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7189. auto se = detail::scope_exit([&] {
  7190. svr.stop();
  7191. t.join();
  7192. ASSERT_FALSE(svr.is_running());
  7193. });
  7194. svr.wait_until_ready();
  7195. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7196. cli.enable_server_certificate_verification(false);
  7197. cli.set_connection_timeout(30);
  7198. auto res = cli.Get("/test");
  7199. ASSERT_TRUE(res);
  7200. ASSERT_EQ(StatusCode::OK_200, res->status);
  7201. }
  7202. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7203. class NoListenSSLServer : public SSLServer {
  7204. public:
  7205. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7206. const char *client_ca_cert_file_path,
  7207. const char *client_ca_cert_dir_path = nullptr)
  7208. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7209. client_ca_cert_dir_path),
  7210. stop_(false) {}
  7211. std::atomic_bool stop_;
  7212. private:
  7213. bool process_and_close_socket(socket_t /*sock*/) override {
  7214. // Don't create SSL context
  7215. while (!stop_.load()) {
  7216. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7217. }
  7218. return true;
  7219. }
  7220. };
  7221. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7222. CLIENT_CA_CERT_FILE);
  7223. ASSERT_TRUE(svr.is_valid());
  7224. svr.Get("/test", [&](const Request &, Response &res) {
  7225. res.set_content("test", "text/plain");
  7226. });
  7227. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7228. auto se = detail::scope_exit([&] {
  7229. svr.stop_ = true;
  7230. svr.stop();
  7231. t.join();
  7232. ASSERT_FALSE(svr.is_running());
  7233. });
  7234. svr.wait_until_ready();
  7235. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7236. cli.enable_server_certificate_verification(false);
  7237. cli.set_connection_timeout(1);
  7238. auto res = cli.Get("/test");
  7239. ASSERT_TRUE(!res);
  7240. EXPECT_EQ(Error::SSLConnection, res.error());
  7241. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7242. }
  7243. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7244. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7245. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7246. SSL_CTX_set_options(&ssl_ctx,
  7247. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7248. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7249. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7250. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7251. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7252. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7253. "ECDHE-DSS-AES128-SHA256:"
  7254. "ECDHE-RSA-AES256-SHA256:"
  7255. "ECDHE-DSS-AES256-SHA256:";
  7256. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7257. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7258. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7259. SSL_FILETYPE_PEM) != 1) {
  7260. return false;
  7261. }
  7262. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7263. CLIENT_CA_CERT_DIR);
  7264. SSL_CTX_set_verify(
  7265. &ssl_ctx,
  7266. SSL_VERIFY_PEER |
  7267. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7268. nullptr);
  7269. return true;
  7270. };
  7271. SSLServer svr(setup_ssl_ctx_callback);
  7272. ASSERT_TRUE(svr.is_valid());
  7273. svr.Get("/test", [&](const Request &req, Response &res) {
  7274. res.set_content("test", "text/plain");
  7275. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7276. ASSERT_TRUE(peer_cert != nullptr);
  7277. auto subject_name = X509_get_subject_name(peer_cert);
  7278. ASSERT_TRUE(subject_name != nullptr);
  7279. std::string common_name;
  7280. {
  7281. char name[BUFSIZ];
  7282. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7283. name, sizeof(name));
  7284. common_name.assign(name, static_cast<size_t>(name_len));
  7285. }
  7286. EXPECT_EQ("Common Name", common_name);
  7287. X509_free(peer_cert);
  7288. });
  7289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. t.join();
  7293. ASSERT_FALSE(svr.is_running());
  7294. });
  7295. svr.wait_until_ready();
  7296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7297. cli.enable_server_certificate_verification(false);
  7298. cli.set_connection_timeout(30);
  7299. auto res = cli.Get("/test");
  7300. ASSERT_TRUE(res);
  7301. ASSERT_EQ(StatusCode::OK_200, res->status);
  7302. }
  7303. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7304. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7305. // prepare large data
  7306. std::random_device seed_gen;
  7307. std::mt19937 random(seed_gen());
  7308. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7309. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7310. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7311. // server
  7312. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7313. ASSERT_TRUE(svr.is_valid());
  7314. svr.Post("/binary", [&](const Request &req, Response &res) {
  7315. EXPECT_EQ(large_size_byte, req.body.size());
  7316. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7317. res.set_content(req.body, "application/octet-stream");
  7318. });
  7319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7320. auto se = detail::scope_exit([&] {
  7321. svr.stop();
  7322. listen_thread.join();
  7323. ASSERT_FALSE(svr.is_running());
  7324. });
  7325. svr.wait_until_ready();
  7326. // client POST
  7327. SSLClient cli("localhost", PORT);
  7328. cli.enable_server_certificate_verification(false);
  7329. cli.set_read_timeout(std::chrono::seconds(100));
  7330. cli.set_write_timeout(std::chrono::seconds(100));
  7331. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7332. large_size_byte, "application/octet-stream");
  7333. // compare
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. EXPECT_EQ(large_size_byte, res->body.size());
  7336. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7337. }
  7338. #endif
  7339. #ifdef _WIN32
  7340. TEST(CleanupTest, WSACleanup) {
  7341. int ret = WSACleanup();
  7342. ASSERT_EQ(0, ret);
  7343. }
  7344. #endif
  7345. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7346. TEST(NoSSLSupport, SimpleInterface) {
  7347. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7348. }
  7349. #endif
  7350. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7351. TEST(InvalidScheme, SimpleInterface) {
  7352. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7353. }
  7354. #endif
  7355. TEST(NoScheme, SimpleInterface) {
  7356. Client cli("yahoo.com:80");
  7357. ASSERT_TRUE(cli.is_valid());
  7358. }
  7359. TEST(SendAPI, SimpleInterface_Online) {
  7360. Client cli("http://yahoo.com");
  7361. Request req;
  7362. req.method = "GET";
  7363. req.path = "/";
  7364. auto res = cli.send(req);
  7365. ASSERT_TRUE(res);
  7366. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7367. }
  7368. TEST(SendAPI, WithParamsInRequest) {
  7369. Server svr;
  7370. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7371. EXPECT_TRUE(req.has_param("test"));
  7372. EXPECT_EQ("test_value", req.get_param_value("test"));
  7373. });
  7374. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. });
  7380. svr.wait_until_ready();
  7381. Client cli(HOST, PORT);
  7382. {
  7383. Request req;
  7384. req.method = "GET";
  7385. req.path = "/";
  7386. req.params.emplace("test", "test_value");
  7387. auto res = cli.send(req);
  7388. ASSERT_TRUE(res);
  7389. }
  7390. {
  7391. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7392. ASSERT_TRUE(res);
  7393. }
  7394. }
  7395. TEST(ClientImplMethods, GetSocketTest) {
  7396. httplib::Server svr;
  7397. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7398. res.status = StatusCode::OK_200;
  7399. });
  7400. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7401. auto se = detail::scope_exit([&] {
  7402. svr.stop();
  7403. thread.join();
  7404. ASSERT_FALSE(svr.is_running());
  7405. });
  7406. svr.wait_until_ready();
  7407. {
  7408. httplib::Client cli("http://127.0.0.1:3333");
  7409. cli.set_keep_alive(true);
  7410. // Use the behavior of cpp-httplib of opening the connection
  7411. // only when the first request happens. If that changes,
  7412. // this test would be obsolete.
  7413. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7414. // This also implicitly tests the server. But other tests would fail much
  7415. // earlier than this one to be considered.
  7416. auto res = cli.Get("/");
  7417. ASSERT_TRUE(res);
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7420. }
  7421. }
  7422. // Disabled due to out-of-memory problem on GitHub Actions
  7423. #ifdef _WIN64
  7424. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7425. // allocate content size larger than 2GB in memory
  7426. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7427. char *content = (char *)malloc(content_size);
  7428. ASSERT_TRUE(content);
  7429. Server svr;
  7430. svr.Get("/foo",
  7431. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7432. res.set_content(content, content_size, "application/octet-stream");
  7433. });
  7434. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7435. auto se = detail::scope_exit([&] {
  7436. svr.stop();
  7437. listen_thread.join();
  7438. if (content) free(content);
  7439. ASSERT_FALSE(svr.is_running());
  7440. });
  7441. svr.wait_until_ready();
  7442. Client cli(HOST, PORT);
  7443. auto res = cli.Get("/foo");
  7444. ASSERT_TRUE(res);
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. EXPECT_EQ(content_size, res->body.length());
  7447. }
  7448. #endif
  7449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7450. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7451. Client cli("http://yahoo.com");
  7452. auto res = cli.Get("/");
  7453. ASSERT_TRUE(res);
  7454. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7455. cli.set_follow_location(true);
  7456. res = cli.Get("/");
  7457. ASSERT_TRUE(res);
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7460. }
  7461. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7462. Client cli("https://yahoo.com");
  7463. auto res = cli.Get("/");
  7464. ASSERT_TRUE(res);
  7465. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7466. cli.set_follow_location(true);
  7467. res = cli.Get("/");
  7468. ASSERT_TRUE(res);
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7471. }
  7472. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7473. Client cli("https://yahoo.com");
  7474. auto res = cli.Get("/");
  7475. ASSERT_TRUE(res);
  7476. ASSERT_FALSE(!res);
  7477. ASSERT_TRUE(res);
  7478. ASSERT_FALSE(res == nullptr);
  7479. ASSERT_TRUE(res != nullptr);
  7480. EXPECT_EQ(Error::Success, res.error());
  7481. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7482. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7483. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7484. cli.set_follow_location(true);
  7485. res = cli.Get("/");
  7486. ASSERT_TRUE(res);
  7487. EXPECT_EQ(Error::Success, res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7489. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7490. EXPECT_EQ(StatusCode::OK_200, res->status);
  7491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7492. }
  7493. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7494. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7495. Client cli("https://cdnjs.cloudflare.com");
  7496. auto res =
  7497. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7498. ASSERT_TRUE(res);
  7499. EXPECT_EQ(StatusCode::OK_200, res->status);
  7500. EXPECT_EQ(287630U, res->body.size());
  7501. EXPECT_EQ("application/javascript; charset=utf-8",
  7502. res->get_header_value("Content-Type"));
  7503. }
  7504. #endif
  7505. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7506. #undef REDIR_HOST // Silence compiler warning
  7507. #define REDIR_HOST "https://httpbingo.org"
  7508. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7509. Client cli(REDIR_HOST);
  7510. cli.set_follow_location(true);
  7511. auto res =
  7512. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7513. ASSERT_TRUE(res);
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. }
  7516. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7517. Client cli(REDIR_HOST);
  7518. cli.set_follow_location(true);
  7519. Params params;
  7520. params.emplace("url", "http://example.com");
  7521. params.emplace("status_code", "302");
  7522. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7523. ASSERT_TRUE(res);
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. }
  7526. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7527. Client cli(REDIR_HOST);
  7528. cli.set_follow_location(true);
  7529. Params params;
  7530. params.emplace("url", "http://example.com");
  7531. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7532. ASSERT_TRUE(res);
  7533. EXPECT_EQ(StatusCode::OK_200, res->status);
  7534. }
  7535. TEST(HttpToHttpsRedirectTest, CertFile) {
  7536. Server svr;
  7537. ASSERT_TRUE(svr.is_valid());
  7538. svr.Get("/index", [&](const Request &, Response &res) {
  7539. res.set_redirect("https://127.0.0.1:1235/index");
  7540. svr.stop();
  7541. });
  7542. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7543. ASSERT_TRUE(ssl_svr.is_valid());
  7544. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7545. res.set_content("test", "text/plain");
  7546. ssl_svr.stop();
  7547. });
  7548. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7549. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7550. auto se = detail::scope_exit([&] {
  7551. t2.join();
  7552. t.join();
  7553. ASSERT_FALSE(svr.is_running());
  7554. });
  7555. svr.wait_until_ready();
  7556. ssl_svr.wait_until_ready();
  7557. Client cli("127.0.0.1", PORT);
  7558. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7559. cli.enable_server_certificate_verification(true);
  7560. cli.set_follow_location(true);
  7561. cli.set_connection_timeout(30);
  7562. auto res = cli.Get("/index");
  7563. ASSERT_TRUE(res);
  7564. ASSERT_EQ(StatusCode::OK_200, res->status);
  7565. }
  7566. TEST(SSLClientRedirectTest, CertFile) {
  7567. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7568. ASSERT_TRUE(ssl_svr1.is_valid());
  7569. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7570. res.set_redirect("https://127.0.0.1:1235/index");
  7571. ssl_svr1.stop();
  7572. });
  7573. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7574. ASSERT_TRUE(ssl_svr2.is_valid());
  7575. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7576. res.set_content("test", "text/plain");
  7577. ssl_svr2.stop();
  7578. });
  7579. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7580. thread t2 =
  7581. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7582. auto se = detail::scope_exit([&] {
  7583. t2.join();
  7584. t.join();
  7585. ASSERT_FALSE(ssl_svr1.is_running());
  7586. });
  7587. ssl_svr1.wait_until_ready();
  7588. ssl_svr2.wait_until_ready();
  7589. SSLClient cli("127.0.0.1", PORT);
  7590. std::string cert;
  7591. read_file(SERVER_CERT2_FILE, cert);
  7592. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7593. cli.enable_server_certificate_verification(true);
  7594. cli.set_follow_location(true);
  7595. cli.set_connection_timeout(30);
  7596. auto res = cli.Get("/index");
  7597. ASSERT_TRUE(res);
  7598. ASSERT_EQ(StatusCode::OK_200, res->status);
  7599. }
  7600. TEST(MultipartFormDataTest, LargeData) {
  7601. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7602. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7603. const ContentReader &content_reader) {
  7604. if (req.is_multipart_form_data()) {
  7605. std::vector<FormData> items;
  7606. content_reader(
  7607. [&](const FormData &file) {
  7608. items.push_back(file);
  7609. return true;
  7610. },
  7611. [&](const char *data, size_t data_length) {
  7612. items.back().content.append(data, data_length);
  7613. return true;
  7614. });
  7615. EXPECT_TRUE(std::string(items[0].name) == "document");
  7616. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7617. EXPECT_TRUE(items[0].filename == "2MB_data");
  7618. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7619. EXPECT_TRUE(items[1].name == "hello");
  7620. EXPECT_TRUE(items[1].content == "world");
  7621. EXPECT_TRUE(items[1].filename == "");
  7622. EXPECT_TRUE(items[1].content_type == "");
  7623. } else {
  7624. std::string body;
  7625. content_reader([&](const char *data, size_t data_length) {
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. }
  7630. });
  7631. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7632. auto se = detail::scope_exit([&] {
  7633. svr.stop();
  7634. t.join();
  7635. ASSERT_FALSE(svr.is_running());
  7636. });
  7637. svr.wait_until_ready();
  7638. {
  7639. std::string data(1024 * 1024 * 2, '.');
  7640. std::stringstream buffer;
  7641. buffer << data;
  7642. Client cli("https://localhost:8080");
  7643. cli.enable_server_certificate_verification(false);
  7644. UploadFormDataItems items{
  7645. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7646. {"hello", "world", "", ""},
  7647. };
  7648. auto res = cli.Post("/post", items);
  7649. ASSERT_TRUE(res);
  7650. ASSERT_EQ(StatusCode::OK_200, res->status);
  7651. }
  7652. }
  7653. TEST(MultipartFormDataTest, DataProviderItems) {
  7654. std::random_device seed_gen;
  7655. std::mt19937 random(seed_gen());
  7656. std::string rand1;
  7657. rand1.resize(1000);
  7658. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7659. std::string rand2;
  7660. rand2.resize(3000);
  7661. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7663. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7664. const ContentReader &content_reader) {
  7665. ASSERT_FALSE(req.is_multipart_form_data());
  7666. std::string body;
  7667. content_reader([&](const char *data, size_t data_length) {
  7668. body.append(data, data_length);
  7669. return true;
  7670. });
  7671. EXPECT_EQ(body, "");
  7672. });
  7673. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7674. const ContentReader &content_reader) {
  7675. ASSERT_TRUE(req.is_multipart_form_data());
  7676. std::vector<FormData> items;
  7677. content_reader(
  7678. [&](const FormData &file) {
  7679. items.push_back(file);
  7680. return true;
  7681. },
  7682. [&](const char *data, size_t data_length) {
  7683. items.back().content.append(data, data_length);
  7684. return true;
  7685. });
  7686. ASSERT_TRUE(items.size() == 2);
  7687. EXPECT_EQ(std::string(items[0].name), "name1");
  7688. EXPECT_EQ(items[0].content, "Testing123");
  7689. EXPECT_EQ(items[0].filename, "filename1");
  7690. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7691. EXPECT_EQ(items[1].name, "name2");
  7692. EXPECT_EQ(items[1].content, "Testing456");
  7693. EXPECT_EQ(items[1].filename, "");
  7694. EXPECT_EQ(items[1].content_type, "");
  7695. });
  7696. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7697. const ContentReader &content_reader) {
  7698. ASSERT_TRUE(req.is_multipart_form_data());
  7699. std::vector<FormData> items;
  7700. content_reader(
  7701. [&](const FormData &file) {
  7702. items.push_back(file);
  7703. return true;
  7704. },
  7705. [&](const char *data, size_t data_length) {
  7706. items.back().content.append(data, data_length);
  7707. return true;
  7708. });
  7709. ASSERT_TRUE(items.size() == 2);
  7710. EXPECT_EQ(items[0].name, "name3");
  7711. EXPECT_EQ(items[0].content, rand1);
  7712. EXPECT_EQ(items[0].filename, "filename3");
  7713. EXPECT_EQ(items[0].content_type, "");
  7714. EXPECT_EQ(items[1].name, "name4");
  7715. EXPECT_EQ(items[1].content, rand2);
  7716. EXPECT_EQ(items[1].filename, "filename4");
  7717. EXPECT_EQ(items[1].content_type, "");
  7718. });
  7719. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7720. const ContentReader &content_reader) {
  7721. ASSERT_TRUE(req.is_multipart_form_data());
  7722. std::vector<FormData> items;
  7723. content_reader(
  7724. [&](const FormData &file) {
  7725. items.push_back(file);
  7726. return true;
  7727. },
  7728. [&](const char *data, size_t data_length) {
  7729. items.back().content.append(data, data_length);
  7730. return true;
  7731. });
  7732. ASSERT_TRUE(items.size() == 4);
  7733. EXPECT_EQ(std::string(items[0].name), "name1");
  7734. EXPECT_EQ(items[0].content, "Testing123");
  7735. EXPECT_EQ(items[0].filename, "filename1");
  7736. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7737. EXPECT_EQ(items[1].name, "name2");
  7738. EXPECT_EQ(items[1].content, "Testing456");
  7739. EXPECT_EQ(items[1].filename, "");
  7740. EXPECT_EQ(items[1].content_type, "");
  7741. EXPECT_EQ(items[2].name, "name3");
  7742. EXPECT_EQ(items[2].content, rand1);
  7743. EXPECT_EQ(items[2].filename, "filename3");
  7744. EXPECT_EQ(items[2].content_type, "");
  7745. EXPECT_EQ(items[3].name, "name4");
  7746. EXPECT_EQ(items[3].content, rand2);
  7747. EXPECT_EQ(items[3].filename, "filename4");
  7748. EXPECT_EQ(items[3].content_type, "");
  7749. });
  7750. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7751. auto se = detail::scope_exit([&] {
  7752. svr.stop();
  7753. t.join();
  7754. ASSERT_FALSE(svr.is_running());
  7755. });
  7756. svr.wait_until_ready();
  7757. {
  7758. Client cli("https://localhost:8080");
  7759. cli.enable_server_certificate_verification(false);
  7760. UploadFormDataItems items{
  7761. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7762. {"name2", "Testing456", "", ""}, // not a file
  7763. };
  7764. {
  7765. auto res = cli.Post("/post-none", {}, {}, {});
  7766. ASSERT_TRUE(res);
  7767. ASSERT_EQ(StatusCode::OK_200, res->status);
  7768. }
  7769. FormDataProviderItems providers;
  7770. {
  7771. auto res =
  7772. cli.Post("/post-items", {}, items, providers); // empty providers
  7773. ASSERT_TRUE(res);
  7774. ASSERT_EQ(StatusCode::OK_200, res->status);
  7775. }
  7776. providers.push_back({"name3",
  7777. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7778. // test the offset is given correctly at each step
  7779. if (!offset)
  7780. sink.os.write(rand1.data(), 30);
  7781. else if (offset == 30)
  7782. sink.os.write(rand1.data() + 30, 300);
  7783. else if (offset == 330)
  7784. sink.os.write(rand1.data() + 330, 670);
  7785. else if (offset == rand1.size())
  7786. sink.done();
  7787. return true;
  7788. },
  7789. "filename3",
  7790. {}});
  7791. providers.push_back({"name4",
  7792. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7793. // test the offset is given correctly at each step
  7794. if (!offset)
  7795. sink.os.write(rand2.data(), 2000);
  7796. else if (offset == 2000)
  7797. sink.os.write(rand2.data() + 2000, 1);
  7798. else if (offset == 2001)
  7799. sink.os.write(rand2.data() + 2001, 999);
  7800. else if (offset == rand2.size())
  7801. sink.done();
  7802. return true;
  7803. },
  7804. "filename4",
  7805. {}});
  7806. {
  7807. auto res = cli.Post("/post-providers", {}, {}, providers);
  7808. ASSERT_TRUE(res);
  7809. ASSERT_EQ(StatusCode::OK_200, res->status);
  7810. }
  7811. {
  7812. auto res = cli.Post("/post-both", {}, items, providers);
  7813. ASSERT_TRUE(res);
  7814. ASSERT_EQ(StatusCode::OK_200, res->status);
  7815. }
  7816. }
  7817. }
  7818. TEST(MultipartFormDataTest, BadHeader) {
  7819. Server svr;
  7820. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7821. res.set_content("ok", "text/plain");
  7822. });
  7823. thread t = thread([&] { svr.listen(HOST, PORT); });
  7824. auto se = detail::scope_exit([&] {
  7825. svr.stop();
  7826. t.join();
  7827. ASSERT_FALSE(svr.is_running());
  7828. });
  7829. svr.wait_until_ready();
  7830. const std::string body =
  7831. "This is the preamble. It is to be ignored, though it\r\n"
  7832. "is a handy place for composition agents to include an\r\n"
  7833. "explanatory note to non-MIME conformant readers.\r\n"
  7834. "\r\n"
  7835. "\r\n"
  7836. "--simple boundary\r\n"
  7837. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7838. ": BAD...\r\n"
  7839. "\r\n"
  7840. "value1\r\n"
  7841. "--simple boundary\r\n"
  7842. "Content-Disposition: form-data; name=\"field2\"; "
  7843. "filename=\"example.txt\"\r\n"
  7844. "\r\n"
  7845. "value2\r\n"
  7846. "--simple boundary--\r\n"
  7847. "This is the epilogue. It is also to be ignored.\r\n";
  7848. std::string content_type =
  7849. R"(multipart/form-data; boundary="simple boundary")";
  7850. Client cli(HOST, PORT);
  7851. auto res = cli.Post("/post", body, content_type.c_str());
  7852. ASSERT_TRUE(res);
  7853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7854. }
  7855. TEST(MultipartFormDataTest, WithPreamble) {
  7856. Server svr;
  7857. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7858. res.set_content("ok", "text/plain");
  7859. });
  7860. thread t = thread([&] { svr.listen(HOST, PORT); });
  7861. auto se = detail::scope_exit([&] {
  7862. svr.stop();
  7863. t.join();
  7864. ASSERT_FALSE(svr.is_running());
  7865. });
  7866. svr.wait_until_ready();
  7867. const std::string body =
  7868. "This is the preamble. It is to be ignored, though it\r\n"
  7869. "is a handy place for composition agents to include an\r\n"
  7870. "explanatory note to non-MIME conformant readers.\r\n"
  7871. "\r\n"
  7872. "\r\n"
  7873. "--simple boundary\r\n"
  7874. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7875. "\r\n"
  7876. "value1\r\n"
  7877. "--simple boundary\r\n"
  7878. "Content-Disposition: form-data; name=\"field2\"; "
  7879. "filename=\"example.txt\"\r\n"
  7880. "\r\n"
  7881. "value2\r\n"
  7882. "--simple boundary--\r\n"
  7883. "This is the epilogue. It is also to be ignored.\r\n";
  7884. std::string content_type =
  7885. R"(multipart/form-data; boundary="simple boundary")";
  7886. Client cli(HOST, PORT);
  7887. auto res = cli.Post("/post", body, content_type.c_str());
  7888. ASSERT_TRUE(res);
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. }
  7891. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7892. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7893. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7894. const ContentReader &content_reader) {
  7895. if (req.is_multipart_form_data()) {
  7896. std::vector<FormData> items;
  7897. content_reader(
  7898. [&](const FormData &file) {
  7899. items.push_back(file);
  7900. return true;
  7901. },
  7902. [&](const char *data, size_t data_length) {
  7903. items.back().content.append(data, data_length);
  7904. return true;
  7905. });
  7906. EXPECT_TRUE(std::string(items[0].name) == "document");
  7907. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7908. EXPECT_TRUE(items[0].filename == "2MB_data");
  7909. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7910. EXPECT_TRUE(items[1].name == "hello");
  7911. EXPECT_TRUE(items[1].content == "world");
  7912. EXPECT_TRUE(items[1].filename == "");
  7913. EXPECT_TRUE(items[1].content_type == "");
  7914. } else {
  7915. std::string body;
  7916. content_reader([&](const char *data, size_t data_length) {
  7917. body.append(data, data_length);
  7918. return true;
  7919. });
  7920. }
  7921. });
  7922. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7923. auto se = detail::scope_exit([&] {
  7924. svr.stop();
  7925. t.join();
  7926. ASSERT_FALSE(svr.is_running());
  7927. });
  7928. svr.wait_until_ready();
  7929. {
  7930. std::string data(1024 * 1024 * 2, '.');
  7931. std::stringstream buffer;
  7932. buffer << data;
  7933. Client cli("https://localhost:8080");
  7934. cli.enable_server_certificate_verification(false);
  7935. UploadFormDataItems items{
  7936. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7937. {"hello", "world", "", ""},
  7938. };
  7939. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7940. ASSERT_TRUE(res);
  7941. ASSERT_EQ(StatusCode::OK_200, res->status);
  7942. }
  7943. }
  7944. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7945. std::string data(1024 * 1024 * 2, '&');
  7946. std::stringstream buffer;
  7947. buffer << data;
  7948. Client cli("https://localhost:8080");
  7949. UploadFormDataItems items{
  7950. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7951. {"hello", "world", "", ""},
  7952. };
  7953. for (const char &c : " \t\r\n") {
  7954. auto res =
  7955. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7956. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7957. ASSERT_FALSE(res);
  7958. }
  7959. }
  7960. TEST(MultipartFormDataTest, PutFormData) {
  7961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7962. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7963. const ContentReader &content_reader) {
  7964. if (req.is_multipart_form_data()) {
  7965. std::vector<FormData> items;
  7966. content_reader(
  7967. [&](const FormData &file) {
  7968. items.push_back(file);
  7969. return true;
  7970. },
  7971. [&](const char *data, size_t data_length) {
  7972. items.back().content.append(data, data_length);
  7973. return true;
  7974. });
  7975. EXPECT_TRUE(std::string(items[0].name) == "document");
  7976. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7977. EXPECT_TRUE(items[0].filename == "2MB_data");
  7978. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7979. EXPECT_TRUE(items[1].name == "hello");
  7980. EXPECT_TRUE(items[1].content == "world");
  7981. EXPECT_TRUE(items[1].filename == "");
  7982. EXPECT_TRUE(items[1].content_type == "");
  7983. } else {
  7984. std::string body;
  7985. content_reader([&](const char *data, size_t data_length) {
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. }
  7990. });
  7991. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7992. auto se = detail::scope_exit([&] {
  7993. svr.stop();
  7994. t.join();
  7995. ASSERT_FALSE(svr.is_running());
  7996. });
  7997. svr.wait_until_ready();
  7998. {
  7999. std::string data(1024 * 1024 * 2, '&');
  8000. std::stringstream buffer;
  8001. buffer << data;
  8002. Client cli("https://localhost:8080");
  8003. cli.enable_server_certificate_verification(false);
  8004. UploadFormDataItems items{
  8005. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8006. {"hello", "world", "", ""},
  8007. };
  8008. auto res = cli.Put("/put", items);
  8009. ASSERT_TRUE(res);
  8010. ASSERT_EQ(StatusCode::OK_200, res->status);
  8011. }
  8012. }
  8013. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8015. svr.Put("/put_customboundary",
  8016. [&](const Request &req, const Response & /*res*/,
  8017. const ContentReader &content_reader) {
  8018. if (req.is_multipart_form_data()) {
  8019. std::vector<FormData> items;
  8020. content_reader(
  8021. [&](const FormData &file) {
  8022. items.push_back(file);
  8023. return true;
  8024. },
  8025. [&](const char *data, size_t data_length) {
  8026. items.back().content.append(data, data_length);
  8027. return true;
  8028. });
  8029. EXPECT_TRUE(std::string(items[0].name) == "document");
  8030. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8031. EXPECT_TRUE(items[0].filename == "2MB_data");
  8032. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8033. EXPECT_TRUE(items[1].name == "hello");
  8034. EXPECT_TRUE(items[1].content == "world");
  8035. EXPECT_TRUE(items[1].filename == "");
  8036. EXPECT_TRUE(items[1].content_type == "");
  8037. } else {
  8038. std::string body;
  8039. content_reader([&](const char *data, size_t data_length) {
  8040. body.append(data, data_length);
  8041. return true;
  8042. });
  8043. }
  8044. });
  8045. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8046. auto se = detail::scope_exit([&] {
  8047. svr.stop();
  8048. t.join();
  8049. ASSERT_FALSE(svr.is_running());
  8050. });
  8051. svr.wait_until_ready();
  8052. {
  8053. std::string data(1024 * 1024 * 2, '&');
  8054. std::stringstream buffer;
  8055. buffer << data;
  8056. Client cli("https://localhost:8080");
  8057. cli.enable_server_certificate_verification(false);
  8058. UploadFormDataItems items{
  8059. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8060. {"hello", "world", "", ""},
  8061. };
  8062. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8063. ASSERT_TRUE(res);
  8064. ASSERT_EQ(StatusCode::OK_200, res->status);
  8065. }
  8066. }
  8067. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8068. std::string data(1024 * 1024 * 2, '&');
  8069. std::stringstream buffer;
  8070. buffer << data;
  8071. Client cli("https://localhost:8080");
  8072. cli.enable_server_certificate_verification(false);
  8073. UploadFormDataItems items{
  8074. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8075. {"hello", "world", "", ""},
  8076. };
  8077. for (const char &c : " \t\r\n") {
  8078. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8079. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8080. ASSERT_FALSE(res);
  8081. }
  8082. }
  8083. TEST(MultipartFormDataTest, AlternateFilename) {
  8084. auto handled = false;
  8085. Server svr;
  8086. svr.Post("/test", [&](const Request &req, Response &res) {
  8087. ASSERT_EQ(2u, req.form.files.size());
  8088. ASSERT_EQ(1u, req.form.fields.size());
  8089. // Test files
  8090. const auto &file1 = req.form.get_file("file1");
  8091. ASSERT_EQ("file1", file1.name);
  8092. ASSERT_EQ("A.txt", file1.filename);
  8093. ASSERT_EQ("text/plain", file1.content_type);
  8094. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8095. const auto &file2 = req.form.get_file("file2");
  8096. ASSERT_EQ("file2", file2.name);
  8097. ASSERT_EQ("a.html", file2.filename);
  8098. ASSERT_EQ("text/html", file2.content_type);
  8099. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8100. file2.content);
  8101. // Test text field
  8102. const auto &text = req.form.get_field("text");
  8103. ASSERT_EQ("text default", text);
  8104. res.set_content("ok", "text/plain");
  8105. handled = true;
  8106. });
  8107. thread t = thread([&] { svr.listen(HOST, PORT); });
  8108. auto se = detail::scope_exit([&] {
  8109. svr.stop();
  8110. t.join();
  8111. ASSERT_FALSE(svr.is_running());
  8112. ASSERT_TRUE(handled);
  8113. });
  8114. svr.wait_until_ready();
  8115. auto req = "POST /test HTTP/1.1\r\n"
  8116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8117. "Content-Length: 399\r\n"
  8118. "\r\n"
  8119. "----------\r\n"
  8120. "Content-Disposition: form-data; name=\"text\"\r\n"
  8121. "\r\n"
  8122. "text default\r\n"
  8123. "----------\r\n"
  8124. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8125. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8126. "Content-Type: text/plain\r\n"
  8127. "\r\n"
  8128. "Content of a.txt.\r\n"
  8129. "\r\n"
  8130. "----------\r\n"
  8131. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8132. "\"a.html\"\r\n"
  8133. "Content-Type: text/html\r\n"
  8134. "\r\n"
  8135. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8136. "\r\n"
  8137. "------------\r\n";
  8138. ASSERT_TRUE(send_request(1, req));
  8139. }
  8140. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8141. auto handled = false;
  8142. Server svr;
  8143. svr.Post("/test", [&](const Request &req, Response &) {
  8144. ASSERT_EQ(2u, req.form.fields.size());
  8145. const auto &text1 = req.form.get_field("text1");
  8146. ASSERT_EQ("text1", text1);
  8147. const auto &text2 = req.form.get_field("text2");
  8148. ASSERT_EQ("text2", text2);
  8149. handled = true;
  8150. });
  8151. thread t = thread([&] { svr.listen(HOST, PORT); });
  8152. auto se = detail::scope_exit([&] {
  8153. svr.stop();
  8154. t.join();
  8155. ASSERT_FALSE(svr.is_running());
  8156. ASSERT_TRUE(handled);
  8157. });
  8158. svr.wait_until_ready();
  8159. auto req = "POST /test HTTP/1.1\r\n"
  8160. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8161. "Content-Length: 146\r\n"
  8162. "\r\n----------\r\n"
  8163. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8164. "\r\n"
  8165. "text1"
  8166. "\r\n----------\r\n"
  8167. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8168. "\r\n"
  8169. "text2"
  8170. "\r\n------------";
  8171. std::string response;
  8172. ASSERT_TRUE(send_request(1, req, &response));
  8173. ASSERT_EQ("200", response.substr(9, 3));
  8174. }
  8175. TEST(MultipartFormDataTest, ContentLength) {
  8176. auto handled = false;
  8177. Server svr;
  8178. svr.Post("/test", [&](const Request &req, Response &) {
  8179. ASSERT_EQ(2u, req.form.fields.size());
  8180. const auto &text1 = req.form.get_field("text1");
  8181. ASSERT_EQ("text1", text1);
  8182. const auto &text2 = req.form.get_field("text2");
  8183. ASSERT_EQ("text2", text2);
  8184. handled = true;
  8185. });
  8186. thread t = thread([&] { svr.listen(HOST, PORT); });
  8187. auto se = detail::scope_exit([&] {
  8188. svr.stop();
  8189. t.join();
  8190. ASSERT_FALSE(svr.is_running());
  8191. ASSERT_TRUE(handled);
  8192. });
  8193. svr.wait_until_ready();
  8194. auto req = "POST /test HTTP/1.1\r\n"
  8195. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8196. "Content-Length: 167\r\n"
  8197. "\r\n----------\r\n"
  8198. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8199. "Content-Length: 5\r\n"
  8200. "\r\n"
  8201. "text1"
  8202. "\r\n----------\r\n"
  8203. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8204. "\r\n"
  8205. "text2"
  8206. "\r\n------------\r\n";
  8207. std::string response;
  8208. ASSERT_TRUE(send_request(1, req, &response));
  8209. ASSERT_EQ("200", response.substr(9, 3));
  8210. }
  8211. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8212. auto handled = false;
  8213. Server svr;
  8214. svr.Post("/test", [&](const Request &req, Response &) {
  8215. ASSERT_EQ(2u, req.form.fields.size());
  8216. const auto &text1 = req.form.get_field("text1");
  8217. ASSERT_EQ("text1", text1);
  8218. // TODO: Add header access for text fields if needed
  8219. const auto &text2 = req.form.get_field("text2");
  8220. ASSERT_EQ("text2", text2);
  8221. // TODO: Header access for text fields needs to be implemented
  8222. // auto &headers = it->second.headers;
  8223. // ASSERT_EQ(3U, headers.size());
  8224. // auto custom_header = headers.find("x-whatever");
  8225. // ASSERT_TRUE(custom_header != headers.end());
  8226. // ASSERT_NE("customvalue", custom_header->second);
  8227. // ASSERT_EQ("CustomValue", custom_header->second);
  8228. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8229. handled = true;
  8230. });
  8231. thread t = thread([&] { svr.listen(HOST, PORT); });
  8232. auto se = detail::scope_exit([&] {
  8233. svr.stop();
  8234. t.join();
  8235. ASSERT_FALSE(svr.is_running());
  8236. ASSERT_TRUE(handled);
  8237. });
  8238. svr.wait_until_ready();
  8239. auto req = "POST /test HTTP/1.1\r\n"
  8240. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8241. "Content-Length: 232\r\n"
  8242. "\r\n----------\r\n"
  8243. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8244. "Content-Length: 5\r\n"
  8245. "X-Test: 1\r\n"
  8246. "\r\n"
  8247. "text1"
  8248. "\r\n----------\r\n"
  8249. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8250. "Content-Type: text/plain\r\n"
  8251. "X-Whatever: CustomValue\r\n"
  8252. "\r\n"
  8253. "text2"
  8254. "\r\n------------\r\n"
  8255. "That should be disregarded. Not even read";
  8256. std::string response;
  8257. ASSERT_TRUE(send_request(1, req, &response));
  8258. ASSERT_EQ("200", response.substr(9, 3));
  8259. }
  8260. #endif
  8261. TEST(MultipartFormDataTest, LargeHeader) {
  8262. auto handled = false;
  8263. Server svr;
  8264. svr.Post("/test", [&](const Request &req, Response &) {
  8265. ASSERT_EQ(1u, req.form.fields.size());
  8266. const auto &text = req.form.get_field("name1");
  8267. ASSERT_EQ("text1", text);
  8268. handled = true;
  8269. });
  8270. thread t = thread([&] { svr.listen(HOST, PORT); });
  8271. auto se = detail::scope_exit([&] {
  8272. svr.stop();
  8273. t.join();
  8274. ASSERT_FALSE(svr.is_running());
  8275. ASSERT_TRUE(handled);
  8276. });
  8277. svr.wait_until_ready();
  8278. auto boundary = std::string("cpp-httplib-multipart-data");
  8279. std::string content = "--" + boundary +
  8280. "\r\n"
  8281. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8282. "\r\n"
  8283. "text1\r\n"
  8284. "--" +
  8285. boundary + "--\r\n";
  8286. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8287. "Content-Type: multipart/form-data;boundary=" +
  8288. boundary +
  8289. "\r\n"
  8290. "Content-Length: " +
  8291. std::to_string(content.size()) +
  8292. "\r\n"
  8293. "Dummy-Header: ";
  8294. std::string header_suffix = "\r\n"
  8295. "\r\n";
  8296. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8297. size_t header_dummy_size =
  8298. read_buff_size -
  8299. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8300. auto header_dummy = std::string(header_dummy_size, '@');
  8301. auto req = header_prefix + header_dummy + header_suffix + content;
  8302. std::string response;
  8303. ASSERT_TRUE(send_request(1, req, &response));
  8304. ASSERT_EQ("200", response.substr(9, 3));
  8305. }
  8306. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8307. static constexpr unsigned int number_of_tasks{1000000};
  8308. std::atomic_uint count{0};
  8309. std::unique_ptr<TaskQueue> task_queue{
  8310. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8311. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8312. auto queued = task_queue->enqueue(
  8313. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8314. EXPECT_TRUE(queued);
  8315. }
  8316. EXPECT_NO_THROW(task_queue->shutdown());
  8317. EXPECT_EQ(number_of_tasks, count.load());
  8318. }
  8319. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8320. static constexpr unsigned int number_of_tasks{1000000};
  8321. static constexpr unsigned int qlimit{2};
  8322. unsigned int queued_count{0};
  8323. std::atomic_uint count{0};
  8324. std::unique_ptr<TaskQueue> task_queue{
  8325. new ThreadPool{/*num_threads=*/1, qlimit}};
  8326. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8327. if (task_queue->enqueue(
  8328. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8329. queued_count++;
  8330. }
  8331. }
  8332. EXPECT_NO_THROW(task_queue->shutdown());
  8333. EXPECT_EQ(queued_count, count.load());
  8334. EXPECT_TRUE(queued_count <= number_of_tasks);
  8335. EXPECT_TRUE(queued_count >= qlimit);
  8336. }
  8337. TEST(TaskQueueTest, MaxQueuedRequests) {
  8338. static constexpr unsigned int qlimit{3};
  8339. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8340. std::condition_variable sem_cv;
  8341. std::mutex sem_mtx;
  8342. int credits = 0;
  8343. bool queued;
  8344. /* Fill up the queue with tasks that will block until we give them credits to
  8345. * complete. */
  8346. for (unsigned int n = 0; n <= qlimit;) {
  8347. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8348. std::unique_lock<std::mutex> lock(sem_mtx);
  8349. while (credits <= 0) {
  8350. sem_cv.wait(lock);
  8351. }
  8352. /* Consume the credit and signal the test code if they are all gone. */
  8353. if (--credits == 0) { sem_cv.notify_one(); }
  8354. });
  8355. if (n < qlimit) {
  8356. /* The first qlimit enqueues must succeed. */
  8357. EXPECT_TRUE(queued);
  8358. } else {
  8359. /* The last one will succeed only when the worker thread
  8360. * starts and dequeues the first blocking task. Although
  8361. * not necessary for the correctness of this test, we sleep for
  8362. * a short while to avoid busy waiting. */
  8363. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8364. }
  8365. if (queued) { n++; }
  8366. }
  8367. /* Further enqueues must fail since the queue is full. */
  8368. for (auto i = 0; i < 4; i++) {
  8369. queued = task_queue->enqueue([] {});
  8370. EXPECT_FALSE(queued);
  8371. }
  8372. /* Give the credits to allow the previous tasks to complete. */
  8373. {
  8374. std::unique_lock<std::mutex> lock(sem_mtx);
  8375. credits += qlimit + 1;
  8376. }
  8377. sem_cv.notify_all();
  8378. /* Wait for all the credits to be consumed. */
  8379. {
  8380. std::unique_lock<std::mutex> lock(sem_mtx);
  8381. while (credits > 0) {
  8382. sem_cv.wait(lock);
  8383. }
  8384. }
  8385. /* Check that we are able again to enqueue at least qlimit tasks. */
  8386. for (unsigned int i = 0; i < qlimit; i++) {
  8387. queued = task_queue->enqueue([] {});
  8388. EXPECT_TRUE(queued);
  8389. }
  8390. EXPECT_NO_THROW(task_queue->shutdown());
  8391. }
  8392. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8393. Server svr;
  8394. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8395. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8396. });
  8397. svr.Get("/hello", [](const Request &req, Response &res) {
  8398. res.set_content(req.get_param_value("key"), "text/plain");
  8399. });
  8400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8401. auto se = detail::scope_exit([&] {
  8402. svr.stop();
  8403. thread.join();
  8404. ASSERT_FALSE(svr.is_running());
  8405. });
  8406. svr.wait_until_ready();
  8407. {
  8408. Client cli(HOST, PORT);
  8409. cli.set_follow_location(true);
  8410. auto res = cli.Get("/");
  8411. ASSERT_TRUE(res);
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("val&key2=val2", res->body);
  8414. }
  8415. }
  8416. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8417. Server svr;
  8418. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8419. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8420. });
  8421. svr.Get("/hello", [](const Request &req, Response &res) {
  8422. res.set_content(req.get_param_value("key"), "text/plain");
  8423. });
  8424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8425. auto se = detail::scope_exit([&] {
  8426. svr.stop();
  8427. thread.join();
  8428. ASSERT_FALSE(svr.is_running());
  8429. });
  8430. svr.wait_until_ready();
  8431. {
  8432. Client cli(HOST, PORT);
  8433. cli.set_follow_location(true);
  8434. auto res = cli.Get("/");
  8435. ASSERT_TRUE(res);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8438. }
  8439. }
  8440. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8441. TEST(RedirectTest, Issue2185_Online) {
  8442. SSLClient client("github.com");
  8443. client.set_follow_location(true);
  8444. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8445. "Coollab-Windows.zip");
  8446. ASSERT_TRUE(res);
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. EXPECT_EQ(9920427U, res->body.size());
  8449. }
  8450. #endif
  8451. TEST(VulnerabilityTest, CRLFInjection) {
  8452. Server svr;
  8453. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8454. res.set_content("Hello 1", "text/plain");
  8455. });
  8456. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8457. res.set_content("Hello 2", "text/plain");
  8458. });
  8459. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8460. res.set_content("Hello 3", "text/plain");
  8461. });
  8462. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8463. res.set_content("Hello 4", "text/plain");
  8464. });
  8465. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8466. for (const auto &x : req.headers) {
  8467. auto key = x.first;
  8468. EXPECT_STRNE("evil", key.c_str());
  8469. }
  8470. });
  8471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8472. auto se = detail::scope_exit([&] {
  8473. svr.stop();
  8474. thread.join();
  8475. ASSERT_FALSE(svr.is_running());
  8476. });
  8477. svr.wait_until_ready();
  8478. {
  8479. Client cli(HOST, PORT);
  8480. cli.Post("/test1", "A=B",
  8481. "application/x-www-form-urlencoded\r\nevil: hello1");
  8482. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8483. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8484. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8485. }
  8486. }
  8487. TEST(PathParamsTest, StaticMatch) {
  8488. const auto pattern = "/users/all";
  8489. detail::PathParamsMatcher matcher(pattern);
  8490. Request request;
  8491. request.path = "/users/all";
  8492. ASSERT_TRUE(matcher.match(request));
  8493. std::unordered_map<std::string, std::string> expected_params = {};
  8494. EXPECT_EQ(request.path_params, expected_params);
  8495. }
  8496. TEST(PathParamsTest, StaticMismatch) {
  8497. const auto pattern = "/users/all";
  8498. detail::PathParamsMatcher matcher(pattern);
  8499. Request request;
  8500. request.path = "/users/1";
  8501. ASSERT_FALSE(matcher.match(request));
  8502. }
  8503. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8504. const auto pattern = "/users/:id/subscriptions";
  8505. detail::PathParamsMatcher matcher(pattern);
  8506. Request request;
  8507. request.path = "/users/42/subscriptions";
  8508. ASSERT_TRUE(matcher.match(request));
  8509. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8510. EXPECT_EQ(request.path_params, expected_params);
  8511. }
  8512. TEST(PathParamsTest, SingleParamInTheEnd) {
  8513. const auto pattern = "/users/:id";
  8514. detail::PathParamsMatcher matcher(pattern);
  8515. Request request;
  8516. request.path = "/users/24";
  8517. ASSERT_TRUE(matcher.match(request));
  8518. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8519. EXPECT_EQ(request.path_params, expected_params);
  8520. }
  8521. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8522. const auto pattern = "/users/:id/";
  8523. detail::PathParamsMatcher matcher(pattern);
  8524. Request request;
  8525. request.path = "/users/42/";
  8526. ASSERT_TRUE(matcher.match(request));
  8527. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8528. EXPECT_EQ(request.path_params, expected_params);
  8529. }
  8530. TEST(PathParamsTest, EmptyParam) {
  8531. const auto pattern = "/users/:id/";
  8532. detail::PathParamsMatcher matcher(pattern);
  8533. Request request;
  8534. request.path = "/users//";
  8535. ASSERT_TRUE(matcher.match(request));
  8536. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8537. EXPECT_EQ(request.path_params, expected_params);
  8538. }
  8539. TEST(PathParamsTest, FragmentMismatch) {
  8540. const auto pattern = "/users/:id/";
  8541. detail::PathParamsMatcher matcher(pattern);
  8542. Request request;
  8543. request.path = "/admins/24/";
  8544. ASSERT_FALSE(matcher.match(request));
  8545. }
  8546. TEST(PathParamsTest, ExtraFragments) {
  8547. const auto pattern = "/users/:id";
  8548. detail::PathParamsMatcher matcher(pattern);
  8549. Request request;
  8550. request.path = "/users/42/subscriptions";
  8551. ASSERT_FALSE(matcher.match(request));
  8552. }
  8553. TEST(PathParamsTest, MissingTrailingParam) {
  8554. const auto pattern = "/users/:id";
  8555. detail::PathParamsMatcher matcher(pattern);
  8556. Request request;
  8557. request.path = "/users";
  8558. ASSERT_FALSE(matcher.match(request));
  8559. }
  8560. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8561. const auto pattern = "/users/:id/subscriptions";
  8562. detail::PathParamsMatcher matcher(pattern);
  8563. Request request;
  8564. request.path = "/users/subscriptions";
  8565. ASSERT_FALSE(matcher.match(request));
  8566. }
  8567. TEST(PathParamsTest, MultipleParams) {
  8568. const auto pattern = "/users/:userid/subscriptions/:subid";
  8569. detail::PathParamsMatcher matcher(pattern);
  8570. Request request;
  8571. request.path = "/users/42/subscriptions/2";
  8572. ASSERT_TRUE(matcher.match(request));
  8573. std::unordered_map<std::string, std::string> expected_params = {
  8574. {"userid", "42"}, {"subid", "2"}};
  8575. EXPECT_EQ(request.path_params, expected_params);
  8576. }
  8577. TEST(PathParamsTest, SequenceOfParams) {
  8578. const auto pattern = "/values/:x/:y/:z";
  8579. detail::PathParamsMatcher matcher(pattern);
  8580. Request request;
  8581. request.path = "/values/1/2/3";
  8582. ASSERT_TRUE(matcher.match(request));
  8583. std::unordered_map<std::string, std::string> expected_params = {
  8584. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8585. EXPECT_EQ(request.path_params, expected_params);
  8586. }
  8587. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8588. const auto pattern = "/prefix:suffix";
  8589. detail::PathParamsMatcher matcher(pattern);
  8590. Request request;
  8591. request.path = "/prefix:suffix";
  8592. ASSERT_TRUE(matcher.match(request));
  8593. const std::unordered_map<std::string, std::string> expected_params = {};
  8594. EXPECT_EQ(request.path_params, expected_params);
  8595. }
  8596. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8597. // If ipv6 regex working, regex match codepath is taken.
  8598. // else port will default to 80 in Client impl
  8599. int clientImplMagicPort = 80;
  8600. int port = 4321;
  8601. // above ports must be different to avoid false negative
  8602. EXPECT_NE(clientImplMagicPort, port);
  8603. std::string ipV6TestURL = "http://[ff06::c3]";
  8604. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8605. CLIENT_PRIVATE_KEY_FILE);
  8606. EXPECT_EQ(cli.port(), port);
  8607. }
  8608. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8609. auto file_path = "./www/dir/index.html";
  8610. auto dir_path = "./www/dir";
  8611. detail::FileStat stat_file(file_path);
  8612. EXPECT_TRUE(stat_file.is_file());
  8613. EXPECT_FALSE(stat_file.is_dir());
  8614. detail::FileStat stat_dir(dir_path);
  8615. EXPECT_FALSE(stat_dir.is_file());
  8616. EXPECT_TRUE(stat_dir.is_dir());
  8617. }
  8618. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8619. // IPv4 with default HTTP port (80)
  8620. EXPECT_EQ("example.com",
  8621. detail::make_host_and_port_string("example.com", 80, false));
  8622. // IPv4 with default HTTPS port (443)
  8623. EXPECT_EQ("example.com",
  8624. detail::make_host_and_port_string("example.com", 443, true));
  8625. // IPv4 with non-default HTTP port
  8626. EXPECT_EQ("example.com:8080",
  8627. detail::make_host_and_port_string("example.com", 8080, false));
  8628. // IPv4 with non-default HTTPS port
  8629. EXPECT_EQ("example.com:8443",
  8630. detail::make_host_and_port_string("example.com", 8443, true));
  8631. // IPv6 with default HTTP port (80)
  8632. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8633. // IPv6 with default HTTPS port (443)
  8634. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8635. // IPv6 with non-default HTTP port
  8636. EXPECT_EQ("[::1]:8080",
  8637. detail::make_host_and_port_string("::1", 8080, false));
  8638. // IPv6 with non-default HTTPS port
  8639. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8640. // IPv6 full address with default port
  8641. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8642. detail::make_host_and_port_string(
  8643. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8644. // IPv6 full address with non-default port
  8645. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8646. detail::make_host_and_port_string(
  8647. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8648. // IPv6 localhost with non-default port
  8649. EXPECT_EQ("[::1]:3000",
  8650. detail::make_host_and_port_string("::1", 3000, false));
  8651. // IPv6 with zone ID (link-local address) with default port
  8652. EXPECT_EQ("[fe80::1%eth0]",
  8653. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8654. // IPv6 with zone ID (link-local address) with non-default port
  8655. EXPECT_EQ("[fe80::1%eth0]:8080",
  8656. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8657. // Edge case: Port 443 with is_ssl=false (should add port)
  8658. EXPECT_EQ("example.com:443",
  8659. detail::make_host_and_port_string("example.com", 443, false));
  8660. // Edge case: Port 80 with is_ssl=true (should add port)
  8661. EXPECT_EQ("example.com:80",
  8662. detail::make_host_and_port_string("example.com", 80, true));
  8663. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8664. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8665. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8666. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8667. // Security fix: Already bracketed IPv6 should not get double brackets
  8668. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8669. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8670. EXPECT_EQ("[::1]:8080",
  8671. detail::make_host_and_port_string("[::1]", 8080, false));
  8672. EXPECT_EQ("[2001:db8::1]:8080",
  8673. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8674. EXPECT_EQ("[fe80::1%eth0]",
  8675. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8676. EXPECT_EQ("[fe80::1%eth0]:8080",
  8677. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8678. // Edge case: Empty host (should return as-is)
  8679. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8680. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8681. // This is a known limitation but shouldn't crash
  8682. EXPECT_EQ("[host:name]",
  8683. detail::make_host_and_port_string("host:name", 80, false));
  8684. // Port number edge cases (no validation, but should not crash)
  8685. EXPECT_EQ("example.com:0",
  8686. detail::make_host_and_port_string("example.com", 0, false));
  8687. EXPECT_EQ("example.com:-1",
  8688. detail::make_host_and_port_string("example.com", -1, false));
  8689. EXPECT_EQ("example.com:65535",
  8690. detail::make_host_and_port_string("example.com", 65535, false));
  8691. EXPECT_EQ("example.com:65536",
  8692. detail::make_host_and_port_string("example.com", 65536, false));
  8693. }
  8694. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8695. Server svr;
  8696. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8697. EXPECT_EQ(res.status, 400);
  8698. });
  8699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8700. auto se = detail::scope_exit([&] {
  8701. svr.stop();
  8702. thread.join();
  8703. ASSERT_FALSE(svr.is_running());
  8704. });
  8705. svr.wait_until_ready();
  8706. Client cli(HOST, PORT);
  8707. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8708. }
  8709. TEST(InvalidHeaderCharsTest, is_field_name) {
  8710. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8711. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8712. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8713. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8714. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8715. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8716. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8717. EXPECT_FALSE(detail::fields::is_field_name(""));
  8718. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8719. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8720. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8721. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8722. }
  8723. TEST(InvalidHeaderCharsTest, is_field_value) {
  8724. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8725. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8726. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8727. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8728. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8729. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8730. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8731. EXPECT_TRUE(detail::fields::is_field_value(""));
  8732. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8733. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8734. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8735. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8736. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8737. }
  8738. TEST(InvalidHeaderCharsTest, OnServer) {
  8739. Server svr;
  8740. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8741. std::string header = "Not Set";
  8742. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8743. res.set_header(header, "value");
  8744. res.set_content("Page Content Page Content", "text/plain");
  8745. });
  8746. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8747. std::string header = "Not Set";
  8748. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8749. res.set_header("X-Test", header);
  8750. res.set_content("Page Content Page Content", "text/plain");
  8751. });
  8752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8753. auto se = detail::scope_exit([&] {
  8754. svr.stop();
  8755. thread.join();
  8756. ASSERT_FALSE(svr.is_running());
  8757. });
  8758. svr.wait_until_ready();
  8759. Client cli(HOST, PORT);
  8760. {
  8761. auto res = cli.Get(
  8762. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8763. ASSERT_TRUE(res);
  8764. EXPECT_EQ("Page Content Page Content", res->body);
  8765. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8766. }
  8767. {
  8768. auto res = cli.Get(
  8769. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8770. ASSERT_TRUE(res);
  8771. EXPECT_EQ("Page Content Page Content", res->body);
  8772. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8773. }
  8774. }
  8775. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8776. auto handled = false;
  8777. Server svr;
  8778. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8779. thread t = thread([&] { svr.listen(HOST, PORT); });
  8780. auto se = detail::scope_exit([&] {
  8781. svr.stop();
  8782. t.join();
  8783. ASSERT_FALSE(svr.is_running());
  8784. ASSERT_FALSE(handled);
  8785. });
  8786. svr.wait_until_ready();
  8787. auto req = "POST /test HTTP/1.1\r\n"
  8788. "Content-Length: x\r\n"
  8789. "\r\n";
  8790. std::string response;
  8791. ASSERT_TRUE(send_request(1, req, &response));
  8792. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8793. response.substr(0, response.find("\r\n")));
  8794. }
  8795. #ifndef _WIN32
  8796. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8797. static constexpr char reject[] = "Unauthorized";
  8798. static constexpr char accept[] = "Upload accepted";
  8799. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8800. Server svr;
  8801. svr.set_expect_100_continue_handler(
  8802. [](const Request & /*req*/, Response &res) {
  8803. res.status = StatusCode::Unauthorized_401;
  8804. res.set_content(reject, "text/plain");
  8805. return res.status;
  8806. });
  8807. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8808. res.set_content(accept, "text/plain");
  8809. });
  8810. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8811. auto se = detail::scope_exit([&] {
  8812. svr.stop();
  8813. thread.join();
  8814. ASSERT_FALSE(svr.is_running());
  8815. });
  8816. svr.wait_until_ready();
  8817. {
  8818. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8819. curl_easy_init(), &curl_easy_cleanup};
  8820. ASSERT_NE(curl, nullptr);
  8821. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8822. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8823. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8824. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8825. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8826. &curl_slist_free_all};
  8827. ASSERT_NE(list, nullptr);
  8828. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8829. struct read_data {
  8830. size_t read_size;
  8831. size_t total_size;
  8832. } data = {0, total_size};
  8833. using read_callback_t =
  8834. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8835. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8836. void *userdata) -> size_t {
  8837. read_data *data = (read_data *)userdata;
  8838. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8839. std::fill_n(ptr, size * nmemb, 'A');
  8840. data->read_size += size * nmemb;
  8841. return size * nmemb;
  8842. };
  8843. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8844. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8845. std::vector<char> buffer;
  8846. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8847. using write_callback_t =
  8848. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8849. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8850. void *userdata) -> size_t {
  8851. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8852. buffer->reserve(buffer->size() + size * nmemb + 1);
  8853. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8854. return size * nmemb;
  8855. };
  8856. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8857. {
  8858. const auto res = curl_easy_perform(curl.get());
  8859. ASSERT_EQ(res, CURLE_OK);
  8860. }
  8861. {
  8862. auto response_code = long{};
  8863. const auto res =
  8864. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8865. ASSERT_EQ(res, CURLE_OK);
  8866. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8867. }
  8868. {
  8869. auto dl = curl_off_t{};
  8870. const auto res =
  8871. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8872. ASSERT_EQ(res, CURLE_OK);
  8873. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8874. }
  8875. {
  8876. buffer.push_back('\0');
  8877. ASSERT_STRCASEEQ(buffer.data(), reject);
  8878. }
  8879. }
  8880. }
  8881. #endif
  8882. template <typename S, typename C>
  8883. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8884. svr.Get("/stream", [&](const Request &, Response &res) {
  8885. auto data = new std::string("01234567890123456789");
  8886. res.set_content_provider(
  8887. data->size(), "text/plain",
  8888. [&, data](size_t offset, size_t length, DataSink &sink) {
  8889. const size_t DATA_CHUNK_SIZE = 4;
  8890. const auto &d = *data;
  8891. std::this_thread::sleep_for(std::chrono::seconds(1));
  8892. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8893. return true;
  8894. },
  8895. [data](bool success) {
  8896. EXPECT_FALSE(success);
  8897. delete data;
  8898. });
  8899. });
  8900. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8901. auto i = new size_t(0);
  8902. res.set_content_provider(
  8903. "text/plain",
  8904. [i](size_t, DataSink &sink) {
  8905. if (*i < 5) {
  8906. std::this_thread::sleep_for(std::chrono::seconds(1));
  8907. sink.write("abcd", 4);
  8908. (*i)++;
  8909. } else {
  8910. sink.done();
  8911. }
  8912. return true;
  8913. },
  8914. [i](bool success) {
  8915. EXPECT_FALSE(success);
  8916. delete i;
  8917. });
  8918. });
  8919. svr.Get("/chunked", [&](const Request &, Response &res) {
  8920. auto i = new size_t(0);
  8921. res.set_chunked_content_provider(
  8922. "text/plain",
  8923. [i](size_t, DataSink &sink) {
  8924. if (*i < 5) {
  8925. std::this_thread::sleep_for(std::chrono::seconds(1));
  8926. sink.os << "abcd";
  8927. (*i)++;
  8928. } else {
  8929. sink.done();
  8930. }
  8931. return true;
  8932. },
  8933. [i](bool success) {
  8934. EXPECT_FALSE(success);
  8935. delete i;
  8936. });
  8937. });
  8938. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8939. auto se = detail::scope_exit([&] {
  8940. svr.stop();
  8941. listen_thread.join();
  8942. ASSERT_FALSE(svr.is_running());
  8943. });
  8944. svr.wait_until_ready();
  8945. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8946. {
  8947. auto start = std::chrono::steady_clock::now();
  8948. auto res = cli.Get("/stream");
  8949. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8950. std::chrono::steady_clock::now() - start)
  8951. .count();
  8952. ASSERT_FALSE(res);
  8953. EXPECT_EQ(Error::Read, res.error());
  8954. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8955. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8956. }
  8957. {
  8958. auto start = std::chrono::steady_clock::now();
  8959. auto res = cli.Get("/stream_without_length");
  8960. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8961. std::chrono::steady_clock::now() - start)
  8962. .count();
  8963. ASSERT_FALSE(res);
  8964. EXPECT_EQ(Error::Read, res.error());
  8965. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8966. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8967. }
  8968. {
  8969. auto start = std::chrono::steady_clock::now();
  8970. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8971. EXPECT_EQ("abcd", string(data, data_length));
  8972. return true;
  8973. });
  8974. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8975. std::chrono::steady_clock::now() - start)
  8976. .count();
  8977. ASSERT_FALSE(res);
  8978. EXPECT_EQ(Error::Read, res.error());
  8979. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8980. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8981. }
  8982. }
  8983. TEST(MaxTimeoutTest, ContentStream) {
  8984. time_t timeout = 2000;
  8985. time_t threshold = 200;
  8986. Server svr;
  8987. Client cli("localhost", PORT);
  8988. max_timeout_test(svr, cli, timeout, threshold);
  8989. }
  8990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8991. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8992. time_t timeout = 2000;
  8993. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8994. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8995. SSLClient cli("localhost", PORT);
  8996. cli.enable_server_certificate_verification(false);
  8997. max_timeout_test(svr, cli, timeout, threshold);
  8998. }
  8999. #endif
  9000. class EventDispatcher {
  9001. public:
  9002. EventDispatcher() {}
  9003. void wait_event(DataSink *sink) {
  9004. unique_lock<mutex> lk(m_);
  9005. int id = id_;
  9006. cv_.wait(lk, [&] { return cid_ == id; });
  9007. sink->write(message_.data(), message_.size());
  9008. }
  9009. void send_event(const string &message) {
  9010. lock_guard<mutex> lk(m_);
  9011. cid_ = id_++;
  9012. message_ = message;
  9013. cv_.notify_all();
  9014. }
  9015. private:
  9016. mutex m_;
  9017. condition_variable cv_;
  9018. atomic_int id_{0};
  9019. atomic_int cid_{-1};
  9020. string message_;
  9021. };
  9022. TEST(ClientInThreadTest, Issue2068) {
  9023. EventDispatcher ed;
  9024. Server svr;
  9025. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9026. res.set_chunked_content_provider("text/event-stream",
  9027. [&](size_t /*offset*/, DataSink &sink) {
  9028. ed.wait_event(&sink);
  9029. return true;
  9030. });
  9031. });
  9032. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9033. svr.wait_until_ready();
  9034. thread event_thread([&] {
  9035. int id = 0;
  9036. while (svr.is_running()) {
  9037. this_thread::sleep_for(chrono::milliseconds(500));
  9038. std::stringstream ss;
  9039. ss << "data: " << id << "\n\n";
  9040. ed.send_event(ss.str());
  9041. id++;
  9042. }
  9043. });
  9044. auto se = detail::scope_exit([&] {
  9045. svr.stop();
  9046. listen_thread.join();
  9047. event_thread.join();
  9048. ASSERT_FALSE(svr.is_running());
  9049. });
  9050. {
  9051. auto client = detail::make_unique<Client>(HOST, PORT);
  9052. client->set_read_timeout(std::chrono::minutes(10));
  9053. std::atomic<bool> stop{false};
  9054. std::thread t([&] {
  9055. client->Get("/event1",
  9056. [&](const char *, size_t) -> bool { return !stop; });
  9057. });
  9058. std::this_thread::sleep_for(std::chrono::seconds(2));
  9059. stop = true;
  9060. client->stop();
  9061. client.reset();
  9062. t.join();
  9063. }
  9064. }
  9065. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9066. Server svr;
  9067. svr.Get("/", [](const Request &req, Response &res) {
  9068. EXPECT_EQ(2U, req.trailers.size());
  9069. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9070. // Denied
  9071. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9072. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9073. // Accepted
  9074. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9075. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9076. EXPECT_TRUE(req.has_trailer("X-World"));
  9077. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9078. res.set_content("ok", "text/plain");
  9079. });
  9080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9081. auto se = detail::scope_exit([&] {
  9082. svr.stop();
  9083. t.join();
  9084. ASSERT_FALSE(svr.is_running());
  9085. });
  9086. svr.wait_until_ready();
  9087. const std::string req = "GET / HTTP/1.1\r\n"
  9088. "Transfer-Encoding: chunked\r\n"
  9089. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9090. "\r\n"
  9091. "0\r\n"
  9092. "Content-Length: 10\r\n"
  9093. "Host: internal.local\r\n"
  9094. "Content-Type: malicious/content\r\n"
  9095. "Cookie: any\r\n"
  9096. "Set-Cookie: any\r\n"
  9097. "X-Forwarded-For: attacker.com\r\n"
  9098. "X-Real-Ip: 1.1.1.1\r\n"
  9099. "X-Hello: hello\r\n"
  9100. "X-World: world\r\n"
  9101. "\r\n";
  9102. std::string res;
  9103. ASSERT_TRUE(send_request(1, req, &res));
  9104. }