test.cc 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid multipart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  136. string content_type = "multipart/form-data; boundary=something";
  137. string boundary;
  138. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  139. EXPECT_TRUE(ret);
  140. EXPECT_EQ(boundary, "something");
  141. }
  142. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  143. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  144. string boundary;
  145. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  146. EXPECT_TRUE(ret);
  147. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  148. }
  149. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  150. string content_type =
  151. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  152. string boundary;
  153. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  154. EXPECT_TRUE(ret);
  155. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  156. }
  157. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  158. string content_type =
  159. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  160. string boundary;
  161. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  162. EXPECT_TRUE(ret);
  163. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  164. }
  165. TEST(GetHeaderValueTest, DefaultValue) {
  166. Headers headers = {{"Dummy", "Dummy"}};
  167. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  168. EXPECT_STREQ("text/plain", val);
  169. }
  170. TEST(GetHeaderValueTest, DefaultValueInt) {
  171. Headers headers = {{"Dummy", "Dummy"}};
  172. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 100);
  173. EXPECT_EQ(100ull, val);
  174. }
  175. TEST(GetHeaderValueTest, RegularValue) {
  176. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  177. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  178. EXPECT_STREQ("text/html", val);
  179. }
  180. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  181. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  182. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  183. EXPECT_STREQ("text/html", val);
  184. }
  185. TEST(GetHeaderValueTest, SetContent) {
  186. Response res;
  187. res.set_content("html", "text/html");
  188. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  189. res.set_content("text", "text/plain");
  190. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  191. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  192. }
  193. TEST(GetHeaderValueTest, RegularValueInt) {
  194. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  195. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  196. EXPECT_EQ(100ull, val);
  197. }
  198. TEST(GetHeaderValueTest, Range) {
  199. {
  200. Headers headers = {make_range_header({{1, -1}})};
  201. auto val = detail::get_header_value(headers, "Range", 0, 0);
  202. EXPECT_STREQ("bytes=1-", val);
  203. }
  204. {
  205. Headers headers = {make_range_header({{-1, 1}})};
  206. auto val = detail::get_header_value(headers, "Range", 0, 0);
  207. EXPECT_STREQ("bytes=-1", val);
  208. }
  209. {
  210. Headers headers = {make_range_header({{1, 10}})};
  211. auto val = detail::get_header_value(headers, "Range", 0, 0);
  212. EXPECT_STREQ("bytes=1-10", val);
  213. }
  214. {
  215. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  216. auto val = detail::get_header_value(headers, "Range", 0, 0);
  217. EXPECT_STREQ("bytes=1-10, 100-", val);
  218. }
  219. {
  220. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  221. auto val = detail::get_header_value(headers, "Range", 0, 0);
  222. EXPECT_STREQ("bytes=1-10, 100-200", val);
  223. }
  224. {
  225. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  226. auto val = detail::get_header_value(headers, "Range", 0, 0);
  227. EXPECT_STREQ("bytes=0-0, -1", val);
  228. }
  229. }
  230. TEST(ParseHeaderValueTest, Range) {
  231. {
  232. Ranges ranges;
  233. auto ret = detail::parse_range_header("bytes=1-", ranges);
  234. EXPECT_TRUE(ret);
  235. EXPECT_EQ(1u, ranges.size());
  236. EXPECT_EQ(1u, ranges[0].first);
  237. EXPECT_EQ(-1, ranges[0].second);
  238. }
  239. {
  240. Ranges ranges;
  241. auto ret = detail::parse_range_header("bytes=-1", ranges);
  242. EXPECT_TRUE(ret);
  243. EXPECT_EQ(1u, ranges.size());
  244. EXPECT_EQ(-1, ranges[0].first);
  245. EXPECT_EQ(1u, ranges[0].second);
  246. }
  247. {
  248. Ranges ranges;
  249. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  250. EXPECT_TRUE(ret);
  251. EXPECT_EQ(1u, ranges.size());
  252. EXPECT_EQ(1u, ranges[0].first);
  253. EXPECT_EQ(10u, ranges[0].second);
  254. }
  255. {
  256. Ranges ranges;
  257. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  258. EXPECT_FALSE(ret);
  259. }
  260. {
  261. Ranges ranges;
  262. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  263. EXPECT_TRUE(ret);
  264. EXPECT_EQ(2u, ranges.size());
  265. EXPECT_EQ(1u, ranges[0].first);
  266. EXPECT_EQ(10u, ranges[0].second);
  267. EXPECT_EQ(100u, ranges[1].first);
  268. EXPECT_EQ(-1, ranges[1].second);
  269. }
  270. {
  271. Ranges ranges;
  272. auto ret =
  273. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  274. EXPECT_TRUE(ret);
  275. EXPECT_EQ(3u, ranges.size());
  276. EXPECT_EQ(1u, ranges[0].first);
  277. EXPECT_EQ(10u, ranges[0].second);
  278. EXPECT_EQ(100u, ranges[1].first);
  279. EXPECT_EQ(200u, ranges[1].second);
  280. EXPECT_EQ(300u, ranges[2].first);
  281. EXPECT_EQ(400u, ranges[2].second);
  282. }
  283. }
  284. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  285. Request req;
  286. req.set_header("Accept-Encoding", "gzip");
  287. Response res;
  288. res.set_header("Content-Type", "text/plain");
  289. auto ret = detail::encoding_type(req, res);
  290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  291. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  292. #else
  293. EXPECT_TRUE(ret == detail::EncodingType::None);
  294. #endif
  295. }
  296. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  297. Request req;
  298. req.set_header("Accept-Encoding", "gzip, deflate, br");
  299. Response res;
  300. res.set_header("Content-Type", "text/plain");
  301. auto ret = detail::encoding_type(req, res);
  302. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  303. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  304. #elif CPPHTTPLIB_ZLIB_SUPPORT
  305. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  306. #else
  307. EXPECT_TRUE(ret == detail::EncodingType::None);
  308. #endif
  309. }
  310. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  311. Request req;
  312. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  313. Response res;
  314. res.set_header("Content-Type", "text/plain");
  315. auto ret = detail::encoding_type(req, res);
  316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  317. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  318. #elif CPPHTTPLIB_ZLIB_SUPPORT
  319. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  320. #else
  321. EXPECT_TRUE(ret == detail::EncodingType::None);
  322. #endif
  323. }
  324. TEST(BufferStreamTest, read) {
  325. detail::BufferStream strm1;
  326. Stream &strm = strm1;
  327. EXPECT_EQ(5, strm.write("hello"));
  328. char buf[512];
  329. EXPECT_EQ(2, strm.read(buf, 2));
  330. EXPECT_EQ('h', buf[0]);
  331. EXPECT_EQ('e', buf[1]);
  332. EXPECT_EQ(2, strm.read(buf, 2));
  333. EXPECT_EQ('l', buf[0]);
  334. EXPECT_EQ('l', buf[1]);
  335. EXPECT_EQ(1, strm.read(buf, 1));
  336. EXPECT_EQ('o', buf[0]);
  337. EXPECT_EQ(0, strm.read(buf, 1));
  338. }
  339. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  340. auto host = "www.httpwatch.com";
  341. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  342. auto port = 443;
  343. SSLClient cli(host, port);
  344. #else
  345. auto port = 80;
  346. Client cli(host, port);
  347. #endif
  348. cli.set_connection_timeout(2);
  349. auto res =
  350. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  351. ASSERT_TRUE(res);
  352. std::string out;
  353. detail::read_file("./image.jpg", out);
  354. EXPECT_EQ(200, res->status);
  355. EXPECT_EQ(out, res->body);
  356. }
  357. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  358. auto host = "www.httpwatch.com";
  359. auto ip = hosted_at(host);
  360. EXPECT_EQ("23.96.13.243", ip);
  361. std::vector<std::string> addrs;
  362. hosted_at(host, addrs);
  363. EXPECT_EQ(1u, addrs.size());
  364. }
  365. #if 0 // It depends on each test environment...
  366. TEST(HostnameToIPConversionTest, YouTube_Online) {
  367. auto host = "www.youtube.com";
  368. std::vector<std::string> addrs;
  369. hosted_at(host, addrs);
  370. EXPECT_EQ(20u, addrs.size());
  371. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  372. EXPECT_TRUE(it != addrs.end());
  373. }
  374. #endif
  375. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  376. auto host = "www.httpwatch.com";
  377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  378. auto port = 443;
  379. SSLClient cli(host, port);
  380. #else
  381. auto port = 80;
  382. Client cli(host, port);
  383. #endif
  384. cli.set_connection_timeout(2);
  385. std::string body;
  386. auto res =
  387. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  388. [&](const char *data, size_t data_length) {
  389. body.append(data, data_length);
  390. return true;
  391. });
  392. ASSERT_TRUE(res);
  393. std::string out;
  394. detail::read_file("./image.jpg", out);
  395. EXPECT_EQ(200, res->status);
  396. EXPECT_EQ(out, body);
  397. }
  398. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  399. auto host = "www.httpwatch.com";
  400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  401. auto port = 443;
  402. SSLClient cli(host, port);
  403. #else
  404. auto port = 80;
  405. Client cli(host, port);
  406. #endif
  407. cli.set_connection_timeout(2);
  408. std::string body;
  409. auto res = cli.Get(
  410. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  411. [&](const Response &response) {
  412. EXPECT_EQ(200, response.status);
  413. return true;
  414. },
  415. [&](const char *data, size_t data_length) {
  416. body.append(data, data_length);
  417. return true;
  418. });
  419. ASSERT_TRUE(res);
  420. std::string out;
  421. detail::read_file("./image.jpg", out);
  422. EXPECT_EQ(200, res->status);
  423. EXPECT_EQ(out, body);
  424. }
  425. TEST(RangeTest, FromHTTPBin_Online) {
  426. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  427. auto host = "httpbin.org";
  428. auto path = std::string{"/range/32"};
  429. #else
  430. auto host = "nghttp2.org";
  431. auto path = std::string{"/httpbin/range/32"};
  432. #endif
  433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  434. auto port = 443;
  435. SSLClient cli(host, port);
  436. #else
  437. auto port = 80;
  438. Client cli(host, port);
  439. #endif
  440. cli.set_connection_timeout(5);
  441. {
  442. auto res = cli.Get(path);
  443. ASSERT_TRUE(res);
  444. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  445. EXPECT_EQ(200, res->status);
  446. }
  447. {
  448. Headers headers = {make_range_header({{1, -1}})};
  449. auto res = cli.Get(path, headers);
  450. ASSERT_TRUE(res);
  451. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  452. EXPECT_EQ(206, res->status);
  453. }
  454. {
  455. Headers headers = {make_range_header({{1, 10}})};
  456. auto res = cli.Get(path, headers);
  457. ASSERT_TRUE(res);
  458. EXPECT_EQ("bcdefghijk", res->body);
  459. EXPECT_EQ(206, res->status);
  460. }
  461. {
  462. Headers headers = {make_range_header({{0, 31}})};
  463. auto res = cli.Get(path, headers);
  464. ASSERT_TRUE(res);
  465. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  466. EXPECT_EQ(200, res->status);
  467. }
  468. {
  469. Headers headers = {make_range_header({{0, -1}})};
  470. auto res = cli.Get(path, headers);
  471. ASSERT_TRUE(res);
  472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  473. EXPECT_EQ(200, res->status);
  474. }
  475. {
  476. Headers headers = {make_range_header({{0, 32}})};
  477. auto res = cli.Get(path, headers);
  478. ASSERT_TRUE(res);
  479. EXPECT_EQ(416, res->status);
  480. }
  481. }
  482. TEST(ConnectionErrorTest, InvalidHost) {
  483. auto host = "-abcde.com";
  484. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  485. auto port = 443;
  486. SSLClient cli(host, port);
  487. #else
  488. auto port = 80;
  489. Client cli(host, port);
  490. #endif
  491. cli.set_connection_timeout(std::chrono::seconds(2));
  492. auto res = cli.Get("/");
  493. ASSERT_TRUE(!res);
  494. EXPECT_EQ(Error::Connection, res.error());
  495. }
  496. TEST(ConnectionErrorTest, InvalidHost2) {
  497. auto host = "httpbin.org/";
  498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  499. SSLClient cli(host);
  500. #else
  501. Client cli(host);
  502. #endif
  503. cli.set_connection_timeout(std::chrono::seconds(2));
  504. auto res = cli.Get("/");
  505. ASSERT_TRUE(!res);
  506. EXPECT_EQ(Error::Connection, res.error());
  507. }
  508. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  509. auto host = "httpbin.org/";
  510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  511. SSLClient cli(host);
  512. #else
  513. Client cli(host);
  514. #endif
  515. cli.set_connection_timeout(std::chrono::seconds(2));
  516. auto res = cli.Get("/");
  517. ASSERT_TRUE(!res);
  518. stringstream s;
  519. s << "error code: " << res.error();
  520. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  521. }
  522. TEST(ConnectionErrorTest, InvalidPort) {
  523. auto host = "localhost";
  524. auto port = 44380;
  525. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  526. SSLClient cli(host, port);
  527. #else
  528. Client cli(host, port);
  529. #endif
  530. cli.set_connection_timeout(std::chrono::seconds(2));
  531. auto res = cli.Get("/");
  532. ASSERT_TRUE(!res);
  533. EXPECT_TRUE(Error::Connection == res.error() ||
  534. Error::ConnectionTimeout == res.error());
  535. }
  536. TEST(ConnectionErrorTest, Timeout_Online) {
  537. auto host = "google.com";
  538. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  539. auto port = 44380;
  540. SSLClient cli(host, port);
  541. #else
  542. auto port = 8080;
  543. Client cli(host, port);
  544. #endif
  545. cli.set_connection_timeout(std::chrono::seconds(2));
  546. // only probe one address type so that the error reason
  547. // correlates to the timed-out IPv4, not the unsupported
  548. // IPv6 connection attempt
  549. cli.set_address_family(AF_INET);
  550. auto res = cli.Get("/");
  551. ASSERT_TRUE(!res);
  552. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  553. }
  554. TEST(CancelTest, NoCancel_Online) {
  555. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  556. auto host = "httpbin.org";
  557. auto path = std::string{"/range/32"};
  558. #else
  559. auto host = "nghttp2.org";
  560. auto path = std::string{"/httpbin/range/32"};
  561. #endif
  562. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  563. auto port = 443;
  564. SSLClient cli(host, port);
  565. #else
  566. auto port = 80;
  567. Client cli(host, port);
  568. #endif
  569. cli.set_connection_timeout(std::chrono::seconds(5));
  570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  571. ASSERT_TRUE(res);
  572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  573. EXPECT_EQ(200, res->status);
  574. }
  575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  576. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  577. auto host = "httpbin.org";
  578. auto path = std::string{"/range/32"};
  579. #else
  580. auto host = "nghttp2.org";
  581. auto path = std::string{"/httpbin/range/32"};
  582. #endif
  583. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  584. auto port = 443;
  585. SSLClient cli(host, port);
  586. #else
  587. auto port = 80;
  588. Client cli(host, port);
  589. #endif
  590. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  591. cli.set_connection_timeout(std::chrono::seconds(5));
  592. ASSERT_TRUE(!res);
  593. EXPECT_EQ(Error::Canceled, res.error());
  594. }
  595. TEST(CancelTest, WithCancelLargePayload_Online) {
  596. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  597. auto host = "httpbin.org";
  598. auto path = std::string{"/range/65536"};
  599. #else
  600. auto host = "nghttp2.org";
  601. auto path = std::string{"/httpbin/range/65536"};
  602. #endif
  603. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  604. auto port = 443;
  605. SSLClient cli(host, port);
  606. #else
  607. auto port = 80;
  608. Client cli(host, port);
  609. #endif
  610. cli.set_connection_timeout(std::chrono::seconds(5));
  611. uint32_t count = 0;
  612. auto res =
  613. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  614. ASSERT_TRUE(!res);
  615. EXPECT_EQ(Error::Canceled, res.error());
  616. }
  617. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  618. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  619. auto host = "httpbin.org";
  620. auto path = std::string{"/basic-auth/hello/world"};
  621. #else
  622. auto host = "nghttp2.org";
  623. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  624. #endif
  625. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  626. auto port = 443;
  627. SSLClient cli(host, port);
  628. #else
  629. auto port = 80;
  630. Client cli(host, port);
  631. #endif
  632. {
  633. auto res = cli.Get(path);
  634. ASSERT_TRUE(res);
  635. EXPECT_EQ(401, res->status);
  636. }
  637. {
  638. auto res =
  639. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  640. ASSERT_TRUE(res);
  641. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  642. res->body);
  643. EXPECT_EQ(200, res->status);
  644. }
  645. {
  646. cli.set_basic_auth("hello", "world");
  647. auto res = cli.Get(path);
  648. ASSERT_TRUE(res);
  649. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  650. res->body);
  651. EXPECT_EQ(200, res->status);
  652. }
  653. {
  654. cli.set_basic_auth("hello", "bad");
  655. auto res = cli.Get(path);
  656. ASSERT_TRUE(res);
  657. EXPECT_EQ(401, res->status);
  658. }
  659. {
  660. cli.set_basic_auth("bad", "world");
  661. auto res = cli.Get(path);
  662. ASSERT_TRUE(res);
  663. EXPECT_EQ(401, res->status);
  664. }
  665. }
  666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  667. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  668. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  669. auto host = "httpbin.org";
  670. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  671. auto paths = std::vector<std::string>{
  672. "/digest-auth/auth/hello/world/MD5",
  673. "/digest-auth/auth/hello/world/SHA-256",
  674. "/digest-auth/auth/hello/world/SHA-512",
  675. "/digest-auth/auth-int/hello/world/MD5",
  676. };
  677. #else
  678. auto host = "nghttp2.org";
  679. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  680. auto paths = std::vector<std::string>{
  681. "/httpbin/digest-auth/auth/hello/world/MD5",
  682. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  683. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  684. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  685. };
  686. #endif
  687. auto port = 443;
  688. SSLClient cli(host, port);
  689. {
  690. auto res = cli.Get(unauth_path);
  691. ASSERT_TRUE(res);
  692. EXPECT_EQ(401, res->status);
  693. }
  694. {
  695. cli.set_digest_auth("hello", "world");
  696. for (const auto &path : paths) {
  697. auto res = cli.Get(path.c_str());
  698. ASSERT_TRUE(res);
  699. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  700. res->body);
  701. EXPECT_EQ(200, res->status);
  702. }
  703. cli.set_digest_auth("hello", "bad");
  704. for (const auto &path : paths) {
  705. auto res = cli.Get(path.c_str());
  706. ASSERT_TRUE(res);
  707. EXPECT_EQ(401, res->status);
  708. }
  709. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  710. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  711. // cli.set_digest_auth("bad", "world");
  712. // for (const auto& path : paths) {
  713. // auto res = cli.Get(path.c_str());
  714. // ASSERT_TRUE(res);
  715. // EXPECT_EQ(400, res->status);
  716. // }
  717. }
  718. }
  719. #endif
  720. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  721. auto host = "google.com";
  722. auto another_host = "example.com";
  723. auto wrong_ip = "0.0.0.0";
  724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  725. SSLClient cli(host);
  726. #else
  727. Client cli(host);
  728. #endif
  729. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  730. auto res = cli.Get("/");
  731. ASSERT_TRUE(res);
  732. ASSERT_EQ(301, res->status);
  733. }
  734. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  735. auto host = "google.com";
  736. auto wrong_ip = "0.0.0.0";
  737. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  738. SSLClient cli(host);
  739. #else
  740. Client cli(host);
  741. #endif
  742. cli.set_hostname_addr_map({{host, wrong_ip}});
  743. auto res = cli.Get("/");
  744. ASSERT_TRUE(!res);
  745. EXPECT_EQ(Error::Connection, res.error());
  746. }
  747. TEST(AbsoluteRedirectTest, Redirect_Online) {
  748. auto host = "nghttp2.org";
  749. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  750. SSLClient cli(host);
  751. #else
  752. Client cli(host);
  753. #endif
  754. cli.set_follow_location(true);
  755. auto res = cli.Get("/httpbin/absolute-redirect/3");
  756. ASSERT_TRUE(res);
  757. EXPECT_EQ(200, res->status);
  758. }
  759. TEST(RedirectTest, Redirect_Online) {
  760. auto host = "nghttp2.org";
  761. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  762. SSLClient cli(host);
  763. #else
  764. Client cli(host);
  765. #endif
  766. cli.set_follow_location(true);
  767. auto res = cli.Get("/httpbin/redirect/3");
  768. ASSERT_TRUE(res);
  769. EXPECT_EQ(200, res->status);
  770. }
  771. TEST(RelativeRedirectTest, Redirect_Online) {
  772. auto host = "nghttp2.org";
  773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  774. SSLClient cli(host);
  775. #else
  776. Client cli(host);
  777. #endif
  778. cli.set_follow_location(true);
  779. auto res = cli.Get("/httpbin/relative-redirect/3");
  780. ASSERT_TRUE(res);
  781. EXPECT_EQ(200, res->status);
  782. }
  783. TEST(TooManyRedirectTest, Redirect_Online) {
  784. auto host = "nghttp2.org";
  785. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  786. SSLClient cli(host);
  787. #else
  788. Client cli(host);
  789. #endif
  790. cli.set_follow_location(true);
  791. auto res = cli.Get("/httpbin/redirect/21");
  792. ASSERT_TRUE(!res);
  793. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  794. }
  795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  796. TEST(YahooRedirectTest, Redirect_Online) {
  797. Client cli("yahoo.com");
  798. auto res = cli.Get("/");
  799. ASSERT_TRUE(res);
  800. EXPECT_EQ(301, res->status);
  801. cli.set_follow_location(true);
  802. res = cli.Get("/");
  803. ASSERT_TRUE(res);
  804. EXPECT_EQ(200, res->status);
  805. EXPECT_EQ("https://www.yahoo.com/", res->location);
  806. }
  807. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  808. SSLClient cli("nghttp2.org");
  809. cli.set_follow_location(true);
  810. auto res = cli.Get(
  811. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  812. ASSERT_TRUE(res);
  813. EXPECT_EQ(200, res->status);
  814. }
  815. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  816. SSLClient cli("nghttp2.org");
  817. cli.set_follow_location(true);
  818. Params params;
  819. params.emplace("url", "http://www.google.com");
  820. params.emplace("status_code", "302");
  821. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  822. ASSERT_TRUE(res);
  823. EXPECT_EQ(200, res->status);
  824. }
  825. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  826. SSLClient cli("nghttp2.org");
  827. cli.set_follow_location(true);
  828. Params params;
  829. params.emplace("url", "http://www.google.com");
  830. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  831. ASSERT_TRUE(res);
  832. EXPECT_EQ(200, res->status);
  833. }
  834. TEST(UrlWithSpace, Redirect_Online) {
  835. SSLClient cli("edge.forgecdn.net");
  836. cli.set_follow_location(true);
  837. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  838. ASSERT_TRUE(res);
  839. EXPECT_EQ(200, res->status);
  840. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  841. }
  842. #endif
  843. #if !defined(_WIN32) && !defined(_WIN64)
  844. TEST(ReceiveSignals, Signal) {
  845. auto setupSignalHandlers = []() {
  846. struct sigaction act;
  847. sigemptyset(&act.sa_mask);
  848. act.sa_flags = SA_SIGINFO;
  849. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  850. switch (sig) {
  851. case SIGINT:
  852. default: break;
  853. }
  854. };
  855. ::sigaction(SIGINT, &act, nullptr);
  856. };
  857. Server svr;
  858. int port = 0;
  859. auto thread = std::thread([&]() {
  860. setupSignalHandlers();
  861. port = svr.bind_to_any_port("localhost");
  862. svr.listen_after_bind();
  863. });
  864. auto se = detail::scope_exit([&] {
  865. svr.stop();
  866. thread.join();
  867. ASSERT_FALSE(svr.is_running());
  868. });
  869. svr.wait_until_ready();
  870. ASSERT_TRUE(svr.is_running());
  871. pthread_kill(thread.native_handle(), SIGINT);
  872. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  873. ASSERT_TRUE(svr.is_running());
  874. }
  875. #endif
  876. TEST(RedirectToDifferentPort, Redirect) {
  877. Server svr1;
  878. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  879. res.set_content("Hello World!", "text/plain");
  880. });
  881. int svr1_port = 0;
  882. auto thread1 = std::thread([&]() {
  883. svr1_port = svr1.bind_to_any_port("localhost");
  884. svr1.listen_after_bind();
  885. });
  886. Server svr2;
  887. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  888. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  889. });
  890. int svr2_port = 0;
  891. auto thread2 = std::thread([&]() {
  892. svr2_port = svr2.bind_to_any_port("localhost");
  893. svr2.listen_after_bind();
  894. });
  895. auto se = detail::scope_exit([&] {
  896. svr2.stop();
  897. thread2.join();
  898. svr1.stop();
  899. thread1.join();
  900. ASSERT_FALSE(svr2.is_running());
  901. ASSERT_FALSE(svr1.is_running());
  902. });
  903. svr1.wait_until_ready();
  904. svr2.wait_until_ready();
  905. Client cli("localhost", svr2_port);
  906. cli.set_follow_location(true);
  907. auto res = cli.Get("/2");
  908. ASSERT_TRUE(res);
  909. EXPECT_EQ(200, res->status);
  910. EXPECT_EQ("Hello World!", res->body);
  911. }
  912. TEST(RedirectFromPageWithContent, Redirect) {
  913. Server svr;
  914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  915. res.set_content("___", "text/plain");
  916. res.set_redirect("/2");
  917. });
  918. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  919. res.set_content("Hello World!", "text/plain");
  920. });
  921. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  922. auto se = detail::scope_exit([&] {
  923. svr.stop();
  924. th.join();
  925. ASSERT_FALSE(svr.is_running());
  926. });
  927. svr.wait_until_ready();
  928. {
  929. Client cli("localhost", PORT);
  930. cli.set_follow_location(true);
  931. std::string body;
  932. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  933. body.append(data, data_length);
  934. return true;
  935. });
  936. ASSERT_TRUE(res);
  937. EXPECT_EQ(200, res->status);
  938. EXPECT_EQ("Hello World!", body);
  939. }
  940. {
  941. Client cli("localhost", PORT);
  942. std::string body;
  943. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  944. body.append(data, data_length);
  945. return true;
  946. });
  947. ASSERT_TRUE(res);
  948. EXPECT_EQ(302, res->status);
  949. EXPECT_EQ("___", body);
  950. }
  951. }
  952. TEST(RedirectFromPageWithContentIP6, Redirect) {
  953. Server svr;
  954. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  955. res.set_content("___", "text/plain");
  956. // res.set_redirect("/2");
  957. res.set_redirect("http://[::1]:1234/2");
  958. });
  959. svr.Get("/2", [&](const Request &req, Response &res) {
  960. auto host_header = req.headers.find("Host");
  961. ASSERT_TRUE(host_header != req.headers.end());
  962. EXPECT_EQ("[::1]:1234", host_header->second);
  963. res.set_content("Hello World!", "text/plain");
  964. });
  965. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  966. auto se = detail::scope_exit([&] {
  967. svr.stop();
  968. th.join();
  969. ASSERT_FALSE(svr.is_running());
  970. });
  971. // When IPV6 support isn't available svr.listen("::1", 1234) never
  972. // actually starts anything, so the condition !svr.is_running() will
  973. // always remain true, and the loop never stops.
  974. // This basically counts how many milliseconds have passed since the
  975. // call to svr.listen(), and if after 5 seconds nothing started yet
  976. // aborts the test.
  977. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  978. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  979. ASSERT_LT(milliseconds, 5000U);
  980. }
  981. {
  982. Client cli("http://[::1]:1234");
  983. cli.set_follow_location(true);
  984. std::string body;
  985. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  986. body.append(data, data_length);
  987. return true;
  988. });
  989. ASSERT_TRUE(res);
  990. EXPECT_EQ(200, res->status);
  991. EXPECT_EQ("Hello World!", body);
  992. }
  993. {
  994. Client cli("http://[::1]:1234");
  995. std::string body;
  996. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  997. body.append(data, data_length);
  998. return true;
  999. });
  1000. ASSERT_TRUE(res);
  1001. EXPECT_EQ(302, res->status);
  1002. EXPECT_EQ("___", body);
  1003. }
  1004. }
  1005. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1006. Server svr;
  1007. svr.Get("/foo", [](const Request &req, Response &res) {
  1008. auto a = req.params.find("a");
  1009. if (a != req.params.end()) {
  1010. res.set_content((*a).second, "text/plain");
  1011. res.status = 200;
  1012. } else {
  1013. res.status = 400;
  1014. }
  1015. });
  1016. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1017. auto se = detail::scope_exit([&] {
  1018. svr.stop();
  1019. thread.join();
  1020. ASSERT_FALSE(svr.is_running());
  1021. });
  1022. svr.wait_until_ready();
  1023. {
  1024. Client cli(HOST, PORT);
  1025. cli.set_url_encode(false);
  1026. auto res = cli.Get("/foo?a=explicitly+encoded");
  1027. ASSERT_TRUE(res);
  1028. EXPECT_EQ(200, res->status);
  1029. // This expects it back with a space, as the `+` won't have been
  1030. // url-encoded, and server-side the params get decoded turning `+`
  1031. // into spaces.
  1032. EXPECT_EQ("explicitly encoded", res->body);
  1033. }
  1034. }
  1035. TEST(BindServerTest, DISABLED_BindDualStack) {
  1036. Server svr;
  1037. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1038. res.set_content("Hello World!", "text/plain");
  1039. });
  1040. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1041. auto se = detail::scope_exit([&] {
  1042. svr.stop();
  1043. thread.join();
  1044. ASSERT_FALSE(svr.is_running());
  1045. });
  1046. svr.wait_until_ready();
  1047. {
  1048. Client cli("127.0.0.1", PORT);
  1049. auto res = cli.Get("/1");
  1050. ASSERT_TRUE(res);
  1051. EXPECT_EQ(200, res->status);
  1052. EXPECT_EQ("Hello World!", res->body);
  1053. }
  1054. {
  1055. Client cli("::1", PORT);
  1056. auto res = cli.Get("/1");
  1057. ASSERT_TRUE(res);
  1058. EXPECT_EQ(200, res->status);
  1059. EXPECT_EQ("Hello World!", res->body);
  1060. }
  1061. }
  1062. TEST(BindServerTest, BindAndListenSeparately) {
  1063. Server svr;
  1064. int port = svr.bind_to_any_port("0.0.0.0");
  1065. ASSERT_TRUE(svr.is_valid());
  1066. ASSERT_TRUE(port > 0);
  1067. svr.stop();
  1068. }
  1069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1070. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1071. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1072. CLIENT_CA_CERT_DIR);
  1073. int port = svr.bind_to_any_port("0.0.0.0");
  1074. ASSERT_TRUE(svr.is_valid());
  1075. ASSERT_TRUE(port > 0);
  1076. svr.stop();
  1077. }
  1078. #endif
  1079. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1080. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1081. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1082. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1083. int port = svr.bind_to_any_port("0.0.0.0");
  1084. ASSERT_TRUE(svr.is_valid());
  1085. ASSERT_TRUE(port > 0);
  1086. svr.stop();
  1087. }
  1088. #endif
  1089. TEST(ErrorHandlerTest, ContentLength) {
  1090. Server svr;
  1091. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1092. res.status = 200;
  1093. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1094. "text/html"); // <= Content-Length still 13
  1095. });
  1096. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1097. res.set_content("Hello World!\n", "text/plain");
  1098. res.status = 524;
  1099. });
  1100. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1101. auto se = detail::scope_exit([&] {
  1102. svr.stop();
  1103. thread.join();
  1104. ASSERT_FALSE(svr.is_running());
  1105. });
  1106. svr.wait_until_ready();
  1107. {
  1108. Client cli(HOST, PORT);
  1109. auto res = cli.Get("/hi");
  1110. ASSERT_TRUE(res);
  1111. EXPECT_EQ(200, res->status);
  1112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1113. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1114. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1115. }
  1116. }
  1117. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1118. TEST(ExceptionHandlerTest, ContentLength) {
  1119. Server svr;
  1120. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1121. std::exception_ptr ep) {
  1122. EXPECT_FALSE(ep == nullptr);
  1123. try {
  1124. std::rethrow_exception(ep);
  1125. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1126. res.status = 500;
  1127. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1128. "text/html"); // <= Content-Length still 13 at this point
  1129. });
  1130. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1131. res.set_content("Hello World!\n", "text/plain");
  1132. throw std::runtime_error("abc");
  1133. });
  1134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1135. auto se = detail::scope_exit([&] {
  1136. svr.stop();
  1137. thread.join();
  1138. ASSERT_FALSE(svr.is_running());
  1139. });
  1140. svr.wait_until_ready();
  1141. for (size_t i = 0; i < 10; i++) {
  1142. Client cli(HOST, PORT);
  1143. for (size_t j = 0; j < 100; j++) {
  1144. auto res = cli.Get("/hi");
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ(500, res->status);
  1147. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1148. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1149. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1150. }
  1151. cli.set_keep_alive(true);
  1152. for (size_t j = 0; j < 100; j++) {
  1153. auto res = cli.Get("/hi");
  1154. ASSERT_TRUE(res);
  1155. EXPECT_EQ(500, res->status);
  1156. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1157. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1158. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1159. }
  1160. }
  1161. }
  1162. #endif
  1163. TEST(NoContentTest, ContentLength) {
  1164. Server svr;
  1165. svr.Get("/hi",
  1166. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1168. auto se = detail::scope_exit([&] {
  1169. svr.stop();
  1170. thread.join();
  1171. ASSERT_FALSE(svr.is_running());
  1172. });
  1173. svr.wait_until_ready();
  1174. {
  1175. Client cli(HOST, PORT);
  1176. auto res = cli.Get("/hi");
  1177. ASSERT_TRUE(res);
  1178. EXPECT_EQ(204, res->status);
  1179. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1180. }
  1181. }
  1182. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1183. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1185. ASSERT_TRUE(svr.is_valid());
  1186. #else
  1187. Server svr;
  1188. #endif
  1189. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1190. if (req.path == "/routing_handler") {
  1191. res.set_header("PRE_ROUTING", "on");
  1192. res.set_content("Routing Handler", "text/plain");
  1193. return httplib::Server::HandlerResponse::Handled;
  1194. }
  1195. return httplib::Server::HandlerResponse::Unhandled;
  1196. });
  1197. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1198. res.set_content("Error", "text/html");
  1199. });
  1200. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1201. if (req.path == "/routing_handler") {
  1202. res.set_header("POST_ROUTING", "on");
  1203. }
  1204. });
  1205. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1206. res.set_content("Hello World!\n", "text/plain");
  1207. });
  1208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. thread.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. {
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. SSLClient cli(HOST, PORT);
  1218. cli.enable_server_certificate_verification(false);
  1219. #else
  1220. Client cli(HOST, PORT);
  1221. #endif
  1222. auto res = cli.Get("/routing_handler");
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ(200, res->status);
  1225. EXPECT_EQ("Routing Handler", res->body);
  1226. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1227. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1228. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1229. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1230. }
  1231. {
  1232. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1233. SSLClient cli(HOST, PORT);
  1234. cli.enable_server_certificate_verification(false);
  1235. #else
  1236. Client cli(HOST, PORT);
  1237. #endif
  1238. auto res = cli.Get("/hi");
  1239. ASSERT_TRUE(res);
  1240. EXPECT_EQ(200, res->status);
  1241. EXPECT_EQ("Hello World!\n", res->body);
  1242. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1243. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1244. }
  1245. {
  1246. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1247. SSLClient cli(HOST, PORT);
  1248. cli.enable_server_certificate_verification(false);
  1249. #else
  1250. Client cli(HOST, PORT);
  1251. #endif
  1252. auto res = cli.Get("/aaa");
  1253. ASSERT_TRUE(res);
  1254. EXPECT_EQ(404, res->status);
  1255. EXPECT_EQ("Error", res->body);
  1256. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1257. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1258. }
  1259. }
  1260. TEST(InvalidFormatTest, StatusCode) {
  1261. Server svr;
  1262. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1263. res.set_content("Hello World!\n", "text/plain");
  1264. res.status = 9999; // Status should be a three-digit code...
  1265. });
  1266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1267. auto se = detail::scope_exit([&] {
  1268. svr.stop();
  1269. thread.join();
  1270. ASSERT_FALSE(svr.is_running());
  1271. });
  1272. svr.wait_until_ready();
  1273. {
  1274. Client cli(HOST, PORT);
  1275. auto res = cli.Get("/hi");
  1276. ASSERT_FALSE(res);
  1277. }
  1278. }
  1279. TEST(URLFragmentTest, WithFragment) {
  1280. Server svr;
  1281. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1282. EXPECT_TRUE(req.target == "/hi");
  1283. });
  1284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1285. auto se = detail::scope_exit([&] {
  1286. svr.stop();
  1287. thread.join();
  1288. ASSERT_FALSE(svr.is_running());
  1289. });
  1290. svr.wait_until_ready();
  1291. {
  1292. Client cli(HOST, PORT);
  1293. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1294. EXPECT_TRUE(res);
  1295. EXPECT_EQ(200, res->status);
  1296. res = cli.Get("/hi%23key1=val1=key2=val2");
  1297. EXPECT_TRUE(res);
  1298. EXPECT_EQ(404, res->status);
  1299. }
  1300. }
  1301. TEST(HeaderWriter, SetHeaderWriter) {
  1302. Server svr;
  1303. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1304. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1305. return detail::write_headers(strm, hdrs);
  1306. });
  1307. svr.Get("/hi", [](const Request &req, Response &res) {
  1308. auto it = req.headers.find("CustomClientHeader");
  1309. EXPECT_TRUE(it != req.headers.end());
  1310. EXPECT_EQ(it->second, "CustomClientValue");
  1311. res.set_content("Hello World!\n", "text/plain");
  1312. });
  1313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1314. auto se = detail::scope_exit([&] {
  1315. svr.stop();
  1316. thread.join();
  1317. ASSERT_FALSE(svr.is_running());
  1318. });
  1319. svr.wait_until_ready();
  1320. {
  1321. Client cli(HOST, PORT);
  1322. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1323. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1324. return detail::write_headers(strm, hdrs);
  1325. });
  1326. auto res = cli.Get("/hi");
  1327. EXPECT_TRUE(res);
  1328. EXPECT_EQ(200, res->status);
  1329. auto it = res->headers.find("CustomServerHeader");
  1330. EXPECT_TRUE(it != res->headers.end());
  1331. EXPECT_EQ(it->second, "CustomServerValue");
  1332. }
  1333. }
  1334. class ServerTest : public ::testing::Test {
  1335. protected:
  1336. ServerTest()
  1337. : cli_(HOST, PORT)
  1338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1339. ,
  1340. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1341. #endif
  1342. {
  1343. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1344. cli_.enable_server_certificate_verification(false);
  1345. #endif
  1346. }
  1347. virtual void SetUp() {
  1348. svr_.set_mount_point("/", "./www");
  1349. svr_.set_mount_point("/mount", "./www2");
  1350. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1351. svr_.Get("/hi",
  1352. [&](const Request & /*req*/, Response &res) {
  1353. res.set_content("Hello World!", "text/plain");
  1354. })
  1355. .Get("/http_response_splitting",
  1356. [&](const Request & /*req*/, Response &res) {
  1357. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1358. EXPECT_EQ(0U, res.headers.size());
  1359. EXPECT_FALSE(res.has_header("a"));
  1360. res.set_header("a", "1\nSet-Cookie: a=1");
  1361. EXPECT_EQ(0U, res.headers.size());
  1362. EXPECT_FALSE(res.has_header("a"));
  1363. res.set_header("a", "1\rSet-Cookie: a=1");
  1364. EXPECT_EQ(0U, res.headers.size());
  1365. EXPECT_FALSE(res.has_header("a"));
  1366. res.set_header("a\r\nb", "0");
  1367. EXPECT_EQ(0U, res.headers.size());
  1368. EXPECT_FALSE(res.has_header("a"));
  1369. res.set_header("a\rb", "0");
  1370. EXPECT_EQ(0U, res.headers.size());
  1371. EXPECT_FALSE(res.has_header("a"));
  1372. res.set_header("a\nb", "0");
  1373. EXPECT_EQ(0U, res.headers.size());
  1374. EXPECT_FALSE(res.has_header("a"));
  1375. res.set_redirect("1\r\nSet-Cookie: a=1");
  1376. EXPECT_EQ(0U, res.headers.size());
  1377. EXPECT_FALSE(res.has_header("Location"));
  1378. })
  1379. .Get("/slow",
  1380. [&](const Request & /*req*/, Response &res) {
  1381. std::this_thread::sleep_for(std::chrono::seconds(2));
  1382. res.set_content("slow", "text/plain");
  1383. })
  1384. #if 0
  1385. .Post("/slowpost",
  1386. [&](const Request & /*req*/, Response &res) {
  1387. std::this_thread::sleep_for(std::chrono::seconds(2));
  1388. res.set_content("slow", "text/plain");
  1389. })
  1390. #endif
  1391. .Get("/remote_addr",
  1392. [&](const Request &req, Response &res) {
  1393. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1394. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1395. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1396. EXPECT_EQ(req.remote_port,
  1397. std::stoi(req.get_header_value("REMOTE_PORT")));
  1398. res.set_content(remote_addr.c_str(), "text/plain");
  1399. })
  1400. .Get("/local_addr",
  1401. [&](const Request &req, Response &res) {
  1402. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1403. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1404. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1405. auto local_port = req.get_header_value("LOCAL_PORT");
  1406. EXPECT_EQ(req.local_addr, local_addr);
  1407. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1408. res.set_content(local_addr.append(":").append(local_port),
  1409. "text/plain");
  1410. })
  1411. .Get("/endwith%",
  1412. [&](const Request & /*req*/, Response &res) {
  1413. res.set_content("Hello World!", "text/plain");
  1414. })
  1415. .Get("/a\\+\\+b",
  1416. [&](const Request &req, Response &res) {
  1417. ASSERT_TRUE(req.has_param("a +b"));
  1418. auto val = req.get_param_value("a +b");
  1419. res.set_content(val, "text/plain");
  1420. })
  1421. .Get("/", [&](const Request & /*req*/,
  1422. Response &res) { res.set_redirect("/hi"); })
  1423. .Post("/1", [](const Request & /*req*/,
  1424. Response &res) { res.set_redirect("/2", 303); })
  1425. .Get("/2",
  1426. [](const Request & /*req*/, Response &res) {
  1427. res.set_content("redirected.", "text/plain");
  1428. res.status = 200;
  1429. })
  1430. .Post("/person",
  1431. [&](const Request &req, Response &res) {
  1432. if (req.has_param("name") && req.has_param("note")) {
  1433. persons_[req.get_param_value("name")] =
  1434. req.get_param_value("note");
  1435. } else {
  1436. res.status = 400;
  1437. }
  1438. })
  1439. .Put("/person",
  1440. [&](const Request &req, Response &res) {
  1441. if (req.has_param("name") && req.has_param("note")) {
  1442. persons_[req.get_param_value("name")] =
  1443. req.get_param_value("note");
  1444. } else {
  1445. res.status = 400;
  1446. }
  1447. })
  1448. .Get("/person/(.*)",
  1449. [&](const Request &req, Response &res) {
  1450. string name = req.matches[1];
  1451. if (persons_.find(name) != persons_.end()) {
  1452. auto note = persons_[name];
  1453. res.set_content(note, "text/plain");
  1454. } else {
  1455. res.status = 404;
  1456. }
  1457. })
  1458. .Post("/x-www-form-urlencoded-json",
  1459. [&](const Request &req, Response &res) {
  1460. auto json = req.get_param_value("json");
  1461. ASSERT_EQ(JSON_DATA, json);
  1462. res.set_content(json, "appliation/json");
  1463. res.status = 200;
  1464. })
  1465. .Get("/streamed-chunked",
  1466. [&](const Request & /*req*/, Response &res) {
  1467. res.set_chunked_content_provider(
  1468. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1469. sink.os << "123";
  1470. sink.os << "456";
  1471. sink.os << "789";
  1472. sink.done();
  1473. return true;
  1474. });
  1475. })
  1476. .Get("/streamed-chunked2",
  1477. [&](const Request & /*req*/, Response &res) {
  1478. auto i = new int(0);
  1479. res.set_chunked_content_provider(
  1480. "text/plain",
  1481. [i](size_t /*offset*/, DataSink &sink) {
  1482. switch (*i) {
  1483. case 0: sink.os << "123"; break;
  1484. case 1: sink.os << "456"; break;
  1485. case 2: sink.os << "789"; break;
  1486. case 3: sink.done(); break;
  1487. }
  1488. (*i)++;
  1489. return true;
  1490. },
  1491. [i](bool success) {
  1492. EXPECT_TRUE(success);
  1493. delete i;
  1494. });
  1495. })
  1496. .Get("/streamed-chunked-with-trailer",
  1497. [&](const Request & /*req*/, Response &res) {
  1498. auto i = new int(0);
  1499. res.set_header("Trailer", "Dummy1, Dummy2");
  1500. res.set_chunked_content_provider(
  1501. "text/plain",
  1502. [i](size_t /*offset*/, DataSink &sink) {
  1503. switch (*i) {
  1504. case 0: sink.os << "123"; break;
  1505. case 1: sink.os << "456"; break;
  1506. case 2: sink.os << "789"; break;
  1507. case 3: {
  1508. sink.done_with_trailer(
  1509. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  1510. } break;
  1511. }
  1512. (*i)++;
  1513. return true;
  1514. },
  1515. [i](bool success) {
  1516. EXPECT_TRUE(success);
  1517. delete i;
  1518. });
  1519. })
  1520. .Get("/streamed",
  1521. [&](const Request & /*req*/, Response &res) {
  1522. res.set_content_provider(
  1523. 6, "text/plain",
  1524. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1525. sink.os << (offset < 3 ? "a" : "b");
  1526. return true;
  1527. });
  1528. })
  1529. .Get("/streamed-with-range",
  1530. [&](const Request & /*req*/, Response &res) {
  1531. auto data = new std::string("abcdefg");
  1532. res.set_content_provider(
  1533. data->size(), "text/plain",
  1534. [data](size_t offset, size_t length, DataSink &sink) {
  1535. size_t DATA_CHUNK_SIZE = 4;
  1536. const auto &d = *data;
  1537. auto out_len =
  1538. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1539. auto ret =
  1540. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1541. EXPECT_TRUE(ret);
  1542. return true;
  1543. },
  1544. [data](bool success) {
  1545. EXPECT_TRUE(success);
  1546. delete data;
  1547. });
  1548. })
  1549. .Get("/streamed-cancel",
  1550. [&](const Request & /*req*/, Response &res) {
  1551. res.set_content_provider(
  1552. size_t(-1), "text/plain",
  1553. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1554. sink.os << "data_chunk";
  1555. return true;
  1556. });
  1557. })
  1558. .Get("/with-range",
  1559. [&](const Request & /*req*/, Response &res) {
  1560. res.set_content("abcdefg", "text/plain");
  1561. })
  1562. .Post("/chunked",
  1563. [&](const Request &req, Response & /*res*/) {
  1564. EXPECT_EQ(req.body, "dechunked post body");
  1565. })
  1566. .Post("/large-chunked",
  1567. [&](const Request &req, Response & /*res*/) {
  1568. std::string expected(6 * 30 * 1024u, 'a');
  1569. EXPECT_EQ(req.body, expected);
  1570. })
  1571. .Post("/multipart",
  1572. [&](const Request &req, Response & /*res*/) {
  1573. EXPECT_EQ(6u, req.files.size());
  1574. ASSERT_TRUE(!req.has_file("???"));
  1575. ASSERT_TRUE(req.body.empty());
  1576. {
  1577. const auto &file = req.get_file_value("text1");
  1578. EXPECT_TRUE(file.filename.empty());
  1579. EXPECT_EQ("text default", file.content);
  1580. }
  1581. {
  1582. const auto &file = req.get_file_value("text2");
  1583. EXPECT_TRUE(file.filename.empty());
  1584. EXPECT_EQ("aωb", file.content);
  1585. }
  1586. {
  1587. const auto &file = req.get_file_value("file1");
  1588. EXPECT_EQ("hello.txt", file.filename);
  1589. EXPECT_EQ("text/plain", file.content_type);
  1590. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1591. }
  1592. {
  1593. const auto &file = req.get_file_value("file3");
  1594. EXPECT_TRUE(file.filename.empty());
  1595. EXPECT_EQ("application/octet-stream", file.content_type);
  1596. EXPECT_EQ(0u, file.content.size());
  1597. }
  1598. {
  1599. const auto &file = req.get_file_value("file4");
  1600. EXPECT_TRUE(file.filename.empty());
  1601. EXPECT_EQ(0u, file.content.size());
  1602. EXPECT_EQ("application/json tmp-string", file.content_type);
  1603. }
  1604. })
  1605. .Post("/multipart/multi_file_values",
  1606. [&](const Request &req, Response & /*res*/) {
  1607. EXPECT_EQ(5u, req.files.size());
  1608. ASSERT_TRUE(!req.has_file("???"));
  1609. ASSERT_TRUE(req.body.empty());
  1610. {
  1611. const auto &text_value = req.get_file_values("text");
  1612. EXPECT_EQ(1u, text_value.size());
  1613. auto &text = text_value[0];
  1614. EXPECT_TRUE(text.filename.empty());
  1615. EXPECT_EQ("default text", text.content);
  1616. }
  1617. {
  1618. const auto &text1_values = req.get_file_values("multi_text1");
  1619. EXPECT_EQ(2u, text1_values.size());
  1620. EXPECT_EQ("aaaaa", text1_values[0].content);
  1621. EXPECT_EQ("bbbbb", text1_values[1].content);
  1622. }
  1623. {
  1624. const auto &file1_values = req.get_file_values("multi_file1");
  1625. EXPECT_EQ(2u, file1_values.size());
  1626. auto file1 = file1_values[0];
  1627. EXPECT_EQ(file1.filename, "hello.txt");
  1628. EXPECT_EQ(file1.content_type, "text/plain");
  1629. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1630. auto file2 = file1_values[1];
  1631. EXPECT_EQ(file2.filename, "world.json");
  1632. EXPECT_EQ(file2.content_type, "application/json");
  1633. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1634. }
  1635. })
  1636. .Post("/empty",
  1637. [&](const Request &req, Response &res) {
  1638. EXPECT_EQ(req.body, "");
  1639. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1640. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1641. res.set_content("empty", "text/plain");
  1642. })
  1643. .Post("/empty-no-content-type",
  1644. [&](const Request &req, Response &res) {
  1645. EXPECT_EQ(req.body, "");
  1646. EXPECT_FALSE(req.has_header("Content-Type"));
  1647. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1648. res.set_content("empty-no-content-type", "text/plain");
  1649. })
  1650. .Post("/path-only",
  1651. [&](const Request &req, Response &res) {
  1652. EXPECT_EQ(req.body, "");
  1653. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1654. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1655. res.set_content("path-only", "text/plain");
  1656. })
  1657. .Post("/path-headers-only",
  1658. [&](const Request &req, Response &res) {
  1659. EXPECT_EQ(req.body, "");
  1660. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1661. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1662. EXPECT_EQ("world", req.get_header_value("hello"));
  1663. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1664. res.set_content("path-headers-only", "text/plain");
  1665. })
  1666. .Post("/post-large",
  1667. [&](const Request &req, Response &res) {
  1668. EXPECT_EQ(req.body, LARGE_DATA);
  1669. res.set_content(req.body, "text/plain");
  1670. })
  1671. .Put("/empty-no-content-type",
  1672. [&](const Request &req, Response &res) {
  1673. EXPECT_EQ(req.body, "");
  1674. EXPECT_FALSE(req.has_header("Content-Type"));
  1675. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1676. res.set_content("empty-no-content-type", "text/plain");
  1677. })
  1678. .Put("/put",
  1679. [&](const Request &req, Response &res) {
  1680. EXPECT_EQ(req.body, "PUT");
  1681. res.set_content(req.body, "text/plain");
  1682. })
  1683. .Put("/put-large",
  1684. [&](const Request &req, Response &res) {
  1685. EXPECT_EQ(req.body, LARGE_DATA);
  1686. res.set_content(req.body, "text/plain");
  1687. })
  1688. .Patch("/patch",
  1689. [&](const Request &req, Response &res) {
  1690. EXPECT_EQ(req.body, "PATCH");
  1691. res.set_content(req.body, "text/plain");
  1692. })
  1693. .Delete("/delete",
  1694. [&](const Request & /*req*/, Response &res) {
  1695. res.set_content("DELETE", "text/plain");
  1696. })
  1697. .Delete("/delete-body",
  1698. [&](const Request &req, Response &res) {
  1699. EXPECT_EQ(req.body, "content");
  1700. res.set_content(req.body, "text/plain");
  1701. })
  1702. .Options(R"(\*)",
  1703. [&](const Request & /*req*/, Response &res) {
  1704. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1705. })
  1706. .Get("/request-target",
  1707. [&](const Request &req, Response & /*res*/) {
  1708. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1709. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1710. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1711. })
  1712. .Get("/long-query-value",
  1713. [&](const Request &req, Response & /*res*/) {
  1714. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1715. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1716. })
  1717. .Get("/array-param",
  1718. [&](const Request &req, Response & /*res*/) {
  1719. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1720. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1721. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1722. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1723. })
  1724. .Post("/validate-no-multiple-headers",
  1725. [&](const Request &req, Response & /*res*/) {
  1726. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1727. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1728. })
  1729. .Post("/content_receiver",
  1730. [&](const Request &req, Response &res,
  1731. const ContentReader &content_reader) {
  1732. if (req.is_multipart_form_data()) {
  1733. MultipartFormDataItems files;
  1734. content_reader(
  1735. [&](const MultipartFormData &file) {
  1736. files.push_back(file);
  1737. return true;
  1738. },
  1739. [&](const char *data, size_t data_length) {
  1740. files.back().content.append(data, data_length);
  1741. return true;
  1742. });
  1743. EXPECT_EQ(5u, files.size());
  1744. {
  1745. const auto &file = get_file_value(files, "text1");
  1746. EXPECT_TRUE(file.filename.empty());
  1747. EXPECT_EQ("text default", file.content);
  1748. }
  1749. {
  1750. const auto &file = get_file_value(files, "text2");
  1751. EXPECT_TRUE(file.filename.empty());
  1752. EXPECT_EQ("aωb", file.content);
  1753. }
  1754. {
  1755. const auto &file = get_file_value(files, "file1");
  1756. EXPECT_EQ("hello.txt", file.filename);
  1757. EXPECT_EQ("text/plain", file.content_type);
  1758. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1759. }
  1760. {
  1761. const auto &file = get_file_value(files, "file3");
  1762. EXPECT_TRUE(file.filename.empty());
  1763. EXPECT_EQ("application/octet-stream", file.content_type);
  1764. EXPECT_EQ(0u, file.content.size());
  1765. }
  1766. } else {
  1767. std::string body;
  1768. content_reader([&](const char *data, size_t data_length) {
  1769. EXPECT_EQ(7U, data_length);
  1770. body.append(data, data_length);
  1771. return true;
  1772. });
  1773. EXPECT_EQ(body, "content");
  1774. res.set_content(body, "text/plain");
  1775. }
  1776. })
  1777. .Put("/content_receiver",
  1778. [&](const Request & /*req*/, Response &res,
  1779. const ContentReader &content_reader) {
  1780. std::string body;
  1781. content_reader([&](const char *data, size_t data_length) {
  1782. body.append(data, data_length);
  1783. return true;
  1784. });
  1785. EXPECT_EQ(body, "content");
  1786. res.set_content(body, "text/plain");
  1787. })
  1788. .Patch("/content_receiver",
  1789. [&](const Request & /*req*/, Response &res,
  1790. const ContentReader &content_reader) {
  1791. std::string body;
  1792. content_reader([&](const char *data, size_t data_length) {
  1793. body.append(data, data_length);
  1794. return true;
  1795. });
  1796. EXPECT_EQ(body, "content");
  1797. res.set_content(body, "text/plain");
  1798. })
  1799. .Post("/query-string-and-body",
  1800. [&](const Request &req, Response & /*res*/) {
  1801. ASSERT_TRUE(req.has_param("key"));
  1802. EXPECT_EQ(req.get_param_value("key"), "value");
  1803. EXPECT_EQ(req.body, "content");
  1804. })
  1805. .Get("/last-request",
  1806. [&](const Request &req, Response & /*res*/) {
  1807. EXPECT_EQ("close", req.get_header_value("Connection"));
  1808. })
  1809. .Get(R"(/redirect/(\d+))",
  1810. [&](const Request &req, Response &res) {
  1811. auto num = std::stoi(req.matches[1]) + 1;
  1812. std::string url = "/redirect/" + std::to_string(num);
  1813. res.set_redirect(url);
  1814. })
  1815. .Post("/binary",
  1816. [&](const Request &req, Response &res) {
  1817. EXPECT_EQ(4U, req.body.size());
  1818. EXPECT_EQ("application/octet-stream",
  1819. req.get_header_value("Content-Type"));
  1820. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1821. res.set_content(req.body, "application/octet-stream");
  1822. })
  1823. .Put("/binary",
  1824. [&](const Request &req, Response &res) {
  1825. EXPECT_EQ(4U, req.body.size());
  1826. EXPECT_EQ("application/octet-stream",
  1827. req.get_header_value("Content-Type"));
  1828. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1829. res.set_content(req.body, "application/octet-stream");
  1830. })
  1831. .Patch("/binary",
  1832. [&](const Request &req, Response &res) {
  1833. EXPECT_EQ(4U, req.body.size());
  1834. EXPECT_EQ("application/octet-stream",
  1835. req.get_header_value("Content-Type"));
  1836. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1837. res.set_content(req.body, "application/octet-stream");
  1838. })
  1839. .Delete("/binary",
  1840. [&](const Request &req, Response &res) {
  1841. EXPECT_EQ(4U, req.body.size());
  1842. EXPECT_EQ("application/octet-stream",
  1843. req.get_header_value("Content-Type"));
  1844. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1845. res.set_content(req.body, "application/octet-stream");
  1846. })
  1847. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1848. .Get("/compress",
  1849. [&](const Request & /*req*/, Response &res) {
  1850. res.set_content(
  1851. "12345678901234567890123456789012345678901234567890123456789"
  1852. "01234567890123456789012345678901234567890",
  1853. "text/plain");
  1854. })
  1855. .Get("/nocompress",
  1856. [&](const Request & /*req*/, Response &res) {
  1857. res.set_content(
  1858. "12345678901234567890123456789012345678901234567890123456789"
  1859. "01234567890123456789012345678901234567890",
  1860. "application/octet-stream");
  1861. })
  1862. .Post("/compress-multipart",
  1863. [&](const Request &req, Response & /*res*/) {
  1864. EXPECT_EQ(2u, req.files.size());
  1865. ASSERT_TRUE(!req.has_file("???"));
  1866. {
  1867. const auto &file = req.get_file_value("key1");
  1868. EXPECT_TRUE(file.filename.empty());
  1869. EXPECT_EQ("test", file.content);
  1870. }
  1871. {
  1872. const auto &file = req.get_file_value("key2");
  1873. EXPECT_TRUE(file.filename.empty());
  1874. EXPECT_EQ("--abcdefg123", file.content);
  1875. }
  1876. })
  1877. #endif
  1878. ;
  1879. persons_["john"] = "programmer";
  1880. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1881. svr_.wait_until_ready();
  1882. }
  1883. virtual void TearDown() {
  1884. svr_.stop();
  1885. if (!request_threads_.empty()) {
  1886. std::this_thread::sleep_for(std::chrono::seconds(1));
  1887. for (auto &t : request_threads_) {
  1888. t.join();
  1889. }
  1890. }
  1891. t_.join();
  1892. }
  1893. map<string, string> persons_;
  1894. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1895. SSLClient cli_;
  1896. SSLServer svr_;
  1897. #else
  1898. Client cli_;
  1899. Server svr_;
  1900. #endif
  1901. thread t_;
  1902. std::vector<thread> request_threads_;
  1903. };
  1904. TEST_F(ServerTest, GetMethod200) {
  1905. auto res = cli_.Get("/hi");
  1906. ASSERT_TRUE(res);
  1907. EXPECT_EQ("HTTP/1.1", res->version);
  1908. EXPECT_EQ(200, res->status);
  1909. EXPECT_EQ("OK", res->reason);
  1910. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1911. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1912. EXPECT_EQ("Hello World!", res->body);
  1913. }
  1914. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1915. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1916. ASSERT_TRUE(res);
  1917. EXPECT_EQ("HTTP/1.1", res->version);
  1918. EXPECT_EQ(200, res->status);
  1919. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1920. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1921. EXPECT_EQ("Hello World!", res->body);
  1922. }
  1923. TEST_F(ServerTest, GetMethod302) {
  1924. auto res = cli_.Get("/");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(302, res->status);
  1927. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1928. }
  1929. TEST_F(ServerTest, GetMethod302Redirect) {
  1930. cli_.set_follow_location(true);
  1931. auto res = cli_.Get("/");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(200, res->status);
  1934. EXPECT_EQ("Hello World!", res->body);
  1935. EXPECT_EQ("/hi", res->location);
  1936. }
  1937. TEST_F(ServerTest, GetMethod404) {
  1938. auto res = cli_.Get("/invalid");
  1939. ASSERT_TRUE(res);
  1940. EXPECT_EQ(404, res->status);
  1941. }
  1942. TEST_F(ServerTest, HeadMethod200) {
  1943. auto res = cli_.Head("/hi");
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(200, res->status);
  1946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1947. EXPECT_TRUE(res->body.empty());
  1948. }
  1949. TEST_F(ServerTest, HeadMethod200Static) {
  1950. auto res = cli_.Head("/mount/dir/index.html");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(200, res->status);
  1953. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1954. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1955. EXPECT_TRUE(res->body.empty());
  1956. }
  1957. TEST_F(ServerTest, HeadMethod404) {
  1958. auto res = cli_.Head("/invalid");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(404, res->status);
  1961. EXPECT_TRUE(res->body.empty());
  1962. }
  1963. TEST_F(ServerTest, GetMethodPersonJohn) {
  1964. auto res = cli_.Get("/person/john");
  1965. ASSERT_TRUE(res);
  1966. EXPECT_EQ(200, res->status);
  1967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1968. EXPECT_EQ("programmer", res->body);
  1969. }
  1970. TEST_F(ServerTest, PostMethod1) {
  1971. auto res = cli_.Get("/person/john1");
  1972. ASSERT_TRUE(res);
  1973. ASSERT_EQ(404, res->status);
  1974. res = cli_.Post("/person", "name=john1&note=coder",
  1975. "application/x-www-form-urlencoded");
  1976. ASSERT_TRUE(res);
  1977. ASSERT_EQ(200, res->status);
  1978. res = cli_.Get("/person/john1");
  1979. ASSERT_TRUE(res);
  1980. ASSERT_EQ(200, res->status);
  1981. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1982. ASSERT_EQ("coder", res->body);
  1983. }
  1984. TEST_F(ServerTest, PostMethod2) {
  1985. auto res = cli_.Get("/person/john2");
  1986. ASSERT_TRUE(res);
  1987. ASSERT_EQ(404, res->status);
  1988. Params params;
  1989. params.emplace("name", "john2");
  1990. params.emplace("note", "coder");
  1991. res = cli_.Post("/person", params);
  1992. ASSERT_TRUE(res);
  1993. ASSERT_EQ(200, res->status);
  1994. res = cli_.Get("/person/john2");
  1995. ASSERT_TRUE(res);
  1996. ASSERT_EQ(200, res->status);
  1997. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1998. ASSERT_EQ("coder", res->body);
  1999. }
  2000. TEST_F(ServerTest, PutMethod3) {
  2001. auto res = cli_.Get("/person/john3");
  2002. ASSERT_TRUE(res);
  2003. ASSERT_EQ(404, res->status);
  2004. Params params;
  2005. params.emplace("name", "john3");
  2006. params.emplace("note", "coder");
  2007. res = cli_.Put("/person", params);
  2008. ASSERT_TRUE(res);
  2009. ASSERT_EQ(200, res->status);
  2010. res = cli_.Get("/person/john3");
  2011. ASSERT_TRUE(res);
  2012. ASSERT_EQ(200, res->status);
  2013. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2014. ASSERT_EQ("coder", res->body);
  2015. }
  2016. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2017. Params params;
  2018. params.emplace("json", JSON_DATA);
  2019. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2020. ASSERT_TRUE(res);
  2021. ASSERT_EQ(200, res->status);
  2022. ASSERT_EQ(JSON_DATA, res->body);
  2023. }
  2024. TEST_F(ServerTest, PostEmptyContent) {
  2025. auto res = cli_.Post("/empty", "", "text/plain");
  2026. ASSERT_TRUE(res);
  2027. ASSERT_EQ(200, res->status);
  2028. ASSERT_EQ("empty", res->body);
  2029. }
  2030. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2031. auto res = cli_.Post("/empty-no-content-type");
  2032. ASSERT_TRUE(res);
  2033. ASSERT_EQ(200, res->status);
  2034. ASSERT_EQ("empty-no-content-type", res->body);
  2035. }
  2036. TEST_F(ServerTest, PostPathOnly) {
  2037. auto res = cli_.Post("/path-only");
  2038. ASSERT_TRUE(res);
  2039. ASSERT_EQ(200, res->status);
  2040. ASSERT_EQ("path-only", res->body);
  2041. }
  2042. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2043. auto res = cli_.Post("/path-headers-only",
  2044. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2045. ASSERT_TRUE(res);
  2046. ASSERT_EQ(200, res->status);
  2047. ASSERT_EQ("path-headers-only", res->body);
  2048. }
  2049. TEST_F(ServerTest, PostLarge) {
  2050. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2051. ASSERT_TRUE(res);
  2052. ASSERT_EQ(200, res->status);
  2053. EXPECT_EQ(LARGE_DATA, res->body);
  2054. }
  2055. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2056. auto res = cli_.Put("/empty-no-content-type");
  2057. ASSERT_TRUE(res);
  2058. ASSERT_EQ(200, res->status);
  2059. ASSERT_EQ("empty-no-content-type", res->body);
  2060. }
  2061. TEST_F(ServerTest, GetMethodDir) {
  2062. auto res = cli_.Get("/dir/");
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(200, res->status);
  2065. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2066. auto body = R"(<html>
  2067. <head>
  2068. </head>
  2069. <body>
  2070. <a href="/dir/test.html">Test</a>
  2071. <a href="/hi">hi</a>
  2072. </body>
  2073. </html>
  2074. )";
  2075. EXPECT_EQ(body, res->body);
  2076. }
  2077. TEST_F(ServerTest, GetMethodDirTest) {
  2078. auto res = cli_.Get("/dir/test.html");
  2079. ASSERT_TRUE(res);
  2080. EXPECT_EQ(200, res->status);
  2081. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2082. EXPECT_EQ("test.html", res->body);
  2083. }
  2084. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2085. auto res = cli_.Get("/dir/../dir/test.html");
  2086. ASSERT_TRUE(res);
  2087. EXPECT_EQ(200, res->status);
  2088. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2089. EXPECT_EQ("test.html", res->body);
  2090. }
  2091. TEST_F(ServerTest, GetMethodInvalidPath) {
  2092. auto res = cli_.Get("/dir/../test.html");
  2093. ASSERT_TRUE(res);
  2094. EXPECT_EQ(404, res->status);
  2095. }
  2096. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2097. auto res = cli_.Get("/../www/dir/test.html");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(404, res->status);
  2100. }
  2101. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2102. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2103. ASSERT_TRUE(res);
  2104. EXPECT_EQ(404, res->status);
  2105. }
  2106. TEST_F(ServerTest, GetMethodDirMountTest) {
  2107. auto res = cli_.Get("/mount/dir/test.html");
  2108. ASSERT_TRUE(res);
  2109. EXPECT_EQ(200, res->status);
  2110. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2111. EXPECT_EQ("test.html", res->body);
  2112. }
  2113. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2114. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2115. ASSERT_TRUE(res);
  2116. EXPECT_EQ(200, res->status);
  2117. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2118. EXPECT_EQ("test.html", res->body);
  2119. }
  2120. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2121. auto res = cli_.Get("/mount/dir/../test.html");
  2122. ASSERT_TRUE(res);
  2123. EXPECT_EQ(404, res->status);
  2124. }
  2125. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2126. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(404, res->status);
  2129. }
  2130. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2131. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(404, res->status);
  2134. }
  2135. TEST_F(ServerTest, PostMethod303) {
  2136. auto res = cli_.Post("/1", "body", "text/plain");
  2137. ASSERT_TRUE(res);
  2138. EXPECT_EQ(303, res->status);
  2139. EXPECT_EQ("/2", res->get_header_value("Location"));
  2140. }
  2141. TEST_F(ServerTest, PostMethod303Redirect) {
  2142. cli_.set_follow_location(true);
  2143. auto res = cli_.Post("/1", "body", "text/plain");
  2144. ASSERT_TRUE(res);
  2145. EXPECT_EQ(200, res->status);
  2146. EXPECT_EQ("redirected.", res->body);
  2147. EXPECT_EQ("/2", res->location);
  2148. }
  2149. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2150. auto res = cli_.Get("/dir/test.abcde");
  2151. ASSERT_TRUE(res);
  2152. EXPECT_EQ(200, res->status);
  2153. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2154. EXPECT_EQ("abcde", res->body);
  2155. }
  2156. TEST_F(ServerTest, StaticFileRange) {
  2157. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2158. ASSERT_TRUE(res);
  2159. EXPECT_EQ(206, res->status);
  2160. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2161. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2162. EXPECT_EQ(true, res->has_header("Content-Range"));
  2163. EXPECT_EQ(std::string("cd"), res->body);
  2164. }
  2165. TEST_F(ServerTest, StaticFileRanges) {
  2166. auto res =
  2167. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(206, res->status);
  2170. EXPECT_TRUE(
  2171. res->get_header_value("Content-Type")
  2172. .find(
  2173. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2174. 0);
  2175. EXPECT_EQ("265", res->get_header_value("Content-Length"));
  2176. }
  2177. TEST_F(ServerTest, StaticFileRangeHead) {
  2178. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2179. ASSERT_TRUE(res);
  2180. EXPECT_EQ(206, res->status);
  2181. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2182. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2183. EXPECT_EQ(true, res->has_header("Content-Range"));
  2184. }
  2185. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2186. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(206, res->status);
  2189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2190. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2191. EXPECT_EQ(true, res->has_header("Content-Range"));
  2192. EXPECT_EQ("LAST\n", res->body);
  2193. }
  2194. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2195. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2196. ASSERT_TRUE(res);
  2197. EXPECT_EQ(206, res->status);
  2198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2199. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2200. EXPECT_EQ(true, res->has_header("Content-Range"));
  2201. }
  2202. TEST_F(ServerTest, StaticFileBigFile) {
  2203. auto res = cli_.Get("/dir/1MB.txt");
  2204. ASSERT_TRUE(res);
  2205. EXPECT_EQ(200, res->status);
  2206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2207. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2208. }
  2209. TEST_F(ServerTest, InvalidBaseDirMount) {
  2210. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2211. }
  2212. TEST_F(ServerTest, Binary) {
  2213. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2214. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2215. "application/octet-stream");
  2216. ASSERT_TRUE(res);
  2217. ASSERT_EQ(200, res->status);
  2218. ASSERT_EQ(4U, res->body.size());
  2219. res = cli_.Put("/binary", binary.data(), binary.size(),
  2220. "application/octet-stream");
  2221. ASSERT_TRUE(res);
  2222. ASSERT_EQ(200, res->status);
  2223. ASSERT_EQ(4U, res->body.size());
  2224. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2225. "application/octet-stream");
  2226. ASSERT_TRUE(res);
  2227. ASSERT_EQ(200, res->status);
  2228. ASSERT_EQ(4U, res->body.size());
  2229. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2230. "application/octet-stream");
  2231. ASSERT_TRUE(res);
  2232. ASSERT_EQ(200, res->status);
  2233. ASSERT_EQ(4U, res->body.size());
  2234. }
  2235. TEST_F(ServerTest, BinaryString) {
  2236. auto binary = std::string("\x00\x01\x02\x03", 4);
  2237. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2238. ASSERT_TRUE(res);
  2239. ASSERT_EQ(200, res->status);
  2240. ASSERT_EQ(4U, res->body.size());
  2241. res = cli_.Put("/binary", binary, "application/octet-stream");
  2242. ASSERT_TRUE(res);
  2243. ASSERT_EQ(200, res->status);
  2244. ASSERT_EQ(4U, res->body.size());
  2245. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2246. ASSERT_TRUE(res);
  2247. ASSERT_EQ(200, res->status);
  2248. ASSERT_EQ(4U, res->body.size());
  2249. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2250. ASSERT_TRUE(res);
  2251. ASSERT_EQ(200, res->status);
  2252. ASSERT_EQ(4U, res->body.size());
  2253. }
  2254. TEST_F(ServerTest, EmptyRequest) {
  2255. auto res = cli_.Get("");
  2256. ASSERT_TRUE(!res);
  2257. EXPECT_EQ(Error::Connection, res.error());
  2258. }
  2259. TEST_F(ServerTest, LongRequest) {
  2260. std::string request;
  2261. for (size_t i = 0; i < 545; i++) {
  2262. request += "/TooLongRequest";
  2263. }
  2264. request += "OK";
  2265. auto res = cli_.Get(request.c_str());
  2266. ASSERT_TRUE(res);
  2267. EXPECT_EQ(404, res->status);
  2268. }
  2269. TEST_F(ServerTest, TooLongRequest) {
  2270. std::string request;
  2271. for (size_t i = 0; i < 545; i++) {
  2272. request += "/TooLongRequest";
  2273. }
  2274. request += "_NG";
  2275. auto res = cli_.Get(request.c_str());
  2276. ASSERT_TRUE(res);
  2277. EXPECT_EQ(414, res->status);
  2278. }
  2279. TEST_F(ServerTest, LongHeader) {
  2280. Request req;
  2281. req.method = "GET";
  2282. req.path = "/hi";
  2283. std::string host_and_port;
  2284. host_and_port += HOST;
  2285. host_and_port += ":";
  2286. host_and_port += std::to_string(PORT);
  2287. req.headers.emplace("Host", host_and_port.c_str());
  2288. req.headers.emplace("Accept", "*/*");
  2289. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2290. req.headers.emplace(
  2291. "Header-Name",
  2292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2320. "@@@@@@@@@@@@@@@@");
  2321. auto res = std::make_shared<Response>();
  2322. auto error = Error::Success;
  2323. auto ret = cli_.send(req, *res, error);
  2324. ASSERT_TRUE(ret);
  2325. EXPECT_EQ(200, res->status);
  2326. }
  2327. TEST_F(ServerTest, LongQueryValue) {
  2328. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(414, res->status);
  2331. }
  2332. TEST_F(ServerTest, TooLongHeader) {
  2333. Request req;
  2334. req.method = "GET";
  2335. req.path = "/hi";
  2336. std::string host_and_port;
  2337. host_and_port += HOST;
  2338. host_and_port += ":";
  2339. host_and_port += std::to_string(PORT);
  2340. req.headers.emplace("Host", host_and_port.c_str());
  2341. req.headers.emplace("Accept", "*/*");
  2342. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2343. req.headers.emplace(
  2344. "Header-Name",
  2345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2373. "@@@@@@@@@@@@@@@@@");
  2374. auto res = std::make_shared<Response>();
  2375. auto error = Error::Success;
  2376. auto ret = cli_.send(req, *res, error);
  2377. ASSERT_TRUE(ret);
  2378. EXPECT_EQ(200, res->status);
  2379. }
  2380. TEST_F(ServerTest, PercentEncoding) {
  2381. auto res = cli_.Get("/e%6edwith%");
  2382. ASSERT_TRUE(res);
  2383. EXPECT_EQ(200, res->status);
  2384. }
  2385. TEST_F(ServerTest, PercentEncodingUnicode) {
  2386. auto res = cli_.Get("/e%u006edwith%");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(200, res->status);
  2389. }
  2390. TEST_F(ServerTest, InvalidPercentEncoding) {
  2391. auto res = cli_.Get("/%endwith%");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(404, res->status);
  2394. }
  2395. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2396. auto res = cli_.Get("/%uendwith%");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(404, res->status);
  2399. }
  2400. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2401. auto res = cli_.Get("/hello?aaa=bbb%");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(404, res->status);
  2404. }
  2405. TEST_F(ServerTest, PlusSignEncoding) {
  2406. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2407. ASSERT_TRUE(res);
  2408. EXPECT_EQ(200, res->status);
  2409. EXPECT_EQ("a +b", res->body);
  2410. }
  2411. TEST_F(ServerTest, MultipartFormData) {
  2412. MultipartFormDataItems items = {
  2413. {"text1", "text default", "", ""},
  2414. {"text2", "aωb", "", ""},
  2415. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2416. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2417. {"file3", "", "", "application/octet-stream"},
  2418. {"file4", "", "", " application/json tmp-string "}};
  2419. auto res = cli_.Post("/multipart", items);
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(200, res->status);
  2422. }
  2423. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2424. MultipartFormDataItems items = {
  2425. {"text", "default text", "", ""},
  2426. {"multi_text1", "aaaaa", "", ""},
  2427. {"multi_text1", "bbbbb", "", ""},
  2428. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2429. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2430. "application/json"},
  2431. };
  2432. auto res = cli_.Post("/multipart/multi_file_values", items);
  2433. ASSERT_TRUE(res);
  2434. EXPECT_EQ(200, res->status);
  2435. }
  2436. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2437. auto res = cli_.Get("/hi");
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(200, res->status);
  2440. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2441. EXPECT_EQ("Hello World!", res->body);
  2442. }
  2443. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2444. Request req;
  2445. req.method = "POST";
  2446. req.path = "/chunked";
  2447. std::string host_and_port;
  2448. host_and_port += HOST;
  2449. host_and_port += ":";
  2450. host_and_port += std::to_string(PORT);
  2451. req.headers.emplace("Host", host_and_port.c_str());
  2452. req.headers.emplace("Accept", "*/*");
  2453. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2454. req.headers.emplace("Content-Type", "text/plain");
  2455. req.headers.emplace("Content-Length", "0");
  2456. req.headers.emplace(
  2457. "Transfer-Encoding",
  2458. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2459. // Client does not chunk, so make a chunked body manually.
  2460. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2461. auto res = std::make_shared<Response>();
  2462. auto error = Error::Success;
  2463. auto ret = cli_.send(req, *res, error);
  2464. ASSERT_TRUE(ret);
  2465. EXPECT_EQ(200, res->status);
  2466. }
  2467. TEST_F(ServerTest, GetStreamed2) {
  2468. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(206, res->status);
  2471. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2472. EXPECT_EQ(std::string("ab"), res->body);
  2473. }
  2474. TEST_F(ServerTest, GetStreamed) {
  2475. auto res = cli_.Get("/streamed");
  2476. ASSERT_TRUE(res);
  2477. EXPECT_EQ(200, res->status);
  2478. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2479. EXPECT_EQ(std::string("aaabbb"), res->body);
  2480. }
  2481. TEST_F(ServerTest, GetStreamedWithRange1) {
  2482. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2483. ASSERT_TRUE(res);
  2484. EXPECT_EQ(206, res->status);
  2485. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2486. EXPECT_EQ(true, res->has_header("Content-Range"));
  2487. EXPECT_EQ(std::string("def"), res->body);
  2488. }
  2489. TEST_F(ServerTest, GetStreamedWithRange2) {
  2490. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2491. ASSERT_TRUE(res);
  2492. EXPECT_EQ(206, res->status);
  2493. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2494. EXPECT_EQ(true, res->has_header("Content-Range"));
  2495. EXPECT_EQ(std::string("bcdefg"), res->body);
  2496. }
  2497. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2498. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(206, res->status);
  2501. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2502. EXPECT_EQ(true, res->has_header("Content-Range"));
  2503. EXPECT_EQ(std::string("efg"), res->body);
  2504. }
  2505. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2506. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2507. ASSERT_TRUE(res);
  2508. EXPECT_EQ(206, res->status);
  2509. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2510. EXPECT_EQ(true, res->has_header("Content-Range"));
  2511. EXPECT_EQ(std::string("abcdefg"), res->body);
  2512. }
  2513. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2514. auto res = cli_.Get("/streamed-with-range",
  2515. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2516. "92233720368547758079223372036854775807"}});
  2517. ASSERT_TRUE(res);
  2518. EXPECT_EQ(416, res->status);
  2519. }
  2520. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2521. auto res =
  2522. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2523. EXPECT_EQ(206, res->status);
  2524. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2525. EXPECT_EQ(true, res->has_header("Content-Range"));
  2526. EXPECT_EQ(std::string("abcdefg"), res->body);
  2527. }
  2528. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2529. auto res =
  2530. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2531. ASSERT_TRUE(res);
  2532. EXPECT_EQ(206, res->status);
  2533. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2534. EXPECT_EQ(false, res->has_header("Content-Range"));
  2535. EXPECT_EQ(267U, res->body.size());
  2536. }
  2537. TEST_F(ServerTest, GetStreamedEndless) {
  2538. uint64_t offset = 0;
  2539. auto res = cli_.Get("/streamed-cancel",
  2540. [&](const char * /*data*/, uint64_t data_length) {
  2541. if (offset < 100) {
  2542. offset += data_length;
  2543. return true;
  2544. }
  2545. return false;
  2546. });
  2547. ASSERT_TRUE(!res);
  2548. EXPECT_EQ(Error::Canceled, res.error());
  2549. }
  2550. TEST_F(ServerTest, ClientStop) {
  2551. std::atomic_size_t count{4};
  2552. std::vector<std::thread> threads;
  2553. for (auto i = count.load(); i != 0; --i) {
  2554. threads.emplace_back([&]() {
  2555. auto res = cli_.Get("/streamed-cancel",
  2556. [&](const char *, uint64_t) { return true; });
  2557. --count;
  2558. ASSERT_TRUE(!res);
  2559. EXPECT_TRUE(res.error() == Error::Canceled ||
  2560. res.error() == Error::Read || res.error() == Error::Write);
  2561. });
  2562. }
  2563. std::this_thread::sleep_for(std::chrono::seconds(2));
  2564. while (count != 0) {
  2565. cli_.stop();
  2566. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2567. }
  2568. for (auto &t : threads) {
  2569. t.join();
  2570. }
  2571. }
  2572. TEST_F(ServerTest, GetWithRange1) {
  2573. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2574. ASSERT_TRUE(res);
  2575. EXPECT_EQ(206, res->status);
  2576. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2577. EXPECT_EQ(true, res->has_header("Content-Range"));
  2578. EXPECT_EQ(std::string("def"), res->body);
  2579. }
  2580. TEST_F(ServerTest, GetWithRange2) {
  2581. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2582. ASSERT_TRUE(res);
  2583. EXPECT_EQ(206, res->status);
  2584. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2585. EXPECT_EQ(true, res->has_header("Content-Range"));
  2586. EXPECT_EQ(std::string("bcdefg"), res->body);
  2587. }
  2588. TEST_F(ServerTest, GetWithRange3) {
  2589. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2590. ASSERT_TRUE(res);
  2591. EXPECT_EQ(206, res->status);
  2592. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2593. EXPECT_EQ(true, res->has_header("Content-Range"));
  2594. EXPECT_EQ(std::string("a"), res->body);
  2595. }
  2596. TEST_F(ServerTest, GetWithRange4) {
  2597. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2598. ASSERT_TRUE(res);
  2599. EXPECT_EQ(206, res->status);
  2600. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2601. EXPECT_EQ(true, res->has_header("Content-Range"));
  2602. EXPECT_EQ(std::string("fg"), res->body);
  2603. }
  2604. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2605. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2606. ASSERT_TRUE(res);
  2607. EXPECT_EQ(416, res->status);
  2608. }
  2609. TEST_F(ServerTest, GetWithRangeMultipart) {
  2610. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2611. ASSERT_TRUE(res);
  2612. EXPECT_EQ(206, res->status);
  2613. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2614. EXPECT_EQ(false, res->has_header("Content-Range"));
  2615. EXPECT_EQ(267U, res->body.size());
  2616. }
  2617. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2618. auto res =
  2619. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2620. ASSERT_TRUE(res);
  2621. EXPECT_EQ(416, res->status);
  2622. }
  2623. TEST_F(ServerTest, GetStreamedChunked) {
  2624. auto res = cli_.Get("/streamed-chunked");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(200, res->status);
  2627. EXPECT_EQ(std::string("123456789"), res->body);
  2628. }
  2629. TEST_F(ServerTest, GetStreamedChunked2) {
  2630. auto res = cli_.Get("/streamed-chunked2");
  2631. ASSERT_TRUE(res);
  2632. EXPECT_EQ(200, res->status);
  2633. EXPECT_EQ(std::string("123456789"), res->body);
  2634. }
  2635. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2636. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(200, res->status);
  2639. EXPECT_EQ(std::string("123456789"), res->body);
  2640. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2641. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2642. }
  2643. TEST_F(ServerTest, LargeChunkedPost) {
  2644. Request req;
  2645. req.method = "POST";
  2646. req.path = "/large-chunked";
  2647. std::string host_and_port;
  2648. host_and_port += HOST;
  2649. host_and_port += ":";
  2650. host_and_port += std::to_string(PORT);
  2651. req.headers.emplace("Host", host_and_port.c_str());
  2652. req.headers.emplace("Accept", "*/*");
  2653. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2654. req.headers.emplace("Content-Type", "text/plain");
  2655. req.headers.emplace("Content-Length", "0");
  2656. req.headers.emplace("Transfer-Encoding", "chunked");
  2657. std::string long_string(30 * 1024u, 'a');
  2658. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2659. // Attempt to make a large enough post to exceed OS buffers, to test that
  2660. // the server handles short reads if the full chunk data isn't available.
  2661. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2662. auto res = std::make_shared<Response>();
  2663. auto error = Error::Success;
  2664. auto ret = cli_.send(req, *res, error);
  2665. ASSERT_TRUE(ret);
  2666. EXPECT_EQ(200, res->status);
  2667. }
  2668. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2669. auto res = cli_.Get("/remote_addr");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(200, res->status);
  2672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2673. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2674. }
  2675. TEST_F(ServerTest, GetMethodLocalAddr) {
  2676. auto res = cli_.Get("/local_addr");
  2677. ASSERT_TRUE(res);
  2678. EXPECT_EQ(200, res->status);
  2679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2680. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2681. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2682. }
  2683. TEST_F(ServerTest, HTTPResponseSplitting) {
  2684. auto res = cli_.Get("/http_response_splitting");
  2685. ASSERT_TRUE(res);
  2686. EXPECT_EQ(200, res->status);
  2687. }
  2688. TEST_F(ServerTest, SlowRequest) {
  2689. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2690. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2691. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2692. }
  2693. #if 0
  2694. TEST_F(ServerTest, SlowPost) {
  2695. char buffer[64 * 1024];
  2696. memset(buffer, 0x42, sizeof(buffer));
  2697. auto res = cli_.Post(
  2698. "/slowpost", 64 * 1024 * 1024,
  2699. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2700. auto ret = sink.write(buffer, sizeof(buffer));
  2701. EXPECT_TRUE(ret);
  2702. return true;
  2703. },
  2704. "text/plain");
  2705. ASSERT_TRUE(res);
  2706. EXPECT_EQ(200, res->status);
  2707. }
  2708. TEST_F(ServerTest, SlowPostFail) {
  2709. char buffer[64 * 1024];
  2710. memset(buffer, 0x42, sizeof(buffer));
  2711. cli_.set_write_timeout(std::chrono::seconds(0));
  2712. auto res = cli_.Post(
  2713. "/slowpost", 64 * 1024 * 1024,
  2714. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2715. sink.write(buffer, sizeof(buffer));
  2716. return true;
  2717. },
  2718. "text/plain");
  2719. ASSERT_TRUE(!res);
  2720. EXPECT_EQ(Error::Write, res.error());
  2721. }
  2722. #endif
  2723. TEST_F(ServerTest, Put) {
  2724. auto res = cli_.Put("/put", "PUT", "text/plain");
  2725. ASSERT_TRUE(res);
  2726. EXPECT_EQ(200, res->status);
  2727. EXPECT_EQ("PUT", res->body);
  2728. }
  2729. TEST_F(ServerTest, PutWithContentProvider) {
  2730. auto res = cli_.Put(
  2731. "/put", 3,
  2732. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2733. sink.os << "PUT";
  2734. return true;
  2735. },
  2736. "text/plain");
  2737. ASSERT_TRUE(res);
  2738. EXPECT_EQ(200, res->status);
  2739. EXPECT_EQ("PUT", res->body);
  2740. }
  2741. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2742. auto res = cli_.Post(
  2743. "/post", 42,
  2744. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2745. return false;
  2746. },
  2747. "text/plain");
  2748. ASSERT_TRUE(!res);
  2749. EXPECT_EQ(Error::Canceled, res.error());
  2750. }
  2751. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2752. auto res = cli_.Put(
  2753. "/put",
  2754. [](size_t /*offset*/, DataSink &sink) {
  2755. sink.os << "PUT";
  2756. sink.done();
  2757. return true;
  2758. },
  2759. "text/plain");
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(200, res->status);
  2762. EXPECT_EQ("PUT", res->body);
  2763. }
  2764. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2765. auto res = cli_.Post(
  2766. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2767. "text/plain");
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2772. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2773. cli_.set_compress(true);
  2774. auto res = cli_.Put(
  2775. "/put", 3,
  2776. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2777. sink.os << "PUT";
  2778. return true;
  2779. },
  2780. "text/plain");
  2781. ASSERT_TRUE(res);
  2782. EXPECT_EQ(200, res->status);
  2783. EXPECT_EQ("PUT", res->body);
  2784. }
  2785. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2786. cli_.set_compress(true);
  2787. auto res = cli_.Post(
  2788. "/post", 42,
  2789. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2790. return false;
  2791. },
  2792. "text/plain");
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2797. cli_.set_compress(true);
  2798. auto res = cli_.Put(
  2799. "/put",
  2800. [](size_t /*offset*/, DataSink &sink) {
  2801. sink.os << "PUT";
  2802. sink.done();
  2803. return true;
  2804. },
  2805. "text/plain");
  2806. ASSERT_TRUE(res);
  2807. EXPECT_EQ(200, res->status);
  2808. EXPECT_EQ("PUT", res->body);
  2809. }
  2810. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2811. cli_.set_compress(true);
  2812. auto res = cli_.Post(
  2813. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2814. "text/plain");
  2815. ASSERT_TRUE(!res);
  2816. EXPECT_EQ(Error::Canceled, res.error());
  2817. }
  2818. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2819. cli_.set_compress(true);
  2820. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2821. ASSERT_TRUE(res);
  2822. EXPECT_EQ(200, res->status);
  2823. EXPECT_EQ(LARGE_DATA, res->body);
  2824. }
  2825. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2826. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2827. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2828. Client cli(s.c_str());
  2829. cli.enable_server_certificate_verification(false);
  2830. #else
  2831. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2832. Client cli(s.c_str());
  2833. #endif
  2834. cli.set_compress(true);
  2835. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2836. ASSERT_TRUE(res);
  2837. EXPECT_EQ(200, res->status);
  2838. EXPECT_EQ(LARGE_DATA, res->body);
  2839. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  2840. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2841. }
  2842. TEST_F(ServerTest, PutContentWithDeflate) {
  2843. cli_.set_compress(false);
  2844. Headers headers;
  2845. headers.emplace("Content-Encoding", "deflate");
  2846. // PUT in deflate format:
  2847. auto res = cli_.Put("/put", headers,
  2848. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2849. ASSERT_TRUE(res);
  2850. EXPECT_EQ(200, res->status);
  2851. EXPECT_EQ("PUT", res->body);
  2852. }
  2853. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2854. Headers headers;
  2855. headers.emplace("Accept-Encoding", "gzip, deflate");
  2856. auto res = cli_.Get("/streamed-chunked", headers);
  2857. ASSERT_TRUE(res);
  2858. EXPECT_EQ(200, res->status);
  2859. EXPECT_EQ(std::string("123456789"), res->body);
  2860. }
  2861. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2862. Headers headers;
  2863. headers.emplace("Accept-Encoding", "gzip, deflate");
  2864. auto res = cli_.Get("/streamed-chunked2", headers);
  2865. ASSERT_TRUE(res);
  2866. EXPECT_EQ(200, res->status);
  2867. EXPECT_EQ(std::string("123456789"), res->body);
  2868. }
  2869. TEST(GzipDecompressor, ChunkedDecompression) {
  2870. std::string data;
  2871. for (size_t i = 0; i < 32 * 1024; ++i) {
  2872. data.push_back(static_cast<char>('a' + i % 26));
  2873. }
  2874. std::string compressed_data;
  2875. {
  2876. httplib::detail::gzip_compressor compressor;
  2877. bool result = compressor.compress(
  2878. data.data(), data.size(),
  2879. /*last=*/true,
  2880. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2881. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2882. compressed_data_size);
  2883. return true;
  2884. });
  2885. ASSERT_TRUE(result);
  2886. }
  2887. std::string decompressed_data;
  2888. {
  2889. httplib::detail::gzip_decompressor decompressor;
  2890. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2891. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2892. size_t chunk_size = 130;
  2893. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2894. chunk_begin += chunk_size) {
  2895. size_t current_chunk_size =
  2896. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2897. bool result = decompressor.decompress(
  2898. compressed_data.data() + chunk_begin, current_chunk_size,
  2899. [&](const char *decompressed_data_chunk,
  2900. size_t decompressed_data_chunk_size) {
  2901. decompressed_data.insert(decompressed_data.size(),
  2902. decompressed_data_chunk,
  2903. decompressed_data_chunk_size);
  2904. return true;
  2905. });
  2906. ASSERT_TRUE(result);
  2907. }
  2908. }
  2909. ASSERT_EQ(data, decompressed_data);
  2910. }
  2911. TEST(GzipDecompressor, DeflateDecompression) {
  2912. std::string original_text = "Raw deflate without gzip";
  2913. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2914. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2915. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2916. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  2917. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2918. std::string decompressed_data;
  2919. {
  2920. httplib::detail::gzip_decompressor decompressor;
  2921. bool result = decompressor.decompress(
  2922. compressed_data.data(), compressed_data.size(),
  2923. [&](const char *decompressed_data_chunk,
  2924. size_t decompressed_data_chunk_size) {
  2925. decompressed_data.insert(decompressed_data.size(),
  2926. decompressed_data_chunk,
  2927. decompressed_data_chunk_size);
  2928. return true;
  2929. });
  2930. ASSERT_TRUE(result);
  2931. }
  2932. ASSERT_EQ(original_text, decompressed_data);
  2933. }
  2934. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  2935. std::string original_text = "Raw deflate without gzip";
  2936. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2937. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2938. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2939. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  2940. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  2941. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2942. std::string decompressed_data;
  2943. {
  2944. httplib::detail::gzip_decompressor decompressor;
  2945. bool result = decompressor.decompress(
  2946. compressed_data.data(), compressed_data.size(),
  2947. [&](const char *decompressed_data_chunk,
  2948. size_t decompressed_data_chunk_size) {
  2949. decompressed_data.insert(decompressed_data.size(),
  2950. decompressed_data_chunk,
  2951. decompressed_data_chunk_size);
  2952. return true;
  2953. });
  2954. ASSERT_TRUE(result);
  2955. }
  2956. ASSERT_EQ(original_text, decompressed_data);
  2957. }
  2958. #ifdef _WIN32
  2959. TEST(GzipDecompressor, LargeRandomData) {
  2960. // prepare large random data that is difficult to be compressed and is
  2961. // expected to have large size even when compressed
  2962. std::random_device seed_gen;
  2963. std::mt19937 random(seed_gen());
  2964. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2965. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2966. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2967. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2968. // compress data over 4GiB
  2969. std::string compressed_data;
  2970. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2971. httplib::detail::gzip_compressor compressor;
  2972. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2973. data.size() * sizeof(std::uint32_t), true,
  2974. [&](const char *data, size_t size) {
  2975. compressed_data.insert(
  2976. compressed_data.size(), data, size);
  2977. return true;
  2978. });
  2979. ASSERT_TRUE(result);
  2980. // FIXME: compressed data size is expected to be greater than 4GiB,
  2981. // but there is no guarantee
  2982. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2983. // decompress data over 4GiB
  2984. std::string decompressed_data;
  2985. decompressed_data.reserve(data_size);
  2986. httplib::detail::gzip_decompressor decompressor;
  2987. result = decompressor.decompress(
  2988. compressed_data.data(), compressed_data.size(),
  2989. [&](const char *data, size_t size) {
  2990. decompressed_data.insert(decompressed_data.size(), data, size);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(result);
  2994. // compare
  2995. ASSERT_EQ(data_size, decompressed_data.size());
  2996. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2997. 0);
  2998. }
  2999. #endif
  3000. #endif
  3001. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3002. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3003. Headers headers;
  3004. headers.emplace("Accept-Encoding", "br");
  3005. auto res = cli_.Get("/streamed-chunked", headers);
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(200, res->status);
  3008. EXPECT_EQ(std::string("123456789"), res->body);
  3009. }
  3010. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3011. Headers headers;
  3012. headers.emplace("Accept-Encoding", "br");
  3013. auto res = cli_.Get("/streamed-chunked2", headers);
  3014. ASSERT_TRUE(res);
  3015. EXPECT_EQ(200, res->status);
  3016. EXPECT_EQ(std::string("123456789"), res->body);
  3017. }
  3018. #endif
  3019. TEST_F(ServerTest, Patch) {
  3020. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3021. ASSERT_TRUE(res);
  3022. EXPECT_EQ(200, res->status);
  3023. EXPECT_EQ("PATCH", res->body);
  3024. }
  3025. TEST_F(ServerTest, Delete) {
  3026. auto res = cli_.Delete("/delete");
  3027. ASSERT_TRUE(res);
  3028. EXPECT_EQ(200, res->status);
  3029. EXPECT_EQ("DELETE", res->body);
  3030. }
  3031. TEST_F(ServerTest, DeleteContentReceiver) {
  3032. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3033. ASSERT_TRUE(res);
  3034. EXPECT_EQ(200, res->status);
  3035. EXPECT_EQ("content", res->body);
  3036. }
  3037. TEST_F(ServerTest, Options) {
  3038. auto res = cli_.Options("*");
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(200, res->status);
  3041. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3042. EXPECT_TRUE(res->body.empty());
  3043. }
  3044. TEST_F(ServerTest, URL) {
  3045. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3046. ASSERT_TRUE(res);
  3047. EXPECT_EQ(200, res->status);
  3048. }
  3049. TEST_F(ServerTest, ArrayParam) {
  3050. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3051. ASSERT_TRUE(res);
  3052. EXPECT_EQ(200, res->status);
  3053. }
  3054. TEST_F(ServerTest, NoMultipleHeaders) {
  3055. Headers headers = {{"Content-Length", "5"}};
  3056. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3057. "text/plain");
  3058. ASSERT_TRUE(res);
  3059. EXPECT_EQ(200, res->status);
  3060. }
  3061. TEST_F(ServerTest, PostContentReceiver) {
  3062. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3063. ASSERT_TRUE(res);
  3064. ASSERT_EQ(200, res->status);
  3065. ASSERT_EQ("content", res->body);
  3066. }
  3067. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3068. MultipartFormDataItems items = {
  3069. {"text1", "text default", "", ""},
  3070. {"text2", "aωb", "", ""},
  3071. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3072. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3073. {"file3", "", "", "application/octet-stream"},
  3074. };
  3075. auto res = cli_.Post("/content_receiver", items);
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(200, res->status);
  3078. }
  3079. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3080. MultipartFormDataItems items = {
  3081. {"text1", "text default", "", ""},
  3082. {"text2", "aωb", "", ""},
  3083. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3084. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3085. {"file3", "", "", "application/octet-stream"},
  3086. };
  3087. auto boundary = std::string("+++++");
  3088. std::string body;
  3089. for (const auto &item : items) {
  3090. body += "--" + boundary + "\r\n";
  3091. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3092. if (!item.filename.empty()) {
  3093. body += "; filename=\"" + item.filename + "\"";
  3094. }
  3095. body += "\r\n";
  3096. if (!item.content_type.empty()) {
  3097. body += "Content-Type: " + item.content_type + "\r\n";
  3098. }
  3099. body += "\r\n";
  3100. body += item.content + "\r\n";
  3101. }
  3102. body += "--" + boundary + "--\r\n";
  3103. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3104. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3105. ASSERT_TRUE(res);
  3106. EXPECT_EQ(200, res->status);
  3107. }
  3108. TEST_F(ServerTest, PostContentReceiverGzip) {
  3109. cli_.set_compress(true);
  3110. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3111. ASSERT_TRUE(res);
  3112. ASSERT_EQ(200, res->status);
  3113. ASSERT_EQ("content", res->body);
  3114. }
  3115. TEST_F(ServerTest, PutContentReceiver) {
  3116. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3117. ASSERT_TRUE(res);
  3118. ASSERT_EQ(200, res->status);
  3119. ASSERT_EQ("content", res->body);
  3120. }
  3121. TEST_F(ServerTest, PatchContentReceiver) {
  3122. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(200, res->status);
  3125. ASSERT_EQ("content", res->body);
  3126. }
  3127. TEST_F(ServerTest, PostQueryStringAndBody) {
  3128. auto res =
  3129. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(200, res->status);
  3132. }
  3133. TEST_F(ServerTest, HTTP2Magic) {
  3134. Request req;
  3135. req.method = "PRI";
  3136. req.path = "*";
  3137. req.body = "SM";
  3138. auto res = std::make_shared<Response>();
  3139. auto error = Error::Success;
  3140. auto ret = cli_.send(req, *res, error);
  3141. ASSERT_TRUE(ret);
  3142. EXPECT_EQ(400, res->status);
  3143. }
  3144. TEST_F(ServerTest, KeepAlive) {
  3145. auto res = cli_.Get("/hi");
  3146. ASSERT_TRUE(res);
  3147. EXPECT_EQ(200, res->status);
  3148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3149. EXPECT_EQ("Hello World!", res->body);
  3150. res = cli_.Get("/hi");
  3151. ASSERT_TRUE(res);
  3152. EXPECT_EQ(200, res->status);
  3153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3154. EXPECT_EQ("Hello World!", res->body);
  3155. res = cli_.Get("/hi");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(200, res->status);
  3158. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("Hello World!", res->body);
  3160. res = cli_.Get("/not-exist");
  3161. ASSERT_TRUE(res);
  3162. EXPECT_EQ(404, res->status);
  3163. res = cli_.Post("/empty", "", "text/plain");
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ(200, res->status);
  3166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. EXPECT_EQ("empty", res->body);
  3168. EXPECT_EQ("close", res->get_header_value("Connection"));
  3169. res = cli_.Post(
  3170. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3171. "text/plain");
  3172. ASSERT_TRUE(res);
  3173. EXPECT_EQ(200, res->status);
  3174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3175. EXPECT_EQ("empty", res->body);
  3176. cli_.set_keep_alive(false);
  3177. res = cli_.Get("/last-request");
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ(200, res->status);
  3180. EXPECT_EQ("close", res->get_header_value("Connection"));
  3181. }
  3182. TEST_F(ServerTest, TooManyRedirect) {
  3183. cli_.set_follow_location(true);
  3184. auto res = cli_.Get("/redirect/0");
  3185. ASSERT_TRUE(!res);
  3186. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3187. }
  3188. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3189. TEST_F(ServerTest, Gzip) {
  3190. Headers headers;
  3191. headers.emplace("Accept-Encoding", "gzip, deflate");
  3192. auto res = cli_.Get("/compress", headers);
  3193. ASSERT_TRUE(res);
  3194. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3195. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3196. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3197. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3198. "7890123456789012345678901234567890",
  3199. res->body);
  3200. EXPECT_EQ(200, res->status);
  3201. }
  3202. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3203. auto res = cli_.Get("/compress");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3207. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3208. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3209. "7890123456789012345678901234567890",
  3210. res->body);
  3211. EXPECT_EQ(200, res->status);
  3212. }
  3213. TEST_F(ServerTest, GzipWithContentReceiver) {
  3214. Headers headers;
  3215. headers.emplace("Accept-Encoding", "gzip, deflate");
  3216. std::string body;
  3217. auto res = cli_.Get("/compress", headers,
  3218. [&](const char *data, uint64_t data_length) {
  3219. EXPECT_EQ(100U, data_length);
  3220. body.append(data, data_length);
  3221. return true;
  3222. });
  3223. ASSERT_TRUE(res);
  3224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3226. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3228. "7890123456789012345678901234567890",
  3229. body);
  3230. EXPECT_EQ(200, res->status);
  3231. }
  3232. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3233. Headers headers;
  3234. headers.emplace("Accept-Encoding", "gzip, deflate");
  3235. cli_.set_decompress(false);
  3236. auto res = cli_.Get("/compress", headers);
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3239. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3240. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3241. EXPECT_EQ(33U, res->body.size());
  3242. EXPECT_EQ(200, res->status);
  3243. }
  3244. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3245. std::string body;
  3246. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3247. EXPECT_EQ(100U, data_length);
  3248. body.append(data, data_length);
  3249. return true;
  3250. });
  3251. ASSERT_TRUE(res);
  3252. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3253. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3254. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3255. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3256. "7890123456789012345678901234567890",
  3257. body);
  3258. EXPECT_EQ(200, res->status);
  3259. }
  3260. TEST_F(ServerTest, NoGzip) {
  3261. Headers headers;
  3262. headers.emplace("Accept-Encoding", "gzip, deflate");
  3263. auto res = cli_.Get("/nocompress", headers);
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3266. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3267. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3269. "7890123456789012345678901234567890",
  3270. res->body);
  3271. EXPECT_EQ(200, res->status);
  3272. }
  3273. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3274. Headers headers;
  3275. headers.emplace("Accept-Encoding", "gzip, deflate");
  3276. std::string body;
  3277. auto res = cli_.Get("/nocompress", headers,
  3278. [&](const char *data, uint64_t data_length) {
  3279. EXPECT_EQ(100U, data_length);
  3280. body.append(data, data_length);
  3281. return true;
  3282. });
  3283. ASSERT_TRUE(res);
  3284. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3285. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3286. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3287. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3288. "7890123456789012345678901234567890",
  3289. body);
  3290. EXPECT_EQ(200, res->status);
  3291. }
  3292. TEST_F(ServerTest, MultipartFormDataGzip) {
  3293. MultipartFormDataItems items = {
  3294. {"key1", "test", "", ""},
  3295. {"key2", "--abcdefg123", "", ""},
  3296. };
  3297. cli_.set_compress(true);
  3298. auto res = cli_.Post("/compress-multipart", items);
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(200, res->status);
  3301. }
  3302. #endif
  3303. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3304. TEST_F(ServerTest, Brotli) {
  3305. Headers headers;
  3306. headers.emplace("Accept-Encoding", "br");
  3307. auto res = cli_.Get("/compress", headers);
  3308. ASSERT_TRUE(res);
  3309. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3311. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3312. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3313. "7890123456789012345678901234567890",
  3314. res->body);
  3315. EXPECT_EQ(200, res->status);
  3316. }
  3317. #endif
  3318. // Sends a raw request to a server listening at HOST:PORT.
  3319. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3320. std::string *resp = nullptr) {
  3321. auto error = Error::Success;
  3322. auto client_sock = detail::create_client_socket(
  3323. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3324. /*connection_timeout_sec=*/5, 0,
  3325. /*read_timeout_sec=*/5, 0,
  3326. /*write_timeout_sec=*/5, 0, std::string(), error);
  3327. if (client_sock == INVALID_SOCKET) { return false; }
  3328. auto ret = detail::process_client_socket(
  3329. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3330. if (req.size() !=
  3331. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3332. return false;
  3333. }
  3334. char buf[512];
  3335. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3336. while (line_reader.getline()) {
  3337. if (resp) { *resp += line_reader.ptr(); }
  3338. }
  3339. return true;
  3340. });
  3341. detail::close_socket(client_sock);
  3342. return ret;
  3343. }
  3344. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3345. Server svr;
  3346. std::string header_value;
  3347. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3348. header_value = req.get_header_value("foo");
  3349. res.set_content("ok", "text/plain");
  3350. });
  3351. thread t = thread([&] { svr.listen(HOST, PORT); });
  3352. auto se = detail::scope_exit([&] {
  3353. svr.stop();
  3354. t.join();
  3355. ASSERT_FALSE(svr.is_running());
  3356. });
  3357. svr.wait_until_ready();
  3358. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3359. // like characters are not treated the same - use vertical tab and escape.
  3360. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3361. "foo: \t \v bar \x1B\t \r\n"
  3362. "Connection: close\r\n"
  3363. "\r\n";
  3364. ASSERT_TRUE(send_request(5, req));
  3365. EXPECT_EQ(header_value, "\v bar \x1B");
  3366. }
  3367. // Sends a raw request and verifies that there isn't a crash or exception.
  3368. static void test_raw_request(const std::string &req,
  3369. std::string *out = nullptr) {
  3370. Server svr;
  3371. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3372. res.set_content("ok", "text/plain");
  3373. });
  3374. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3375. res.set_content("ok", "text/plain");
  3376. });
  3377. // Server read timeout must be longer than the client read timeout for the
  3378. // bug to reproduce, probably to force the server to process a request
  3379. // without a trailing blank line.
  3380. const time_t client_read_timeout_sec = 1;
  3381. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3382. bool listen_thread_ok = false;
  3383. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. t.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. EXPECT_TRUE(listen_thread_ok);
  3389. });
  3390. svr.wait_until_ready();
  3391. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3392. }
  3393. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3394. // A certain header line causes an exception if the header property is parsed
  3395. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3396. test_raw_request(
  3397. "GET /hi HTTP/1.1\r\n"
  3398. " : "
  3399. " "
  3400. " ");
  3401. }
  3402. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3403. // A certain header line causes an exception if the header property *name* is
  3404. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3405. // greedy matcher and requires backtracking when there are a lot of ":"
  3406. // characters.
  3407. // This occurs with libc++ but not libstdc++.
  3408. test_raw_request(
  3409. "GET /hi HTTP/1.1\r\n"
  3410. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3411. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3412. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3413. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3414. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3415. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3416. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3417. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3418. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3419. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3420. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3421. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3422. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3423. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3424. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3425. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3426. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3427. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3428. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3429. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3430. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3431. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3432. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3433. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3434. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3435. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3436. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3437. "&&&%%%");
  3438. }
  3439. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3440. // Make sure this doesn't crash the server.
  3441. // In a previous version of the header line regex, the "\r" rendered the line
  3442. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3443. // a new position where the leading white space ended and the field value
  3444. // began.
  3445. // The crash occurs with libc++ but not libstdc++.
  3446. test_raw_request("GET /hi HTTP/1.1\r\n"
  3447. "a:" +
  3448. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3449. "\r\n"
  3450. "\r\n");
  3451. }
  3452. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3453. std::string out;
  3454. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3455. "Content-Type: text/plain\r\n"
  3456. "Transfer-Encoding: chunked\r\n"
  3457. "\r\n"
  3458. "nothex\r\n",
  3459. &out);
  3460. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3461. }
  3462. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3463. std::string out;
  3464. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3465. "Content-Type: text/plain\r\n"
  3466. "Transfer-Encoding: chunked\r\n"
  3467. "\r\n"
  3468. "3\r\n"
  3469. "xyz\r\n"
  3470. "NaN\r\n",
  3471. &out);
  3472. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3473. }
  3474. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3475. std::string out;
  3476. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3477. "Content-Type: text/plain\r\n"
  3478. "Transfer-Encoding: chunked\r\n"
  3479. "\r\n"
  3480. // Length is too large for 64 bits.
  3481. "1ffffffffffffffff\r\n"
  3482. "xyz\r\n",
  3483. &out);
  3484. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3485. }
  3486. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3487. test_raw_request("GET /hi HTTP/1.1\r\n"
  3488. "Content-Type: text/plain\r\n\r");
  3489. }
  3490. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3491. std::string out;
  3492. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3493. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3494. }
  3495. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3496. Server svr;
  3497. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3498. res.set_header("Cache-Control", "no-cache");
  3499. res.set_chunked_content_provider(
  3500. "text/event-stream", [](size_t offset, DataSink &sink) {
  3501. std::string s = "data:";
  3502. s += std::to_string(offset);
  3503. s += "\n\n";
  3504. auto ret = sink.write(s.data(), s.size());
  3505. EXPECT_TRUE(ret);
  3506. std::this_thread::sleep_for(std::chrono::seconds(1));
  3507. return true;
  3508. });
  3509. });
  3510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3511. svr.wait_until_ready();
  3512. Client client(HOST, PORT);
  3513. const Headers headers = {{"Accept", "text/event-stream"}};
  3514. auto get_thread = std::thread([&client, &headers]() {
  3515. auto res = client.Get(
  3516. "/events", headers,
  3517. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3518. });
  3519. auto se = detail::scope_exit([&] {
  3520. svr.stop();
  3521. get_thread.join();
  3522. listen_thread.join();
  3523. ASSERT_FALSE(svr.is_running());
  3524. });
  3525. // Give GET time to get a few messages.
  3526. std::this_thread::sleep_for(std::chrono::seconds(2));
  3527. }
  3528. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3529. httplib::Server svr;
  3530. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3531. httplib::Response &res) { res.status = 200; });
  3532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3533. svr.wait_until_ready();
  3534. Client cli(HOST, PORT);
  3535. auto res = cli.Post("/hi", "data", "text/plain");
  3536. ASSERT_TRUE(res);
  3537. EXPECT_EQ(200, res->status);
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. res = cli.Post("/hi", "data", "text/plain");
  3542. ASSERT_FALSE(res);
  3543. }
  3544. TEST(ServerStopTest, ListenFailure) {
  3545. Server svr;
  3546. auto t = thread([&]() {
  3547. auto ret = svr.listen("????", PORT);
  3548. EXPECT_FALSE(ret);
  3549. });
  3550. svr.wait_until_ready();
  3551. svr.stop();
  3552. t.join();
  3553. }
  3554. TEST(StreamingTest, NoContentLengthStreaming) {
  3555. Server svr;
  3556. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3557. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3558. if (offset < 6) {
  3559. sink.os << (offset < 3 ? "a" : "b");
  3560. } else {
  3561. sink.done();
  3562. }
  3563. return true;
  3564. });
  3565. });
  3566. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3567. auto listen_se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. listen_thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client client(HOST, PORT);
  3574. auto get_thread = std::thread([&client]() {
  3575. std::string s;
  3576. auto res =
  3577. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3578. s += std::string(data, len);
  3579. return true;
  3580. });
  3581. EXPECT_EQ("aaabbb", s);
  3582. });
  3583. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3584. // Give GET time to get a few messages.
  3585. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3586. }
  3587. TEST(MountTest, Unmount) {
  3588. Server svr;
  3589. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3590. auto se = detail::scope_exit([&] {
  3591. svr.stop();
  3592. listen_thread.join();
  3593. ASSERT_FALSE(svr.is_running());
  3594. });
  3595. svr.wait_until_ready();
  3596. Client cli("localhost", PORT);
  3597. svr.set_mount_point("/mount2", "./www2");
  3598. auto res = cli.Get("/");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(404, res->status);
  3601. res = cli.Get("/mount2/dir/test.html");
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(200, res->status);
  3604. svr.set_mount_point("/", "./www");
  3605. res = cli.Get("/dir/");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(200, res->status);
  3608. svr.remove_mount_point("/");
  3609. res = cli.Get("/dir/");
  3610. ASSERT_TRUE(res);
  3611. EXPECT_EQ(404, res->status);
  3612. svr.remove_mount_point("/mount2");
  3613. res = cli.Get("/mount2/dir/test.html");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(404, res->status);
  3616. }
  3617. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3618. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3619. Server svr;
  3620. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3621. throw std::runtime_error("exception...");
  3622. });
  3623. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3624. throw std::runtime_error("exception\r\n...");
  3625. });
  3626. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. listen_thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. Client cli("localhost", PORT);
  3634. {
  3635. auto res = cli.Get("/exception");
  3636. ASSERT_TRUE(res);
  3637. EXPECT_EQ(500, res->status);
  3638. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3639. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3640. }
  3641. {
  3642. auto res = cli.Get("/unknown");
  3643. ASSERT_TRUE(res);
  3644. EXPECT_EQ(500, res->status);
  3645. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3646. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3647. }
  3648. }
  3649. #endif
  3650. TEST(KeepAliveTest, ReadTimeout) {
  3651. Server svr;
  3652. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3653. std::this_thread::sleep_for(std::chrono::seconds(2));
  3654. res.set_content("a", "text/plain");
  3655. });
  3656. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3657. res.set_content("b", "text/plain");
  3658. });
  3659. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. listen_thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. Client cli("localhost", PORT);
  3667. cli.set_keep_alive(true);
  3668. cli.set_read_timeout(std::chrono::seconds(1));
  3669. auto resa = cli.Get("/a");
  3670. ASSERT_FALSE(resa);
  3671. EXPECT_EQ(Error::Read, resa.error());
  3672. auto resb = cli.Get("/b");
  3673. ASSERT_TRUE(resb);
  3674. EXPECT_EQ(200, resb->status);
  3675. EXPECT_EQ("b", resb->body);
  3676. }
  3677. TEST(KeepAliveTest, Issue1041) {
  3678. Server svr;
  3679. svr.set_keep_alive_timeout(3);
  3680. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3681. res.set_content("Hello World!", "text/plain");
  3682. });
  3683. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3684. auto se = detail::scope_exit([&] {
  3685. svr.stop();
  3686. listen_thread.join();
  3687. ASSERT_FALSE(svr.is_running());
  3688. });
  3689. svr.wait_until_ready();
  3690. Client cli(HOST, PORT);
  3691. cli.set_keep_alive(true);
  3692. auto result = cli.Get("/hi");
  3693. ASSERT_TRUE(result);
  3694. EXPECT_EQ(200, result->status);
  3695. std::this_thread::sleep_for(std::chrono::seconds(5));
  3696. result = cli.Get("/hi");
  3697. ASSERT_TRUE(result);
  3698. EXPECT_EQ(200, result->status);
  3699. }
  3700. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3701. TEST(KeepAliveTest, SSLClientReconnection) {
  3702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3703. ASSERT_TRUE(svr.is_valid());
  3704. svr.set_keep_alive_timeout(1);
  3705. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3706. res.set_content("Hello World!", "text/plain");
  3707. });
  3708. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3709. auto se = detail::scope_exit([&] {
  3710. svr.stop();
  3711. listen_thread.join();
  3712. ASSERT_FALSE(svr.is_running());
  3713. });
  3714. svr.wait_until_ready();
  3715. SSLClient cli(HOST, PORT);
  3716. cli.enable_server_certificate_verification(false);
  3717. cli.set_keep_alive(true);
  3718. auto result = cli.Get("/hi");
  3719. ASSERT_TRUE(result);
  3720. EXPECT_EQ(200, result->status);
  3721. result = cli.Get("/hi");
  3722. ASSERT_TRUE(result);
  3723. EXPECT_EQ(200, result->status);
  3724. std::this_thread::sleep_for(std::chrono::seconds(2));
  3725. // Recoonect
  3726. result = cli.Get("/hi");
  3727. ASSERT_TRUE(result);
  3728. EXPECT_EQ(200, result->status);
  3729. result = cli.Get("/hi");
  3730. ASSERT_TRUE(result);
  3731. EXPECT_EQ(200, result->status);
  3732. }
  3733. #endif
  3734. TEST(ClientProblemDetectionTest, ContentProvider) {
  3735. Server svr;
  3736. size_t content_length = 1024 * 1024;
  3737. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3738. res.set_content_provider(
  3739. content_length, "text/plain",
  3740. [&](size_t offset, size_t length, DataSink &sink) {
  3741. auto out_len = std::min(length, static_cast<size_t>(1024));
  3742. std::string out(out_len, '@');
  3743. sink.write(out.data(), out_len);
  3744. return offset < 4096;
  3745. },
  3746. [](bool success) { ASSERT_FALSE(success); });
  3747. });
  3748. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3749. res.set_content_provider(
  3750. 0, "text/plain",
  3751. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3752. EXPECT_TRUE(false);
  3753. return true;
  3754. },
  3755. [](bool success) { ASSERT_FALSE(success); });
  3756. });
  3757. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3758. auto se = detail::scope_exit([&] {
  3759. svr.stop();
  3760. listen_thread.join();
  3761. ASSERT_FALSE(svr.is_running());
  3762. });
  3763. svr.wait_until_ready();
  3764. Client cli("localhost", PORT);
  3765. {
  3766. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3767. size_t /*data_length*/) { return false; });
  3768. ASSERT_FALSE(res);
  3769. }
  3770. {
  3771. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3772. size_t /*data_length*/) { return false; });
  3773. ASSERT_TRUE(res);
  3774. }
  3775. }
  3776. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3777. Server svr;
  3778. svr.set_error_handler([](Request const &, Response &res) -> void {
  3779. res.set_chunked_content_provider(
  3780. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3781. sink.os << "hello";
  3782. sink.os << "world";
  3783. sink.done();
  3784. return true;
  3785. });
  3786. });
  3787. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3788. auto se = detail::scope_exit([&] {
  3789. svr.stop();
  3790. listen_thread.join();
  3791. ASSERT_FALSE(svr.is_running());
  3792. });
  3793. svr.wait_until_ready();
  3794. Client cli("localhost", PORT);
  3795. auto res = cli.Get("/");
  3796. ASSERT_TRUE(res);
  3797. EXPECT_EQ(404, res->status);
  3798. EXPECT_EQ("helloworld", res->body);
  3799. }
  3800. TEST(LongPollingTest, ClientCloseDetection) {
  3801. Server svr;
  3802. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  3803. res.set_chunked_content_provider(
  3804. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3805. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  3806. sink.os << "hello";
  3807. auto count = 10;
  3808. while (count > 0 && sink.is_writable()) {
  3809. this_thread::sleep_for(chrono::milliseconds(10));
  3810. }
  3811. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  3812. return true;
  3813. });
  3814. });
  3815. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. listen_thread.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. svr.wait_until_ready();
  3822. Client cli("localhost", PORT);
  3823. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  3824. EXPECT_EQ("hello", string(data, data_length));
  3825. return false; // close the socket immediately.
  3826. });
  3827. ASSERT_FALSE(res);
  3828. }
  3829. TEST(GetWithParametersTest, GetWithParameters) {
  3830. Server svr;
  3831. svr.Get("/", [&](const Request &req, Response &) {
  3832. EXPECT_EQ("world", req.get_param_value("hello"));
  3833. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3834. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3835. });
  3836. svr.Get("/params", [&](const Request &req, Response &) {
  3837. EXPECT_EQ("world", req.get_param_value("hello"));
  3838. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3839. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3840. });
  3841. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3842. EXPECT_EQ("resource-id", req.matches[1]);
  3843. EXPECT_EQ("foo", req.get_param_value("param1"));
  3844. EXPECT_EQ("bar", req.get_param_value("param2"));
  3845. });
  3846. svr.Get("/users/:id", [&](const Request &req, Response &) {
  3847. EXPECT_EQ("user-id", req.path_params.at("id"));
  3848. EXPECT_EQ("foo", req.get_param_value("param1"));
  3849. EXPECT_EQ("bar", req.get_param_value("param2"));
  3850. });
  3851. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3852. auto se = detail::scope_exit([&] {
  3853. svr.stop();
  3854. listen_thread.join();
  3855. ASSERT_FALSE(svr.is_running());
  3856. });
  3857. svr.wait_until_ready();
  3858. {
  3859. Client cli(HOST, PORT);
  3860. Params params;
  3861. params.emplace("hello", "world");
  3862. params.emplace("hello2", "world2");
  3863. params.emplace("hello3", "world3");
  3864. auto res = cli.Get("/", params, Headers{});
  3865. ASSERT_TRUE(res);
  3866. EXPECT_EQ(200, res->status);
  3867. }
  3868. {
  3869. Client cli(HOST, PORT);
  3870. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(200, res->status);
  3873. }
  3874. {
  3875. Client cli(HOST, PORT);
  3876. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3877. ASSERT_TRUE(res);
  3878. EXPECT_EQ(200, res->status);
  3879. }
  3880. {
  3881. Client cli(HOST, PORT);
  3882. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(200, res->status);
  3885. }
  3886. }
  3887. TEST(GetWithParametersTest, GetWithParameters2) {
  3888. Server svr;
  3889. svr.Get("/", [&](const Request &req, Response &res) {
  3890. auto text = req.get_param_value("hello");
  3891. res.set_content(text, "text/plain");
  3892. });
  3893. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3894. auto se = detail::scope_exit([&] {
  3895. svr.stop();
  3896. listen_thread.join();
  3897. ASSERT_FALSE(svr.is_running());
  3898. });
  3899. svr.wait_until_ready();
  3900. Client cli("localhost", PORT);
  3901. Params params;
  3902. params.emplace("hello", "world");
  3903. std::string body;
  3904. auto res = cli.Get("/", params, Headers{},
  3905. [&](const char *data, size_t data_length) {
  3906. body.append(data, data_length);
  3907. return true;
  3908. });
  3909. ASSERT_TRUE(res);
  3910. EXPECT_EQ(200, res->status);
  3911. EXPECT_EQ("world", body);
  3912. }
  3913. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3914. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  3915. auto host = "httpbin.org";
  3916. auto path = std::string{"/range/32"};
  3917. #else
  3918. auto host = "nghttp2.org";
  3919. auto path = std::string{"/httpbin/range/32"};
  3920. #endif
  3921. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3922. SSLClient cli(host);
  3923. #else
  3924. Client cli(host);
  3925. #endif
  3926. cli.set_default_headers({make_range_header({{1, 10}})});
  3927. cli.set_connection_timeout(5);
  3928. {
  3929. auto res = cli.Get(path);
  3930. ASSERT_TRUE(res);
  3931. EXPECT_EQ("bcdefghijk", res->body);
  3932. EXPECT_EQ(206, res->status);
  3933. }
  3934. {
  3935. auto res = cli.Get(path);
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ("bcdefghijk", res->body);
  3938. EXPECT_EQ(206, res->status);
  3939. }
  3940. }
  3941. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3942. Server svr;
  3943. svr.set_default_headers({{"Hello", "World"}});
  3944. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3945. res.set_content("ok", "text/plain");
  3946. });
  3947. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3948. auto se = detail::scope_exit([&] {
  3949. svr.stop();
  3950. listen_thread.join();
  3951. ASSERT_FALSE(svr.is_running());
  3952. });
  3953. svr.wait_until_ready();
  3954. Client cli("localhost", PORT);
  3955. auto res = cli.Get("/");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(200, res->status);
  3958. EXPECT_EQ("ok", res->body);
  3959. EXPECT_EQ("World", res->get_header_value("Hello"));
  3960. }
  3961. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3962. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3963. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3964. ASSERT_TRUE(svr.is_valid());
  3965. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3966. std::this_thread::sleep_for(std::chrono::seconds(2));
  3967. res.set_content("a", "text/plain");
  3968. });
  3969. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3970. res.set_content("b", "text/plain");
  3971. });
  3972. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3973. auto se = detail::scope_exit([&] {
  3974. svr.stop();
  3975. listen_thread.join();
  3976. ASSERT_FALSE(svr.is_running());
  3977. });
  3978. svr.wait_until_ready();
  3979. SSLClient cli("localhost", PORT);
  3980. cli.enable_server_certificate_verification(false);
  3981. cli.set_keep_alive(true);
  3982. cli.set_read_timeout(std::chrono::seconds(1));
  3983. auto resa = cli.Get("/a");
  3984. ASSERT_TRUE(!resa);
  3985. EXPECT_EQ(Error::Read, resa.error());
  3986. auto resb = cli.Get("/b");
  3987. ASSERT_TRUE(resb);
  3988. EXPECT_EQ(200, resb->status);
  3989. EXPECT_EQ("b", resb->body);
  3990. }
  3991. #endif
  3992. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3993. protected:
  3994. ServerTestWithAI_PASSIVE()
  3995. : cli_(HOST, PORT)
  3996. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3997. ,
  3998. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3999. #endif
  4000. {
  4001. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4002. cli_.enable_server_certificate_verification(false);
  4003. #endif
  4004. }
  4005. virtual void SetUp() {
  4006. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4007. res.set_content("Hello World!", "text/plain");
  4008. });
  4009. t_ = thread(
  4010. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4011. svr_.wait_until_ready();
  4012. }
  4013. virtual void TearDown() {
  4014. svr_.stop();
  4015. t_.join();
  4016. }
  4017. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4018. SSLClient cli_;
  4019. SSLServer svr_;
  4020. #else
  4021. Client cli_;
  4022. Server svr_;
  4023. #endif
  4024. thread t_;
  4025. };
  4026. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4027. auto res = cli_.Get("/hi");
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(200, res->status);
  4030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4031. EXPECT_EQ("Hello World!", res->body);
  4032. }
  4033. class ServerUpDownTest : public ::testing::Test {
  4034. protected:
  4035. ServerUpDownTest() : cli_(HOST, PORT) {}
  4036. virtual void SetUp() {
  4037. t_ = thread([&]() {
  4038. svr_.bind_to_any_port(HOST);
  4039. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4040. ASSERT_TRUE(svr_.listen_after_bind());
  4041. });
  4042. svr_.wait_until_ready();
  4043. }
  4044. virtual void TearDown() {
  4045. svr_.stop();
  4046. t_.join();
  4047. }
  4048. Client cli_;
  4049. Server svr_;
  4050. thread t_;
  4051. };
  4052. TEST_F(ServerUpDownTest, QuickStartStop) {
  4053. // Should not crash, especially when run with
  4054. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4055. }
  4056. class PayloadMaxLengthTest : public ::testing::Test {
  4057. protected:
  4058. PayloadMaxLengthTest()
  4059. : cli_(HOST, PORT)
  4060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4061. ,
  4062. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4063. #endif
  4064. {
  4065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4066. cli_.enable_server_certificate_verification(false);
  4067. #endif
  4068. }
  4069. virtual void SetUp() {
  4070. svr_.set_payload_max_length(8);
  4071. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4072. res.set_content("test", "text/plain");
  4073. });
  4074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4075. svr_.wait_until_ready();
  4076. }
  4077. virtual void TearDown() {
  4078. svr_.stop();
  4079. t_.join();
  4080. }
  4081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4082. SSLClient cli_;
  4083. SSLServer svr_;
  4084. #else
  4085. Client cli_;
  4086. Server svr_;
  4087. #endif
  4088. thread t_;
  4089. };
  4090. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4091. auto res = cli_.Post("/test", "123456789", "text/plain");
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(413, res->status);
  4094. res = cli_.Post("/test", "12345678", "text/plain");
  4095. ASSERT_TRUE(res);
  4096. EXPECT_EQ(200, res->status);
  4097. }
  4098. TEST(HostAndPortPropertiesTest, NoSSL) {
  4099. httplib::Client cli("www.google.com", 1234);
  4100. ASSERT_EQ("www.google.com", cli.host());
  4101. ASSERT_EQ(1234, cli.port());
  4102. }
  4103. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4104. httplib::Client cli("www.google.com:1234");
  4105. ASSERT_EQ("www.google.com", cli.host());
  4106. ASSERT_EQ(1234, cli.port());
  4107. }
  4108. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4109. TEST(HostAndPortPropertiesTest, SSL) {
  4110. httplib::SSLClient cli("www.google.com");
  4111. ASSERT_EQ("www.google.com", cli.host());
  4112. ASSERT_EQ(443, cli.port());
  4113. }
  4114. #endif
  4115. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4116. TEST(SSLClientTest, UpdateCAStore) {
  4117. httplib::SSLClient httplib_client("www.google.com");
  4118. auto ca_store_1 = X509_STORE_new();
  4119. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4120. nullptr);
  4121. httplib_client.set_ca_cert_store(ca_store_1);
  4122. auto ca_store_2 = X509_STORE_new();
  4123. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4124. nullptr);
  4125. httplib_client.set_ca_cert_store(ca_store_2);
  4126. }
  4127. TEST(SSLClientTest, ServerNameIndication_Online) {
  4128. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4129. auto host = "httpbin.org";
  4130. auto path = std::string{"/get"};
  4131. #else
  4132. auto host = "nghttp2.org";
  4133. auto path = std::string{"/httpbin/get"};
  4134. #endif
  4135. SSLClient cli(host, 443);
  4136. auto res = cli.Get(path);
  4137. ASSERT_TRUE(res);
  4138. ASSERT_EQ(200, res->status);
  4139. }
  4140. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4141. Client cli("https://google.com");
  4142. auto res = cli.Get("/");
  4143. ASSERT_TRUE(res);
  4144. ASSERT_EQ(301, res->status);
  4145. }
  4146. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4147. SSLClient cli("google.com");
  4148. cli.enable_server_certificate_verification(true);
  4149. cli.set_ca_cert_path("hello");
  4150. auto res = cli.Get("/");
  4151. ASSERT_TRUE(!res);
  4152. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4153. }
  4154. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4155. SSLClient cli("google.com");
  4156. cli.set_ca_cert_path(CA_CERT_FILE);
  4157. auto res = cli.Get("/");
  4158. ASSERT_TRUE(res);
  4159. ASSERT_EQ(301, res->status);
  4160. }
  4161. TEST(SSLClientTest, ServerCertificateVerification4) {
  4162. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4163. ASSERT_TRUE(svr.is_valid());
  4164. svr.Get("/test", [&](const Request &, Response &res) {
  4165. res.set_content("test", "text/plain");
  4166. svr.stop();
  4167. ASSERT_TRUE(true);
  4168. });
  4169. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4170. auto se = detail::scope_exit([&] {
  4171. t.join();
  4172. ASSERT_FALSE(svr.is_running());
  4173. });
  4174. svr.wait_until_ready();
  4175. SSLClient cli("127.0.0.1", PORT);
  4176. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4177. cli.enable_server_certificate_verification(true);
  4178. cli.set_connection_timeout(30);
  4179. auto res = cli.Get("/test");
  4180. ASSERT_TRUE(res);
  4181. ASSERT_EQ(200, res->status);
  4182. }
  4183. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4184. std::string cert;
  4185. detail::read_file(CA_CERT_FILE, cert);
  4186. SSLClient cli("google.com");
  4187. cli.load_ca_cert_store(cert.data(), cert.size());
  4188. const auto res = cli.Get("/");
  4189. ASSERT_TRUE(res);
  4190. ASSERT_EQ(301, res->status);
  4191. }
  4192. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4193. // clang-format off
  4194. static constexpr char cert[] =
  4195. "GlobalSign Root CA\n"
  4196. "==================\n"
  4197. "-----BEGIN CERTIFICATE-----\n"
  4198. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4199. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4200. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4201. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4202. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4203. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4204. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4205. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4206. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4207. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4208. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4209. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4210. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4211. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4212. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4213. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4214. "-----END CERTIFICATE-----\n";
  4215. // clang-format on
  4216. SSLClient cli("google.com");
  4217. cli.load_ca_cert_store(cert, sizeof(cert));
  4218. const auto res = cli.Get("/");
  4219. ASSERT_TRUE(res);
  4220. ASSERT_EQ(301, res->status);
  4221. }
  4222. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4223. SSLClient cli("www.youtube.com");
  4224. cli.set_ca_cert_path(CA_CERT_FILE);
  4225. cli.enable_server_certificate_verification(true);
  4226. cli.set_follow_location(true);
  4227. auto res = cli.Get("/");
  4228. ASSERT_TRUE(res);
  4229. ASSERT_EQ(200, res->status);
  4230. }
  4231. #if 0
  4232. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4233. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4234. ASSERT_TRUE(cli != nullptr);
  4235. cli->set_address_family(AF_INET6);
  4236. cli->set_interface("en0");
  4237. auto res = cli->Get("/get");
  4238. ASSERT_TRUE(res);
  4239. ASSERT_EQ(200, res->status);
  4240. }
  4241. #endif
  4242. TEST(SSLClientServerTest, ClientCertPresent) {
  4243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4244. CLIENT_CA_CERT_DIR);
  4245. ASSERT_TRUE(svr.is_valid());
  4246. svr.Get("/test", [&](const Request &req, Response &res) {
  4247. res.set_content("test", "text/plain");
  4248. svr.stop();
  4249. ASSERT_TRUE(true);
  4250. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4251. ASSERT_TRUE(peer_cert != nullptr);
  4252. auto subject_name = X509_get_subject_name(peer_cert);
  4253. ASSERT_TRUE(subject_name != nullptr);
  4254. std::string common_name;
  4255. {
  4256. char name[BUFSIZ];
  4257. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4258. name, sizeof(name));
  4259. common_name.assign(name, static_cast<size_t>(name_len));
  4260. }
  4261. EXPECT_EQ("Common Name", common_name);
  4262. X509_free(peer_cert);
  4263. });
  4264. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4265. auto se = detail::scope_exit([&] {
  4266. t.join();
  4267. ASSERT_FALSE(svr.is_running());
  4268. });
  4269. svr.wait_until_ready();
  4270. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4271. cli.enable_server_certificate_verification(false);
  4272. cli.set_connection_timeout(30);
  4273. auto res = cli.Get("/test");
  4274. ASSERT_TRUE(res);
  4275. ASSERT_EQ(200, res->status);
  4276. }
  4277. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4278. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4279. X509 *server_cert;
  4280. EVP_PKEY *server_private_key;
  4281. X509_STORE *client_ca_cert_store;
  4282. X509 *client_cert;
  4283. EVP_PKEY *client_private_key;
  4284. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4285. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4286. fclose(f);
  4287. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4288. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4289. fclose(f);
  4290. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4291. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4292. client_ca_cert_store = X509_STORE_new();
  4293. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4294. X509_free(client_cert);
  4295. fclose(f);
  4296. f = fopen(CLIENT_CERT_FILE, "r+");
  4297. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4298. fclose(f);
  4299. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4300. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4301. fclose(f);
  4302. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4303. ASSERT_TRUE(svr.is_valid());
  4304. svr.Get("/test", [&](const Request &req, Response &res) {
  4305. res.set_content("test", "text/plain");
  4306. svr.stop();
  4307. ASSERT_TRUE(true);
  4308. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4309. ASSERT_TRUE(peer_cert != nullptr);
  4310. auto subject_name = X509_get_subject_name(peer_cert);
  4311. ASSERT_TRUE(subject_name != nullptr);
  4312. std::string common_name;
  4313. {
  4314. char name[BUFSIZ];
  4315. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4316. name, sizeof(name));
  4317. common_name.assign(name, static_cast<size_t>(name_len));
  4318. }
  4319. EXPECT_EQ("Common Name", common_name);
  4320. X509_free(peer_cert);
  4321. });
  4322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4323. auto se = detail::scope_exit([&] {
  4324. t.join();
  4325. ASSERT_FALSE(svr.is_running());
  4326. });
  4327. svr.wait_until_ready();
  4328. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4329. cli.enable_server_certificate_verification(false);
  4330. cli.set_connection_timeout(30);
  4331. auto res = cli.Get("/test");
  4332. ASSERT_TRUE(res);
  4333. ASSERT_EQ(200, res->status);
  4334. X509_free(server_cert);
  4335. EVP_PKEY_free(server_private_key);
  4336. X509_free(client_cert);
  4337. EVP_PKEY_free(client_private_key);
  4338. }
  4339. #endif
  4340. TEST(SSLClientServerTest, ClientCertMissing) {
  4341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4342. CLIENT_CA_CERT_DIR);
  4343. ASSERT_TRUE(svr.is_valid());
  4344. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4345. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4346. auto se = detail::scope_exit([&] {
  4347. svr.stop();
  4348. t.join();
  4349. ASSERT_FALSE(svr.is_running());
  4350. });
  4351. svr.wait_until_ready();
  4352. SSLClient cli(HOST, PORT);
  4353. auto res = cli.Get("/test");
  4354. cli.set_connection_timeout(30);
  4355. ASSERT_TRUE(!res);
  4356. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4357. }
  4358. TEST(SSLClientServerTest, TrustDirOptional) {
  4359. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4360. ASSERT_TRUE(svr.is_valid());
  4361. svr.Get("/test", [&](const Request &, Response &res) {
  4362. res.set_content("test", "text/plain");
  4363. svr.stop();
  4364. });
  4365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4366. auto se = detail::scope_exit([&] {
  4367. t.join();
  4368. ASSERT_FALSE(svr.is_running());
  4369. });
  4370. svr.wait_until_ready();
  4371. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4372. cli.enable_server_certificate_verification(false);
  4373. cli.set_connection_timeout(30);
  4374. auto res = cli.Get("/test");
  4375. ASSERT_TRUE(res);
  4376. ASSERT_EQ(200, res->status);
  4377. }
  4378. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4379. class NoListenSSLServer : public SSLServer {
  4380. public:
  4381. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4382. const char *client_ca_cert_file_path,
  4383. const char *client_ca_cert_dir_path = nullptr)
  4384. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4385. client_ca_cert_dir_path),
  4386. stop_(false) {}
  4387. std::atomic_bool stop_;
  4388. private:
  4389. bool process_and_close_socket(socket_t /*sock*/) override {
  4390. // Don't create SSL context
  4391. while (!stop_.load()) {
  4392. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4393. }
  4394. return true;
  4395. }
  4396. };
  4397. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4398. CLIENT_CA_CERT_FILE);
  4399. ASSERT_TRUE(svr.is_valid());
  4400. svr.Get("/test", [&](const Request &, Response &res) {
  4401. res.set_content("test", "text/plain");
  4402. });
  4403. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4404. auto se = detail::scope_exit([&] {
  4405. svr.stop_ = true;
  4406. svr.stop();
  4407. t.join();
  4408. ASSERT_FALSE(svr.is_running());
  4409. });
  4410. svr.wait_until_ready();
  4411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4412. cli.enable_server_certificate_verification(false);
  4413. cli.set_connection_timeout(1);
  4414. auto res = cli.Get("/test");
  4415. ASSERT_TRUE(!res);
  4416. EXPECT_EQ(Error::SSLConnection, res.error());
  4417. }
  4418. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4419. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4420. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4421. SSL_CTX_set_options(&ssl_ctx,
  4422. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4423. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4424. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4425. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4426. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4427. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4428. "ECDHE-DSS-AES128-SHA256:"
  4429. "ECDHE-RSA-AES256-SHA256:"
  4430. "ECDHE-DSS-AES256-SHA256:";
  4431. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4432. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4433. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4434. SSL_FILETYPE_PEM) != 1) {
  4435. return false;
  4436. }
  4437. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4438. CLIENT_CA_CERT_DIR);
  4439. SSL_CTX_set_verify(
  4440. &ssl_ctx,
  4441. SSL_VERIFY_PEER |
  4442. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4443. nullptr);
  4444. return true;
  4445. };
  4446. SSLServer svr(setup_ssl_ctx_callback);
  4447. ASSERT_TRUE(svr.is_valid());
  4448. svr.Get("/test", [&](const Request &req, Response &res) {
  4449. res.set_content("test", "text/plain");
  4450. svr.stop();
  4451. ASSERT_TRUE(true);
  4452. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4453. ASSERT_TRUE(peer_cert != nullptr);
  4454. auto subject_name = X509_get_subject_name(peer_cert);
  4455. ASSERT_TRUE(subject_name != nullptr);
  4456. std::string common_name;
  4457. {
  4458. char name[BUFSIZ];
  4459. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4460. name, sizeof(name));
  4461. common_name.assign(name, static_cast<size_t>(name_len));
  4462. }
  4463. EXPECT_EQ("Common Name", common_name);
  4464. X509_free(peer_cert);
  4465. });
  4466. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4467. auto se = detail::scope_exit([&] {
  4468. t.join();
  4469. ASSERT_FALSE(svr.is_running());
  4470. });
  4471. svr.wait_until_ready();
  4472. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4473. cli.enable_server_certificate_verification(false);
  4474. cli.set_connection_timeout(30);
  4475. auto res = cli.Get("/test");
  4476. ASSERT_TRUE(res);
  4477. ASSERT_EQ(200, res->status);
  4478. }
  4479. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4480. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4481. // prepare large data
  4482. std::random_device seed_gen;
  4483. std::mt19937 random(seed_gen());
  4484. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4485. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4486. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4487. // server
  4488. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4489. ASSERT_TRUE(svr.is_valid());
  4490. svr.Post("/binary", [&](const Request &req, Response &res) {
  4491. EXPECT_EQ(large_size_byte, req.body.size());
  4492. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4493. res.set_content(req.body, "application/octet-stream");
  4494. });
  4495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4496. auto se = detail::scope_exit([&] {
  4497. svr.stop();
  4498. listen_thread.join();
  4499. ASSERT_FALSE(svr.is_running());
  4500. });
  4501. svr.wait_until_ready();
  4502. // client POST
  4503. SSLClient cli("localhost", PORT);
  4504. cli.enable_server_certificate_verification(false);
  4505. cli.set_read_timeout(std::chrono::seconds(100));
  4506. cli.set_write_timeout(std::chrono::seconds(100));
  4507. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4508. large_size_byte, "application/octet-stream");
  4509. // compare
  4510. EXPECT_EQ(200, res->status);
  4511. EXPECT_EQ(large_size_byte, res->body.size());
  4512. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4513. }
  4514. #endif
  4515. #ifdef _WIN32
  4516. TEST(CleanupTest, WSACleanup) {
  4517. int ret = WSACleanup();
  4518. ASSERT_EQ(0, ret);
  4519. }
  4520. #endif
  4521. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4522. TEST(NoSSLSupport, SimpleInterface) {
  4523. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4524. }
  4525. #endif
  4526. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4527. TEST(InvalidScheme, SimpleInterface) {
  4528. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4529. }
  4530. #endif
  4531. TEST(NoScheme, SimpleInterface) {
  4532. Client cli("yahoo.com:80");
  4533. ASSERT_TRUE(cli.is_valid());
  4534. }
  4535. TEST(SendAPI, SimpleInterface_Online) {
  4536. Client cli("http://yahoo.com");
  4537. Request req;
  4538. req.method = "GET";
  4539. req.path = "/";
  4540. auto res = cli.send(req);
  4541. ASSERT_TRUE(res);
  4542. EXPECT_EQ(301, res->status);
  4543. }
  4544. TEST(ClientImplMethods, GetSocketTest) {
  4545. httplib::Server svr;
  4546. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4547. res.status = 200;
  4548. });
  4549. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4550. auto se = detail::scope_exit([&] {
  4551. svr.stop();
  4552. thread.join();
  4553. ASSERT_FALSE(svr.is_running());
  4554. });
  4555. svr.wait_until_ready();
  4556. {
  4557. httplib::Client cli("http://127.0.0.1:3333");
  4558. cli.set_keep_alive(true);
  4559. // Use the behavior of cpp-httplib of opening the connection
  4560. // only when the first request happens. If that changes,
  4561. // this test would be obsolete.
  4562. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4563. // This also implicitly tests the server. But other tests would fail much
  4564. // earlier than this one to be considered.
  4565. auto res = cli.Get("/");
  4566. ASSERT_TRUE(res);
  4567. EXPECT_EQ(200, res->status);
  4568. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4569. }
  4570. }
  4571. // Disabled due to out-of-memory problem on GitHub Actions
  4572. #ifdef _WIN64
  4573. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4574. // allocate content size larger than 2GB in memory
  4575. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4576. char *content = (char *)malloc(content_size);
  4577. ASSERT_TRUE(content);
  4578. Server svr;
  4579. svr.Get("/foo",
  4580. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  4581. res.set_content(content, content_size, "application/octet-stream");
  4582. });
  4583. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4584. auto se = detail::scope_exit([&] {
  4585. svr.stop();
  4586. listen_thread.join();
  4587. if (content) free(content);
  4588. ASSERT_FALSE(svr.is_running());
  4589. });
  4590. svr.wait_until_ready();
  4591. Client cli(HOST, PORT);
  4592. auto res = cli.Get("/foo");
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(200, res->status);
  4595. EXPECT_EQ(content_size, res->body.length());
  4596. }
  4597. #endif
  4598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4599. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4600. Client cli("http://yahoo.com");
  4601. auto res = cli.Get("/");
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(301, res->status);
  4604. cli.set_follow_location(true);
  4605. res = cli.Get("/");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(200, res->status);
  4608. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4609. }
  4610. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4611. Client cli("https://yahoo.com");
  4612. auto res = cli.Get("/");
  4613. ASSERT_TRUE(res);
  4614. EXPECT_EQ(301, res->status);
  4615. cli.set_follow_location(true);
  4616. res = cli.Get("/");
  4617. ASSERT_TRUE(res);
  4618. EXPECT_EQ(200, res->status);
  4619. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4620. }
  4621. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4622. Client cli("https://yahoo.com");
  4623. auto res = cli.Get("/");
  4624. ASSERT_TRUE(res);
  4625. ASSERT_FALSE(!res);
  4626. ASSERT_TRUE(res);
  4627. ASSERT_FALSE(res == nullptr);
  4628. ASSERT_TRUE(res != nullptr);
  4629. EXPECT_EQ(Error::Success, res.error());
  4630. EXPECT_EQ(301, res.value().status);
  4631. EXPECT_EQ(301, (*res).status);
  4632. EXPECT_EQ(301, res->status);
  4633. cli.set_follow_location(true);
  4634. res = cli.Get("/");
  4635. ASSERT_TRUE(res);
  4636. EXPECT_EQ(Error::Success, res.error());
  4637. EXPECT_EQ(200, res.value().status);
  4638. EXPECT_EQ(200, (*res).status);
  4639. EXPECT_EQ(200, res->status);
  4640. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4641. }
  4642. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4643. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4644. Client cli("https://cdnjs.cloudflare.com");
  4645. auto res =
  4646. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(200, res->status);
  4649. EXPECT_EQ(287630U, res->body.size());
  4650. EXPECT_EQ("application/javascript; charset=utf-8",
  4651. res->get_header_value("Content-Type"));
  4652. }
  4653. #endif
  4654. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4655. Client cli("https://nghttp2.org");
  4656. cli.set_follow_location(true);
  4657. auto res =
  4658. cli.Get("/httpbin/"
  4659. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4660. ASSERT_TRUE(res);
  4661. EXPECT_EQ(200, res->status);
  4662. }
  4663. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4664. Client cli("https://nghttp2.org");
  4665. cli.set_follow_location(true);
  4666. Params params;
  4667. params.emplace("url", "http://www.google.com");
  4668. params.emplace("status_code", "302");
  4669. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(200, res->status);
  4672. }
  4673. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4674. Client cli("https://nghttp2.org");
  4675. cli.set_follow_location(true);
  4676. Params params;
  4677. params.emplace("url", "http://www.google.com");
  4678. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(200, res->status);
  4681. }
  4682. TEST(HttpToHttpsRedirectTest, CertFile) {
  4683. Server svr;
  4684. ASSERT_TRUE(svr.is_valid());
  4685. svr.Get("/index", [&](const Request &, Response &res) {
  4686. res.set_redirect("https://127.0.0.1:1235/index");
  4687. svr.stop();
  4688. });
  4689. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4690. ASSERT_TRUE(ssl_svr.is_valid());
  4691. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4692. res.set_content("test", "text/plain");
  4693. ssl_svr.stop();
  4694. });
  4695. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4696. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4697. auto se = detail::scope_exit([&] {
  4698. t2.join();
  4699. t.join();
  4700. ASSERT_FALSE(svr.is_running());
  4701. });
  4702. svr.wait_until_ready();
  4703. ssl_svr.wait_until_ready();
  4704. Client cli("127.0.0.1", PORT);
  4705. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4706. cli.enable_server_certificate_verification(true);
  4707. cli.set_follow_location(true);
  4708. cli.set_connection_timeout(30);
  4709. auto res = cli.Get("/index");
  4710. ASSERT_TRUE(res);
  4711. ASSERT_EQ(200, res->status);
  4712. }
  4713. TEST(MultipartFormDataTest, LargeData) {
  4714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4715. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4716. const ContentReader &content_reader) {
  4717. if (req.is_multipart_form_data()) {
  4718. MultipartFormDataItems files;
  4719. content_reader(
  4720. [&](const MultipartFormData &file) {
  4721. files.push_back(file);
  4722. return true;
  4723. },
  4724. [&](const char *data, size_t data_length) {
  4725. files.back().content.append(data, data_length);
  4726. return true;
  4727. });
  4728. EXPECT_TRUE(std::string(files[0].name) == "document");
  4729. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4730. EXPECT_TRUE(files[0].filename == "2MB_data");
  4731. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4732. EXPECT_TRUE(files[1].name == "hello");
  4733. EXPECT_TRUE(files[1].content == "world");
  4734. EXPECT_TRUE(files[1].filename == "");
  4735. EXPECT_TRUE(files[1].content_type == "");
  4736. } else {
  4737. std::string body;
  4738. content_reader([&](const char *data, size_t data_length) {
  4739. body.append(data, data_length);
  4740. return true;
  4741. });
  4742. }
  4743. });
  4744. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4745. auto se = detail::scope_exit([&] {
  4746. svr.stop();
  4747. t.join();
  4748. ASSERT_FALSE(svr.is_running());
  4749. });
  4750. svr.wait_until_ready();
  4751. {
  4752. std::string data(1024 * 1024 * 2, '.');
  4753. std::stringstream buffer;
  4754. buffer << data;
  4755. Client cli("https://localhost:8080");
  4756. cli.enable_server_certificate_verification(false);
  4757. MultipartFormDataItems items{
  4758. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4759. {"hello", "world", "", ""},
  4760. };
  4761. auto res = cli.Post("/post", items);
  4762. ASSERT_TRUE(res);
  4763. ASSERT_EQ(200, res->status);
  4764. }
  4765. }
  4766. TEST(MultipartFormDataTest, DataProviderItems) {
  4767. std::random_device seed_gen;
  4768. std::mt19937 random(seed_gen());
  4769. std::string rand1;
  4770. rand1.resize(1000);
  4771. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4772. std::string rand2;
  4773. rand2.resize(3000);
  4774. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4776. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4777. const ContentReader &content_reader) {
  4778. ASSERT_FALSE(req.is_multipart_form_data());
  4779. std::string body;
  4780. content_reader([&](const char *data, size_t data_length) {
  4781. body.append(data, data_length);
  4782. return true;
  4783. });
  4784. EXPECT_EQ(body, "");
  4785. });
  4786. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4787. const ContentReader &content_reader) {
  4788. ASSERT_TRUE(req.is_multipart_form_data());
  4789. MultipartFormDataItems files;
  4790. content_reader(
  4791. [&](const MultipartFormData &file) {
  4792. files.push_back(file);
  4793. return true;
  4794. },
  4795. [&](const char *data, size_t data_length) {
  4796. files.back().content.append(data, data_length);
  4797. return true;
  4798. });
  4799. ASSERT_TRUE(files.size() == 2);
  4800. EXPECT_EQ(std::string(files[0].name), "name1");
  4801. EXPECT_EQ(files[0].content, "Testing123");
  4802. EXPECT_EQ(files[0].filename, "filename1");
  4803. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4804. EXPECT_EQ(files[1].name, "name2");
  4805. EXPECT_EQ(files[1].content, "Testing456");
  4806. EXPECT_EQ(files[1].filename, "");
  4807. EXPECT_EQ(files[1].content_type, "");
  4808. });
  4809. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4810. const ContentReader &content_reader) {
  4811. ASSERT_TRUE(req.is_multipart_form_data());
  4812. MultipartFormDataItems files;
  4813. content_reader(
  4814. [&](const MultipartFormData &file) {
  4815. files.push_back(file);
  4816. return true;
  4817. },
  4818. [&](const char *data, size_t data_length) {
  4819. files.back().content.append(data, data_length);
  4820. return true;
  4821. });
  4822. ASSERT_TRUE(files.size() == 2);
  4823. EXPECT_EQ(files[0].name, "name3");
  4824. EXPECT_EQ(files[0].content, rand1);
  4825. EXPECT_EQ(files[0].filename, "filename3");
  4826. EXPECT_EQ(files[0].content_type, "");
  4827. EXPECT_EQ(files[1].name, "name4");
  4828. EXPECT_EQ(files[1].content, rand2);
  4829. EXPECT_EQ(files[1].filename, "filename4");
  4830. EXPECT_EQ(files[1].content_type, "");
  4831. });
  4832. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4833. const ContentReader &content_reader) {
  4834. ASSERT_TRUE(req.is_multipart_form_data());
  4835. MultipartFormDataItems files;
  4836. content_reader(
  4837. [&](const MultipartFormData &file) {
  4838. files.push_back(file);
  4839. return true;
  4840. },
  4841. [&](const char *data, size_t data_length) {
  4842. files.back().content.append(data, data_length);
  4843. return true;
  4844. });
  4845. ASSERT_TRUE(files.size() == 4);
  4846. EXPECT_EQ(std::string(files[0].name), "name1");
  4847. EXPECT_EQ(files[0].content, "Testing123");
  4848. EXPECT_EQ(files[0].filename, "filename1");
  4849. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4850. EXPECT_EQ(files[1].name, "name2");
  4851. EXPECT_EQ(files[1].content, "Testing456");
  4852. EXPECT_EQ(files[1].filename, "");
  4853. EXPECT_EQ(files[1].content_type, "");
  4854. EXPECT_EQ(files[2].name, "name3");
  4855. EXPECT_EQ(files[2].content, rand1);
  4856. EXPECT_EQ(files[2].filename, "filename3");
  4857. EXPECT_EQ(files[2].content_type, "");
  4858. EXPECT_EQ(files[3].name, "name4");
  4859. EXPECT_EQ(files[3].content, rand2);
  4860. EXPECT_EQ(files[3].filename, "filename4");
  4861. EXPECT_EQ(files[3].content_type, "");
  4862. });
  4863. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4864. auto se = detail::scope_exit([&] {
  4865. svr.stop();
  4866. t.join();
  4867. ASSERT_FALSE(svr.is_running());
  4868. });
  4869. svr.wait_until_ready();
  4870. {
  4871. Client cli("https://localhost:8080");
  4872. cli.enable_server_certificate_verification(false);
  4873. MultipartFormDataItems items{
  4874. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4875. {"name2", "Testing456", "", ""}, // not a file
  4876. };
  4877. {
  4878. auto res = cli.Post("/post-none", {}, {}, {});
  4879. ASSERT_TRUE(res);
  4880. ASSERT_EQ(200, res->status);
  4881. }
  4882. MultipartFormDataProviderItems providers;
  4883. {
  4884. auto res =
  4885. cli.Post("/post-items", {}, items, providers); // empty providers
  4886. ASSERT_TRUE(res);
  4887. ASSERT_EQ(200, res->status);
  4888. }
  4889. providers.push_back({"name3",
  4890. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4891. // test the offset is given correctly at each step
  4892. if (!offset)
  4893. sink.os.write(rand1.data(), 30);
  4894. else if (offset == 30)
  4895. sink.os.write(rand1.data() + 30, 300);
  4896. else if (offset == 330)
  4897. sink.os.write(rand1.data() + 330, 670);
  4898. else if (offset == rand1.size())
  4899. sink.done();
  4900. return true;
  4901. },
  4902. "filename3",
  4903. {}});
  4904. providers.push_back({"name4",
  4905. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4906. // test the offset is given correctly at each step
  4907. if (!offset)
  4908. sink.os.write(rand2.data(), 2000);
  4909. else if (offset == 2000)
  4910. sink.os.write(rand2.data() + 2000, 1);
  4911. else if (offset == 2001)
  4912. sink.os.write(rand2.data() + 2001, 999);
  4913. else if (offset == rand2.size())
  4914. sink.done();
  4915. return true;
  4916. },
  4917. "filename4",
  4918. {}});
  4919. {
  4920. auto res = cli.Post("/post-providers", {}, {}, providers);
  4921. ASSERT_TRUE(res);
  4922. ASSERT_EQ(200, res->status);
  4923. }
  4924. {
  4925. auto res = cli.Post("/post-both", {}, items, providers);
  4926. ASSERT_TRUE(res);
  4927. ASSERT_EQ(200, res->status);
  4928. }
  4929. }
  4930. }
  4931. TEST(MultipartFormDataTest, BadHeader) {
  4932. Server svr;
  4933. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4934. res.set_content("ok", "text/plain");
  4935. });
  4936. thread t = thread([&] { svr.listen(HOST, PORT); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. t.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. const std::string body =
  4944. "This is the preamble. It is to be ignored, though it\r\n"
  4945. "is a handy place for composition agents to include an\r\n"
  4946. "explanatory note to non-MIME conformant readers.\r\n"
  4947. "\r\n"
  4948. "\r\n"
  4949. "--simple boundary\r\n"
  4950. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4951. ": BAD...\r\n"
  4952. "\r\n"
  4953. "value1\r\n"
  4954. "--simple boundary\r\n"
  4955. "Content-Disposition: form-data; name=\"field2\"; "
  4956. "filename=\"example.txt\"\r\n"
  4957. "\r\n"
  4958. "value2\r\n"
  4959. "--simple boundary--\r\n"
  4960. "This is the epilogue. It is also to be ignored.\r\n";
  4961. std::string content_type =
  4962. R"(multipart/form-data; boundary="simple boundary")";
  4963. Client cli(HOST, PORT);
  4964. auto res = cli.Post("/post", body, content_type.c_str());
  4965. ASSERT_TRUE(res);
  4966. EXPECT_EQ(400, res->status);
  4967. }
  4968. TEST(MultipartFormDataTest, WithPreamble) {
  4969. Server svr;
  4970. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4971. res.set_content("ok", "text/plain");
  4972. });
  4973. thread t = thread([&] { svr.listen(HOST, PORT); });
  4974. auto se = detail::scope_exit([&] {
  4975. svr.stop();
  4976. t.join();
  4977. ASSERT_FALSE(svr.is_running());
  4978. });
  4979. svr.wait_until_ready();
  4980. const std::string body =
  4981. "This is the preamble. It is to be ignored, though it\r\n"
  4982. "is a handy place for composition agents to include an\r\n"
  4983. "explanatory note to non-MIME conformant readers.\r\n"
  4984. "\r\n"
  4985. "\r\n"
  4986. "--simple boundary\r\n"
  4987. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4988. "\r\n"
  4989. "value1\r\n"
  4990. "--simple boundary\r\n"
  4991. "Content-Disposition: form-data; name=\"field2\"; "
  4992. "filename=\"example.txt\"\r\n"
  4993. "\r\n"
  4994. "value2\r\n"
  4995. "--simple boundary--\r\n"
  4996. "This is the epilogue. It is also to be ignored.\r\n";
  4997. std::string content_type =
  4998. R"(multipart/form-data; boundary="simple boundary")";
  4999. Client cli(HOST, PORT);
  5000. auto res = cli.Post("/post", body, content_type.c_str());
  5001. ASSERT_TRUE(res);
  5002. EXPECT_EQ(200, res->status);
  5003. }
  5004. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5006. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5007. const ContentReader &content_reader) {
  5008. if (req.is_multipart_form_data()) {
  5009. MultipartFormDataItems files;
  5010. content_reader(
  5011. [&](const MultipartFormData &file) {
  5012. files.push_back(file);
  5013. return true;
  5014. },
  5015. [&](const char *data, size_t data_length) {
  5016. files.back().content.append(data, data_length);
  5017. return true;
  5018. });
  5019. EXPECT_TRUE(std::string(files[0].name) == "document");
  5020. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5021. EXPECT_TRUE(files[0].filename == "2MB_data");
  5022. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5023. EXPECT_TRUE(files[1].name == "hello");
  5024. EXPECT_TRUE(files[1].content == "world");
  5025. EXPECT_TRUE(files[1].filename == "");
  5026. EXPECT_TRUE(files[1].content_type == "");
  5027. } else {
  5028. std::string body;
  5029. content_reader([&](const char *data, size_t data_length) {
  5030. body.append(data, data_length);
  5031. return true;
  5032. });
  5033. }
  5034. });
  5035. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. t.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. {
  5043. std::string data(1024 * 1024 * 2, '.');
  5044. std::stringstream buffer;
  5045. buffer << data;
  5046. Client cli("https://localhost:8080");
  5047. cli.enable_server_certificate_verification(false);
  5048. MultipartFormDataItems items{
  5049. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5050. {"hello", "world", "", ""},
  5051. };
  5052. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5053. ASSERT_TRUE(res);
  5054. ASSERT_EQ(200, res->status);
  5055. }
  5056. }
  5057. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5058. std::string data(1024 * 1024 * 2, '&');
  5059. std::stringstream buffer;
  5060. buffer << data;
  5061. Client cli("https://localhost:8080");
  5062. MultipartFormDataItems items{
  5063. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5064. {"hello", "world", "", ""},
  5065. };
  5066. for (const char &c : " \t\r\n") {
  5067. auto res =
  5068. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5069. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5070. ASSERT_FALSE(res);
  5071. }
  5072. }
  5073. TEST(MultipartFormDataTest, PutFormData) {
  5074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5075. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5076. const ContentReader &content_reader) {
  5077. if (req.is_multipart_form_data()) {
  5078. MultipartFormDataItems files;
  5079. content_reader(
  5080. [&](const MultipartFormData &file) {
  5081. files.push_back(file);
  5082. return true;
  5083. },
  5084. [&](const char *data, size_t data_length) {
  5085. files.back().content.append(data, data_length);
  5086. return true;
  5087. });
  5088. EXPECT_TRUE(std::string(files[0].name) == "document");
  5089. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5090. EXPECT_TRUE(files[0].filename == "2MB_data");
  5091. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5092. EXPECT_TRUE(files[1].name == "hello");
  5093. EXPECT_TRUE(files[1].content == "world");
  5094. EXPECT_TRUE(files[1].filename == "");
  5095. EXPECT_TRUE(files[1].content_type == "");
  5096. } else {
  5097. std::string body;
  5098. content_reader([&](const char *data, size_t data_length) {
  5099. body.append(data, data_length);
  5100. return true;
  5101. });
  5102. }
  5103. });
  5104. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5105. auto se = detail::scope_exit([&] {
  5106. svr.stop();
  5107. t.join();
  5108. ASSERT_FALSE(svr.is_running());
  5109. });
  5110. svr.wait_until_ready();
  5111. {
  5112. std::string data(1024 * 1024 * 2, '&');
  5113. std::stringstream buffer;
  5114. buffer << data;
  5115. Client cli("https://localhost:8080");
  5116. cli.enable_server_certificate_verification(false);
  5117. MultipartFormDataItems items{
  5118. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5119. {"hello", "world", "", ""},
  5120. };
  5121. auto res = cli.Put("/put", items);
  5122. ASSERT_TRUE(res);
  5123. ASSERT_EQ(200, res->status);
  5124. }
  5125. }
  5126. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5128. svr.Put("/put_customboundary",
  5129. [&](const Request &req, const Response & /*res*/,
  5130. const ContentReader &content_reader) {
  5131. if (req.is_multipart_form_data()) {
  5132. MultipartFormDataItems files;
  5133. content_reader(
  5134. [&](const MultipartFormData &file) {
  5135. files.push_back(file);
  5136. return true;
  5137. },
  5138. [&](const char *data, size_t data_length) {
  5139. files.back().content.append(data, data_length);
  5140. return true;
  5141. });
  5142. EXPECT_TRUE(std::string(files[0].name) == "document");
  5143. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5144. EXPECT_TRUE(files[0].filename == "2MB_data");
  5145. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5146. EXPECT_TRUE(files[1].name == "hello");
  5147. EXPECT_TRUE(files[1].content == "world");
  5148. EXPECT_TRUE(files[1].filename == "");
  5149. EXPECT_TRUE(files[1].content_type == "");
  5150. } else {
  5151. std::string body;
  5152. content_reader([&](const char *data, size_t data_length) {
  5153. body.append(data, data_length);
  5154. return true;
  5155. });
  5156. }
  5157. });
  5158. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5159. auto se = detail::scope_exit([&] {
  5160. svr.stop();
  5161. t.join();
  5162. ASSERT_FALSE(svr.is_running());
  5163. });
  5164. svr.wait_until_ready();
  5165. {
  5166. std::string data(1024 * 1024 * 2, '&');
  5167. std::stringstream buffer;
  5168. buffer << data;
  5169. Client cli("https://localhost:8080");
  5170. cli.enable_server_certificate_verification(false);
  5171. MultipartFormDataItems items{
  5172. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5173. {"hello", "world", "", ""},
  5174. };
  5175. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5176. ASSERT_TRUE(res);
  5177. ASSERT_EQ(200, res->status);
  5178. }
  5179. }
  5180. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5181. std::string data(1024 * 1024 * 2, '&');
  5182. std::stringstream buffer;
  5183. buffer << data;
  5184. Client cli("https://localhost:8080");
  5185. cli.enable_server_certificate_verification(false);
  5186. MultipartFormDataItems items{
  5187. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5188. {"hello", "world", "", ""},
  5189. };
  5190. for (const char &c : " \t\r\n") {
  5191. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5192. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5193. ASSERT_FALSE(res);
  5194. }
  5195. }
  5196. TEST(MultipartFormDataTest, AlternateFilename) {
  5197. auto handled = false;
  5198. Server svr;
  5199. svr.Post("/test", [&](const Request &req, Response &res) {
  5200. ASSERT_EQ(3u, req.files.size());
  5201. auto it = req.files.begin();
  5202. ASSERT_EQ("file1", it->second.name);
  5203. ASSERT_EQ("A.txt", it->second.filename);
  5204. ASSERT_EQ("text/plain", it->second.content_type);
  5205. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5206. ++it;
  5207. ASSERT_EQ("file2", it->second.name);
  5208. ASSERT_EQ("a.html", it->second.filename);
  5209. ASSERT_EQ("text/html", it->second.content_type);
  5210. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5211. it->second.content);
  5212. ++it;
  5213. ASSERT_EQ("text", it->second.name);
  5214. ASSERT_EQ("", it->second.filename);
  5215. ASSERT_EQ("", it->second.content_type);
  5216. ASSERT_EQ("text default", it->second.content);
  5217. res.set_content("ok", "text/plain");
  5218. handled = true;
  5219. });
  5220. thread t = thread([&] { svr.listen(HOST, PORT); });
  5221. auto se = detail::scope_exit([&] {
  5222. svr.stop();
  5223. t.join();
  5224. ASSERT_FALSE(svr.is_running());
  5225. ASSERT_TRUE(handled);
  5226. });
  5227. svr.wait_until_ready();
  5228. auto req = "POST /test HTTP/1.1\r\n"
  5229. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5230. "Content-Length: 399\r\n"
  5231. "\r\n"
  5232. "----------\r\n"
  5233. "Content-Disposition: form-data; name=\"text\"\r\n"
  5234. "\r\n"
  5235. "text default\r\n"
  5236. "----------\r\n"
  5237. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  5238. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5239. "Content-Type: text/plain\r\n"
  5240. "\r\n"
  5241. "Content of a.txt.\r\n"
  5242. "\r\n"
  5243. "----------\r\n"
  5244. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5245. "\"a.html\"\r\n"
  5246. "Content-Type: text/html\r\n"
  5247. "\r\n"
  5248. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5249. "\r\n"
  5250. "------------\r\n";
  5251. ASSERT_TRUE(send_request(1, req));
  5252. }
  5253. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5254. auto handled = false;
  5255. Server svr;
  5256. svr.Post("/test", [&](const Request &req, Response &) {
  5257. ASSERT_EQ(2u, req.files.size());
  5258. auto it = req.files.begin();
  5259. ASSERT_EQ("text1", it->second.name);
  5260. ASSERT_EQ("text1", it->second.content);
  5261. ++it;
  5262. ASSERT_EQ("text2", it->second.name);
  5263. ASSERT_EQ("text2", it->second.content);
  5264. handled = true;
  5265. });
  5266. thread t = thread([&] { svr.listen(HOST, PORT); });
  5267. auto se = detail::scope_exit([&] {
  5268. svr.stop();
  5269. t.join();
  5270. ASSERT_FALSE(svr.is_running());
  5271. ASSERT_TRUE(handled);
  5272. });
  5273. svr.wait_until_ready();
  5274. auto req = "POST /test HTTP/1.1\r\n"
  5275. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5276. "Content-Length: 146\r\n"
  5277. "\r\n----------\r\n"
  5278. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5279. "\r\n"
  5280. "text1"
  5281. "\r\n----------\r\n"
  5282. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5283. "\r\n"
  5284. "text2"
  5285. "\r\n------------";
  5286. std::string resonse;
  5287. ASSERT_TRUE(send_request(1, req, &resonse));
  5288. ASSERT_EQ("200", resonse.substr(9, 3));
  5289. }
  5290. #endif
  5291. #ifndef _WIN32
  5292. class UnixSocketTest : public ::testing::Test {
  5293. protected:
  5294. void TearDown() override { std::remove(pathname_.c_str()); }
  5295. void client_GET(const std::string &addr) {
  5296. httplib::Client cli{addr};
  5297. cli.set_address_family(AF_UNIX);
  5298. ASSERT_TRUE(cli.is_valid());
  5299. const auto &result = cli.Get(pattern_);
  5300. ASSERT_TRUE(result) << "error: " << result.error();
  5301. const auto &resp = result.value();
  5302. EXPECT_EQ(resp.status, 200);
  5303. EXPECT_EQ(resp.body, content_);
  5304. }
  5305. const std::string pathname_{"./httplib-server.sock"};
  5306. const std::string pattern_{"/hi"};
  5307. const std::string content_{"Hello World!"};
  5308. };
  5309. TEST_F(UnixSocketTest, pathname) {
  5310. httplib::Server svr;
  5311. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5312. res.set_content(content_, "text/plain");
  5313. });
  5314. std::thread t{[&] {
  5315. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5316. }};
  5317. auto se = detail::scope_exit([&] {
  5318. svr.stop();
  5319. t.join();
  5320. ASSERT_FALSE(svr.is_running());
  5321. });
  5322. svr.wait_until_ready();
  5323. ASSERT_TRUE(svr.is_running());
  5324. client_GET(pathname_);
  5325. }
  5326. #if defined(__linux__) || \
  5327. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5328. TEST_F(UnixSocketTest, PeerPid) {
  5329. httplib::Server svr;
  5330. std::string remote_port_val;
  5331. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5332. res.set_content(content_, "text/plain");
  5333. remote_port_val = req.get_header_value("REMOTE_PORT");
  5334. });
  5335. std::thread t{[&] {
  5336. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5337. }};
  5338. auto se = detail::scope_exit([&] {
  5339. svr.stop();
  5340. t.join();
  5341. ASSERT_FALSE(svr.is_running());
  5342. });
  5343. svr.wait_until_ready();
  5344. ASSERT_TRUE(svr.is_running());
  5345. client_GET(pathname_);
  5346. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5347. }
  5348. #endif
  5349. #ifdef __linux__
  5350. TEST_F(UnixSocketTest, abstract) {
  5351. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5352. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5353. httplib::Server svr;
  5354. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5355. res.set_content(content_, "text/plain");
  5356. });
  5357. std::thread t{[&] {
  5358. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5359. }};
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. t.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. ASSERT_TRUE(svr.is_running());
  5367. client_GET(abstract_addr);
  5368. }
  5369. #endif
  5370. TEST(SocketStream, is_writable_UNIX) {
  5371. int fds[2];
  5372. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5373. const auto asSocketStream = [&](socket_t fd,
  5374. std::function<bool(Stream &)> func) {
  5375. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5376. };
  5377. asSocketStream(fds[0], [&](Stream &s0) {
  5378. EXPECT_EQ(s0.socket(), fds[0]);
  5379. EXPECT_TRUE(s0.is_writable());
  5380. EXPECT_EQ(0, close(fds[1]));
  5381. EXPECT_FALSE(s0.is_writable());
  5382. return true;
  5383. });
  5384. EXPECT_EQ(0, close(fds[0]));
  5385. }
  5386. TEST(SocketStream, is_writable_INET) {
  5387. sockaddr_in addr;
  5388. memset(&addr, 0, sizeof(addr));
  5389. addr.sin_family = AF_INET;
  5390. addr.sin_port = htons(PORT + 1);
  5391. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5392. int disconnected_svr_sock = -1;
  5393. std::thread svr{[&] {
  5394. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5395. ASSERT_LE(0, s);
  5396. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5397. ASSERT_EQ(0, listen(s, 1));
  5398. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5399. ASSERT_EQ(0, close(s));
  5400. }};
  5401. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5402. std::thread cli{[&] {
  5403. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5404. ASSERT_LE(0, s);
  5405. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5406. ASSERT_EQ(0, close(s));
  5407. }};
  5408. cli.join();
  5409. svr.join();
  5410. ASSERT_NE(disconnected_svr_sock, -1);
  5411. const auto asSocketStream = [&](socket_t fd,
  5412. std::function<bool(Stream &)> func) {
  5413. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5414. };
  5415. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5416. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5417. EXPECT_FALSE(ss.is_writable());
  5418. return true;
  5419. });
  5420. ASSERT_EQ(0, close(disconnected_svr_sock));
  5421. }
  5422. #endif // #ifndef _WIN32
  5423. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5424. static constexpr unsigned int number_of_task{1000000};
  5425. std::atomic_uint count{0};
  5426. std::unique_ptr<TaskQueue> task_queue{
  5427. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5428. for (unsigned int i = 0; i < number_of_task; ++i) {
  5429. task_queue->enqueue(
  5430. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5431. }
  5432. EXPECT_NO_THROW(task_queue->shutdown());
  5433. EXPECT_EQ(number_of_task, count.load());
  5434. }
  5435. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5436. Server svr;
  5437. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5438. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5439. });
  5440. svr.Get("/hello", [](const Request &req, Response &res) {
  5441. res.set_content(req.get_param_value("key"), "text/plain");
  5442. });
  5443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5444. auto se = detail::scope_exit([&] {
  5445. svr.stop();
  5446. thread.join();
  5447. ASSERT_FALSE(svr.is_running());
  5448. });
  5449. svr.wait_until_ready();
  5450. {
  5451. Client cli(HOST, PORT);
  5452. cli.set_follow_location(true);
  5453. auto res = cli.Get("/");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(200, res->status);
  5456. EXPECT_EQ("val&key2=val2", res->body);
  5457. }
  5458. }
  5459. TEST(VulnerabilityTest, CRLFInjection) {
  5460. Server svr;
  5461. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  5462. res.set_content("Hello 1", "text/plain");
  5463. });
  5464. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  5465. res.set_content("Hello 2", "text/plain");
  5466. });
  5467. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  5468. res.set_content("Hello 3", "text/plain");
  5469. });
  5470. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  5471. res.set_content("Hello 4", "text/plain");
  5472. });
  5473. svr.set_logger([](const Request &req, const Response & /*res*/) {
  5474. for (const auto &x : req.headers) {
  5475. auto key = x.first;
  5476. EXPECT_STRNE("evil", key.c_str());
  5477. }
  5478. });
  5479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5480. auto se = detail::scope_exit([&] {
  5481. svr.stop();
  5482. thread.join();
  5483. ASSERT_FALSE(svr.is_running());
  5484. });
  5485. svr.wait_until_ready();
  5486. {
  5487. Client cli(HOST, PORT);
  5488. cli.Post("/test1", "A=B",
  5489. "application/x-www-form-urlencoded\r\nevil: hello1");
  5490. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  5491. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  5492. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  5493. }
  5494. }
  5495. TEST(PathParamsTest, StaticMatch) {
  5496. const auto pattern = "/users/all";
  5497. detail::PathParamsMatcher matcher(pattern);
  5498. Request request;
  5499. request.path = "/users/all";
  5500. ASSERT_TRUE(matcher.match(request));
  5501. std::unordered_map<std::string, std::string> expected_params = {};
  5502. EXPECT_EQ(request.path_params, expected_params);
  5503. }
  5504. TEST(PathParamsTest, StaticMismatch) {
  5505. const auto pattern = "/users/all";
  5506. detail::PathParamsMatcher matcher(pattern);
  5507. Request request;
  5508. request.path = "/users/1";
  5509. ASSERT_FALSE(matcher.match(request));
  5510. }
  5511. TEST(PathParamsTest, SingleParamInTheMiddle) {
  5512. const auto pattern = "/users/:id/subscriptions";
  5513. detail::PathParamsMatcher matcher(pattern);
  5514. Request request;
  5515. request.path = "/users/42/subscriptions";
  5516. ASSERT_TRUE(matcher.match(request));
  5517. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5518. EXPECT_EQ(request.path_params, expected_params);
  5519. }
  5520. TEST(PathParamsTest, SingleParamInTheEnd) {
  5521. const auto pattern = "/users/:id";
  5522. detail::PathParamsMatcher matcher(pattern);
  5523. Request request;
  5524. request.path = "/users/24";
  5525. ASSERT_TRUE(matcher.match(request));
  5526. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  5527. EXPECT_EQ(request.path_params, expected_params);
  5528. }
  5529. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  5530. const auto pattern = "/users/:id/";
  5531. detail::PathParamsMatcher matcher(pattern);
  5532. Request request;
  5533. request.path = "/users/42/";
  5534. ASSERT_TRUE(matcher.match(request));
  5535. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5536. EXPECT_EQ(request.path_params, expected_params);
  5537. }
  5538. TEST(PathParamsTest, EmptyParam) {
  5539. const auto pattern = "/users/:id/";
  5540. detail::PathParamsMatcher matcher(pattern);
  5541. Request request;
  5542. request.path = "/users//";
  5543. ASSERT_TRUE(matcher.match(request));
  5544. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  5545. EXPECT_EQ(request.path_params, expected_params);
  5546. }
  5547. TEST(PathParamsTest, FragmentMismatch) {
  5548. const auto pattern = "/users/:id/";
  5549. detail::PathParamsMatcher matcher(pattern);
  5550. Request request;
  5551. request.path = "/admins/24/";
  5552. ASSERT_FALSE(matcher.match(request));
  5553. }
  5554. TEST(PathParamsTest, ExtraFragments) {
  5555. const auto pattern = "/users/:id";
  5556. detail::PathParamsMatcher matcher(pattern);
  5557. Request request;
  5558. request.path = "/users/42/subscriptions";
  5559. ASSERT_FALSE(matcher.match(request));
  5560. }
  5561. TEST(PathParamsTest, MissingTrailingParam) {
  5562. const auto pattern = "/users/:id";
  5563. detail::PathParamsMatcher matcher(pattern);
  5564. Request request;
  5565. request.path = "/users";
  5566. ASSERT_FALSE(matcher.match(request));
  5567. }
  5568. TEST(PathParamsTest, MissingParamInTheMiddle) {
  5569. const auto pattern = "/users/:id/subscriptions";
  5570. detail::PathParamsMatcher matcher(pattern);
  5571. Request request;
  5572. request.path = "/users/subscriptions";
  5573. ASSERT_FALSE(matcher.match(request));
  5574. }
  5575. TEST(PathParamsTest, MultipleParams) {
  5576. const auto pattern = "/users/:userid/subscriptions/:subid";
  5577. detail::PathParamsMatcher matcher(pattern);
  5578. Request request;
  5579. request.path = "/users/42/subscriptions/2";
  5580. ASSERT_TRUE(matcher.match(request));
  5581. std::unordered_map<std::string, std::string> expected_params = {
  5582. {"userid", "42"}, {"subid", "2"}};
  5583. EXPECT_EQ(request.path_params, expected_params);
  5584. }
  5585. TEST(PathParamsTest, SequenceOfParams) {
  5586. const auto pattern = "/values/:x/:y/:z";
  5587. detail::PathParamsMatcher matcher(pattern);
  5588. Request request;
  5589. request.path = "/values/1/2/3";
  5590. ASSERT_TRUE(matcher.match(request));
  5591. std::unordered_map<std::string, std::string> expected_params = {
  5592. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  5593. EXPECT_EQ(request.path_params, expected_params);
  5594. }