test.cc 198 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737
  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("/regex-with-delimiter",
  1559. [&](const Request & req, Response &res) {
  1560. ASSERT_TRUE(req.has_param("key"));
  1561. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  1562. })
  1563. .Get("/with-range",
  1564. [&](const Request & /*req*/, Response &res) {
  1565. res.set_content("abcdefg", "text/plain");
  1566. })
  1567. .Post("/chunked",
  1568. [&](const Request &req, Response & /*res*/) {
  1569. EXPECT_EQ(req.body, "dechunked post body");
  1570. })
  1571. .Post("/large-chunked",
  1572. [&](const Request &req, Response & /*res*/) {
  1573. std::string expected(6 * 30 * 1024u, 'a');
  1574. EXPECT_EQ(req.body, expected);
  1575. })
  1576. .Post("/multipart",
  1577. [&](const Request &req, Response & /*res*/) {
  1578. EXPECT_EQ(6u, req.files.size());
  1579. ASSERT_TRUE(!req.has_file("???"));
  1580. ASSERT_TRUE(req.body.empty());
  1581. {
  1582. const auto &file = req.get_file_value("text1");
  1583. EXPECT_TRUE(file.filename.empty());
  1584. EXPECT_EQ("text default", file.content);
  1585. }
  1586. {
  1587. const auto &file = req.get_file_value("text2");
  1588. EXPECT_TRUE(file.filename.empty());
  1589. EXPECT_EQ("aωb", file.content);
  1590. }
  1591. {
  1592. const auto &file = req.get_file_value("file1");
  1593. EXPECT_EQ("hello.txt", file.filename);
  1594. EXPECT_EQ("text/plain", file.content_type);
  1595. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1596. }
  1597. {
  1598. const auto &file = req.get_file_value("file3");
  1599. EXPECT_TRUE(file.filename.empty());
  1600. EXPECT_EQ("application/octet-stream", file.content_type);
  1601. EXPECT_EQ(0u, file.content.size());
  1602. }
  1603. {
  1604. const auto &file = req.get_file_value("file4");
  1605. EXPECT_TRUE(file.filename.empty());
  1606. EXPECT_EQ(0u, file.content.size());
  1607. EXPECT_EQ("application/json tmp-string", file.content_type);
  1608. }
  1609. })
  1610. .Post("/multipart/multi_file_values",
  1611. [&](const Request &req, Response & /*res*/) {
  1612. EXPECT_EQ(5u, req.files.size());
  1613. ASSERT_TRUE(!req.has_file("???"));
  1614. ASSERT_TRUE(req.body.empty());
  1615. {
  1616. const auto &text_value = req.get_file_values("text");
  1617. EXPECT_EQ(1u, text_value.size());
  1618. auto &text = text_value[0];
  1619. EXPECT_TRUE(text.filename.empty());
  1620. EXPECT_EQ("default text", text.content);
  1621. }
  1622. {
  1623. const auto &text1_values = req.get_file_values("multi_text1");
  1624. EXPECT_EQ(2u, text1_values.size());
  1625. EXPECT_EQ("aaaaa", text1_values[0].content);
  1626. EXPECT_EQ("bbbbb", text1_values[1].content);
  1627. }
  1628. {
  1629. const auto &file1_values = req.get_file_values("multi_file1");
  1630. EXPECT_EQ(2u, file1_values.size());
  1631. auto file1 = file1_values[0];
  1632. EXPECT_EQ(file1.filename, "hello.txt");
  1633. EXPECT_EQ(file1.content_type, "text/plain");
  1634. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1635. auto file2 = file1_values[1];
  1636. EXPECT_EQ(file2.filename, "world.json");
  1637. EXPECT_EQ(file2.content_type, "application/json");
  1638. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1639. }
  1640. })
  1641. .Post("/empty",
  1642. [&](const Request &req, Response &res) {
  1643. EXPECT_EQ(req.body, "");
  1644. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1645. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1646. res.set_content("empty", "text/plain");
  1647. })
  1648. .Post("/empty-no-content-type",
  1649. [&](const Request &req, Response &res) {
  1650. EXPECT_EQ(req.body, "");
  1651. EXPECT_FALSE(req.has_header("Content-Type"));
  1652. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1653. res.set_content("empty-no-content-type", "text/plain");
  1654. })
  1655. .Post("/path-only",
  1656. [&](const Request &req, Response &res) {
  1657. EXPECT_EQ(req.body, "");
  1658. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1659. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1660. res.set_content("path-only", "text/plain");
  1661. })
  1662. .Post("/path-headers-only",
  1663. [&](const Request &req, Response &res) {
  1664. EXPECT_EQ(req.body, "");
  1665. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1666. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1667. EXPECT_EQ("world", req.get_header_value("hello"));
  1668. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1669. res.set_content("path-headers-only", "text/plain");
  1670. })
  1671. .Post("/post-large",
  1672. [&](const Request &req, Response &res) {
  1673. EXPECT_EQ(req.body, LARGE_DATA);
  1674. res.set_content(req.body, "text/plain");
  1675. })
  1676. .Put("/empty-no-content-type",
  1677. [&](const Request &req, Response &res) {
  1678. EXPECT_EQ(req.body, "");
  1679. EXPECT_FALSE(req.has_header("Content-Type"));
  1680. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1681. res.set_content("empty-no-content-type", "text/plain");
  1682. })
  1683. .Put("/put",
  1684. [&](const Request &req, Response &res) {
  1685. EXPECT_EQ(req.body, "PUT");
  1686. res.set_content(req.body, "text/plain");
  1687. })
  1688. .Put("/put-large",
  1689. [&](const Request &req, Response &res) {
  1690. EXPECT_EQ(req.body, LARGE_DATA);
  1691. res.set_content(req.body, "text/plain");
  1692. })
  1693. .Patch("/patch",
  1694. [&](const Request &req, Response &res) {
  1695. EXPECT_EQ(req.body, "PATCH");
  1696. res.set_content(req.body, "text/plain");
  1697. })
  1698. .Delete("/delete",
  1699. [&](const Request & /*req*/, Response &res) {
  1700. res.set_content("DELETE", "text/plain");
  1701. })
  1702. .Delete("/delete-body",
  1703. [&](const Request &req, Response &res) {
  1704. EXPECT_EQ(req.body, "content");
  1705. res.set_content(req.body, "text/plain");
  1706. })
  1707. .Options(R"(\*)",
  1708. [&](const Request & /*req*/, Response &res) {
  1709. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1710. })
  1711. .Get("/request-target",
  1712. [&](const Request &req, Response & /*res*/) {
  1713. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1714. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1715. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1716. })
  1717. .Get("/long-query-value",
  1718. [&](const Request &req, Response & /*res*/) {
  1719. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1720. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1721. })
  1722. .Get("/array-param",
  1723. [&](const Request &req, Response & /*res*/) {
  1724. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1725. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1726. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1727. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1728. })
  1729. .Post("/validate-no-multiple-headers",
  1730. [&](const Request &req, Response & /*res*/) {
  1731. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1732. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1733. })
  1734. .Post("/content_receiver",
  1735. [&](const Request &req, Response &res,
  1736. const ContentReader &content_reader) {
  1737. if (req.is_multipart_form_data()) {
  1738. MultipartFormDataItems files;
  1739. content_reader(
  1740. [&](const MultipartFormData &file) {
  1741. files.push_back(file);
  1742. return true;
  1743. },
  1744. [&](const char *data, size_t data_length) {
  1745. files.back().content.append(data, data_length);
  1746. return true;
  1747. });
  1748. EXPECT_EQ(5u, files.size());
  1749. {
  1750. const auto &file = get_file_value(files, "text1");
  1751. EXPECT_TRUE(file.filename.empty());
  1752. EXPECT_EQ("text default", file.content);
  1753. }
  1754. {
  1755. const auto &file = get_file_value(files, "text2");
  1756. EXPECT_TRUE(file.filename.empty());
  1757. EXPECT_EQ("aωb", file.content);
  1758. }
  1759. {
  1760. const auto &file = get_file_value(files, "file1");
  1761. EXPECT_EQ("hello.txt", file.filename);
  1762. EXPECT_EQ("text/plain", file.content_type);
  1763. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1764. }
  1765. {
  1766. const auto &file = get_file_value(files, "file3");
  1767. EXPECT_TRUE(file.filename.empty());
  1768. EXPECT_EQ("application/octet-stream", file.content_type);
  1769. EXPECT_EQ(0u, file.content.size());
  1770. }
  1771. } else {
  1772. std::string body;
  1773. content_reader([&](const char *data, size_t data_length) {
  1774. EXPECT_EQ(7U, data_length);
  1775. body.append(data, data_length);
  1776. return true;
  1777. });
  1778. EXPECT_EQ(body, "content");
  1779. res.set_content(body, "text/plain");
  1780. }
  1781. })
  1782. .Put("/content_receiver",
  1783. [&](const Request & /*req*/, Response &res,
  1784. const ContentReader &content_reader) {
  1785. std::string body;
  1786. content_reader([&](const char *data, size_t data_length) {
  1787. body.append(data, data_length);
  1788. return true;
  1789. });
  1790. EXPECT_EQ(body, "content");
  1791. res.set_content(body, "text/plain");
  1792. })
  1793. .Patch("/content_receiver",
  1794. [&](const Request & /*req*/, Response &res,
  1795. const ContentReader &content_reader) {
  1796. std::string body;
  1797. content_reader([&](const char *data, size_t data_length) {
  1798. body.append(data, data_length);
  1799. return true;
  1800. });
  1801. EXPECT_EQ(body, "content");
  1802. res.set_content(body, "text/plain");
  1803. })
  1804. .Post("/query-string-and-body",
  1805. [&](const Request &req, Response & /*res*/) {
  1806. ASSERT_TRUE(req.has_param("key"));
  1807. EXPECT_EQ(req.get_param_value("key"), "value");
  1808. EXPECT_EQ(req.body, "content");
  1809. })
  1810. .Get("/last-request",
  1811. [&](const Request &req, Response & /*res*/) {
  1812. EXPECT_EQ("close", req.get_header_value("Connection"));
  1813. })
  1814. .Get(R"(/redirect/(\d+))",
  1815. [&](const Request &req, Response &res) {
  1816. auto num = std::stoi(req.matches[1]) + 1;
  1817. std::string url = "/redirect/" + std::to_string(num);
  1818. res.set_redirect(url);
  1819. })
  1820. .Post("/binary",
  1821. [&](const Request &req, Response &res) {
  1822. EXPECT_EQ(4U, req.body.size());
  1823. EXPECT_EQ("application/octet-stream",
  1824. req.get_header_value("Content-Type"));
  1825. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1826. res.set_content(req.body, "application/octet-stream");
  1827. })
  1828. .Put("/binary",
  1829. [&](const Request &req, Response &res) {
  1830. EXPECT_EQ(4U, req.body.size());
  1831. EXPECT_EQ("application/octet-stream",
  1832. req.get_header_value("Content-Type"));
  1833. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1834. res.set_content(req.body, "application/octet-stream");
  1835. })
  1836. .Patch("/binary",
  1837. [&](const Request &req, Response &res) {
  1838. EXPECT_EQ(4U, req.body.size());
  1839. EXPECT_EQ("application/octet-stream",
  1840. req.get_header_value("Content-Type"));
  1841. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1842. res.set_content(req.body, "application/octet-stream");
  1843. })
  1844. .Delete("/binary",
  1845. [&](const Request &req, Response &res) {
  1846. EXPECT_EQ(4U, req.body.size());
  1847. EXPECT_EQ("application/octet-stream",
  1848. req.get_header_value("Content-Type"));
  1849. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1850. res.set_content(req.body, "application/octet-stream");
  1851. })
  1852. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1853. .Get("/compress",
  1854. [&](const Request & /*req*/, Response &res) {
  1855. res.set_content(
  1856. "12345678901234567890123456789012345678901234567890123456789"
  1857. "01234567890123456789012345678901234567890",
  1858. "text/plain");
  1859. })
  1860. .Get("/nocompress",
  1861. [&](const Request & /*req*/, Response &res) {
  1862. res.set_content(
  1863. "12345678901234567890123456789012345678901234567890123456789"
  1864. "01234567890123456789012345678901234567890",
  1865. "application/octet-stream");
  1866. })
  1867. .Post("/compress-multipart",
  1868. [&](const Request &req, Response & /*res*/) {
  1869. EXPECT_EQ(2u, req.files.size());
  1870. ASSERT_TRUE(!req.has_file("???"));
  1871. {
  1872. const auto &file = req.get_file_value("key1");
  1873. EXPECT_TRUE(file.filename.empty());
  1874. EXPECT_EQ("test", file.content);
  1875. }
  1876. {
  1877. const auto &file = req.get_file_value("key2");
  1878. EXPECT_TRUE(file.filename.empty());
  1879. EXPECT_EQ("--abcdefg123", file.content);
  1880. }
  1881. })
  1882. #endif
  1883. ;
  1884. persons_["john"] = "programmer";
  1885. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1886. svr_.wait_until_ready();
  1887. }
  1888. virtual void TearDown() {
  1889. svr_.stop();
  1890. if (!request_threads_.empty()) {
  1891. std::this_thread::sleep_for(std::chrono::seconds(1));
  1892. for (auto &t : request_threads_) {
  1893. t.join();
  1894. }
  1895. }
  1896. t_.join();
  1897. }
  1898. map<string, string> persons_;
  1899. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1900. SSLClient cli_;
  1901. SSLServer svr_;
  1902. #else
  1903. Client cli_;
  1904. Server svr_;
  1905. #endif
  1906. thread t_;
  1907. std::vector<thread> request_threads_;
  1908. };
  1909. TEST_F(ServerTest, GetMethod200) {
  1910. auto res = cli_.Get("/hi");
  1911. ASSERT_TRUE(res);
  1912. EXPECT_EQ("HTTP/1.1", res->version);
  1913. EXPECT_EQ(200, res->status);
  1914. EXPECT_EQ("OK", res->reason);
  1915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1916. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1917. EXPECT_EQ("Hello World!", res->body);
  1918. }
  1919. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1920. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ("HTTP/1.1", res->version);
  1923. EXPECT_EQ(200, res->status);
  1924. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1925. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1926. EXPECT_EQ("Hello World!", res->body);
  1927. }
  1928. TEST_F(ServerTest, GetMethod302) {
  1929. auto res = cli_.Get("/");
  1930. ASSERT_TRUE(res);
  1931. EXPECT_EQ(302, res->status);
  1932. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1933. }
  1934. TEST_F(ServerTest, GetMethod302Redirect) {
  1935. cli_.set_follow_location(true);
  1936. auto res = cli_.Get("/");
  1937. ASSERT_TRUE(res);
  1938. EXPECT_EQ(200, res->status);
  1939. EXPECT_EQ("Hello World!", res->body);
  1940. EXPECT_EQ("/hi", res->location);
  1941. }
  1942. TEST_F(ServerTest, GetMethod404) {
  1943. auto res = cli_.Get("/invalid");
  1944. ASSERT_TRUE(res);
  1945. EXPECT_EQ(404, res->status);
  1946. }
  1947. TEST_F(ServerTest, HeadMethod200) {
  1948. auto res = cli_.Head("/hi");
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(200, res->status);
  1951. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1952. EXPECT_TRUE(res->body.empty());
  1953. }
  1954. TEST_F(ServerTest, HeadMethod200Static) {
  1955. auto res = cli_.Head("/mount/dir/index.html");
  1956. ASSERT_TRUE(res);
  1957. EXPECT_EQ(200, res->status);
  1958. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1959. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1960. EXPECT_TRUE(res->body.empty());
  1961. }
  1962. TEST_F(ServerTest, HeadMethod404) {
  1963. auto res = cli_.Head("/invalid");
  1964. ASSERT_TRUE(res);
  1965. EXPECT_EQ(404, res->status);
  1966. EXPECT_TRUE(res->body.empty());
  1967. }
  1968. TEST_F(ServerTest, GetMethodPersonJohn) {
  1969. auto res = cli_.Get("/person/john");
  1970. ASSERT_TRUE(res);
  1971. EXPECT_EQ(200, res->status);
  1972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1973. EXPECT_EQ("programmer", res->body);
  1974. }
  1975. TEST_F(ServerTest, PostMethod1) {
  1976. auto res = cli_.Get("/person/john1");
  1977. ASSERT_TRUE(res);
  1978. ASSERT_EQ(404, res->status);
  1979. res = cli_.Post("/person", "name=john1&note=coder",
  1980. "application/x-www-form-urlencoded");
  1981. ASSERT_TRUE(res);
  1982. ASSERT_EQ(200, res->status);
  1983. res = cli_.Get("/person/john1");
  1984. ASSERT_TRUE(res);
  1985. ASSERT_EQ(200, res->status);
  1986. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1987. ASSERT_EQ("coder", res->body);
  1988. }
  1989. TEST_F(ServerTest, PostMethod2) {
  1990. auto res = cli_.Get("/person/john2");
  1991. ASSERT_TRUE(res);
  1992. ASSERT_EQ(404, res->status);
  1993. Params params;
  1994. params.emplace("name", "john2");
  1995. params.emplace("note", "coder");
  1996. res = cli_.Post("/person", params);
  1997. ASSERT_TRUE(res);
  1998. ASSERT_EQ(200, res->status);
  1999. res = cli_.Get("/person/john2");
  2000. ASSERT_TRUE(res);
  2001. ASSERT_EQ(200, res->status);
  2002. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2003. ASSERT_EQ("coder", res->body);
  2004. }
  2005. TEST_F(ServerTest, PutMethod3) {
  2006. auto res = cli_.Get("/person/john3");
  2007. ASSERT_TRUE(res);
  2008. ASSERT_EQ(404, res->status);
  2009. Params params;
  2010. params.emplace("name", "john3");
  2011. params.emplace("note", "coder");
  2012. res = cli_.Put("/person", params);
  2013. ASSERT_TRUE(res);
  2014. ASSERT_EQ(200, res->status);
  2015. res = cli_.Get("/person/john3");
  2016. ASSERT_TRUE(res);
  2017. ASSERT_EQ(200, res->status);
  2018. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2019. ASSERT_EQ("coder", res->body);
  2020. }
  2021. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2022. Params params;
  2023. params.emplace("json", JSON_DATA);
  2024. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2025. ASSERT_TRUE(res);
  2026. ASSERT_EQ(200, res->status);
  2027. ASSERT_EQ(JSON_DATA, res->body);
  2028. }
  2029. TEST_F(ServerTest, PostEmptyContent) {
  2030. auto res = cli_.Post("/empty", "", "text/plain");
  2031. ASSERT_TRUE(res);
  2032. ASSERT_EQ(200, res->status);
  2033. ASSERT_EQ("empty", res->body);
  2034. }
  2035. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2036. auto res = cli_.Post("/empty-no-content-type");
  2037. ASSERT_TRUE(res);
  2038. ASSERT_EQ(200, res->status);
  2039. ASSERT_EQ("empty-no-content-type", res->body);
  2040. }
  2041. TEST_F(ServerTest, PostPathOnly) {
  2042. auto res = cli_.Post("/path-only");
  2043. ASSERT_TRUE(res);
  2044. ASSERT_EQ(200, res->status);
  2045. ASSERT_EQ("path-only", res->body);
  2046. }
  2047. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2048. auto res = cli_.Post("/path-headers-only",
  2049. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2050. ASSERT_TRUE(res);
  2051. ASSERT_EQ(200, res->status);
  2052. ASSERT_EQ("path-headers-only", res->body);
  2053. }
  2054. TEST_F(ServerTest, PostLarge) {
  2055. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2056. ASSERT_TRUE(res);
  2057. ASSERT_EQ(200, res->status);
  2058. EXPECT_EQ(LARGE_DATA, res->body);
  2059. }
  2060. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2061. auto res = cli_.Put("/empty-no-content-type");
  2062. ASSERT_TRUE(res);
  2063. ASSERT_EQ(200, res->status);
  2064. ASSERT_EQ("empty-no-content-type", res->body);
  2065. }
  2066. TEST_F(ServerTest, GetMethodDir) {
  2067. auto res = cli_.Get("/dir/");
  2068. ASSERT_TRUE(res);
  2069. EXPECT_EQ(200, res->status);
  2070. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2071. auto body = R"(<html>
  2072. <head>
  2073. </head>
  2074. <body>
  2075. <a href="/dir/test.html">Test</a>
  2076. <a href="/hi">hi</a>
  2077. </body>
  2078. </html>
  2079. )";
  2080. EXPECT_EQ(body, res->body);
  2081. }
  2082. TEST_F(ServerTest, GetMethodDirTest) {
  2083. auto res = cli_.Get("/dir/test.html");
  2084. ASSERT_TRUE(res);
  2085. EXPECT_EQ(200, res->status);
  2086. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2087. EXPECT_EQ("test.html", res->body);
  2088. }
  2089. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2090. auto res = cli_.Get("/dir/../dir/test.html");
  2091. ASSERT_TRUE(res);
  2092. EXPECT_EQ(200, res->status);
  2093. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2094. EXPECT_EQ("test.html", res->body);
  2095. }
  2096. TEST_F(ServerTest, GetMethodInvalidPath) {
  2097. auto res = cli_.Get("/dir/../test.html");
  2098. ASSERT_TRUE(res);
  2099. EXPECT_EQ(404, res->status);
  2100. }
  2101. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2102. auto res = cli_.Get("/../www/dir/test.html");
  2103. ASSERT_TRUE(res);
  2104. EXPECT_EQ(404, res->status);
  2105. }
  2106. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2107. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2108. ASSERT_TRUE(res);
  2109. EXPECT_EQ(404, res->status);
  2110. }
  2111. TEST_F(ServerTest, GetMethodDirMountTest) {
  2112. auto res = cli_.Get("/mount/dir/test.html");
  2113. ASSERT_TRUE(res);
  2114. EXPECT_EQ(200, res->status);
  2115. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2116. EXPECT_EQ("test.html", res->body);
  2117. }
  2118. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2119. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2120. ASSERT_TRUE(res);
  2121. EXPECT_EQ(200, res->status);
  2122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2123. EXPECT_EQ("test.html", res->body);
  2124. }
  2125. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2126. auto res = cli_.Get("/mount/dir/../test.html");
  2127. ASSERT_TRUE(res);
  2128. EXPECT_EQ(404, res->status);
  2129. }
  2130. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2131. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(404, res->status);
  2134. }
  2135. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2136. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2137. ASSERT_TRUE(res);
  2138. EXPECT_EQ(404, res->status);
  2139. }
  2140. TEST_F(ServerTest, PostMethod303) {
  2141. auto res = cli_.Post("/1", "body", "text/plain");
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ(303, res->status);
  2144. EXPECT_EQ("/2", res->get_header_value("Location"));
  2145. }
  2146. TEST_F(ServerTest, PostMethod303Redirect) {
  2147. cli_.set_follow_location(true);
  2148. auto res = cli_.Post("/1", "body", "text/plain");
  2149. ASSERT_TRUE(res);
  2150. EXPECT_EQ(200, res->status);
  2151. EXPECT_EQ("redirected.", res->body);
  2152. EXPECT_EQ("/2", res->location);
  2153. }
  2154. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2155. auto res = cli_.Get("/dir/test.abcde");
  2156. ASSERT_TRUE(res);
  2157. EXPECT_EQ(200, res->status);
  2158. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2159. EXPECT_EQ("abcde", res->body);
  2160. }
  2161. TEST_F(ServerTest, StaticFileRange) {
  2162. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2163. ASSERT_TRUE(res);
  2164. EXPECT_EQ(206, res->status);
  2165. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2166. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2167. EXPECT_EQ(true, res->has_header("Content-Range"));
  2168. EXPECT_EQ(std::string("cd"), res->body);
  2169. }
  2170. TEST_F(ServerTest, StaticFileRanges) {
  2171. auto res =
  2172. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2173. ASSERT_TRUE(res);
  2174. EXPECT_EQ(206, res->status);
  2175. EXPECT_TRUE(
  2176. res->get_header_value("Content-Type")
  2177. .find(
  2178. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2179. 0);
  2180. EXPECT_EQ("265", res->get_header_value("Content-Length"));
  2181. }
  2182. TEST_F(ServerTest, StaticFileRangeHead) {
  2183. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2184. ASSERT_TRUE(res);
  2185. EXPECT_EQ(206, res->status);
  2186. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2187. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2188. EXPECT_EQ(true, res->has_header("Content-Range"));
  2189. }
  2190. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2191. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2192. ASSERT_TRUE(res);
  2193. EXPECT_EQ(206, res->status);
  2194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2195. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2196. EXPECT_EQ(true, res->has_header("Content-Range"));
  2197. EXPECT_EQ("LAST\n", res->body);
  2198. }
  2199. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2200. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2201. ASSERT_TRUE(res);
  2202. EXPECT_EQ(206, res->status);
  2203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2204. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2205. EXPECT_EQ(true, res->has_header("Content-Range"));
  2206. }
  2207. TEST_F(ServerTest, StaticFileBigFile) {
  2208. auto res = cli_.Get("/dir/1MB.txt");
  2209. ASSERT_TRUE(res);
  2210. EXPECT_EQ(200, res->status);
  2211. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2212. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2213. }
  2214. TEST_F(ServerTest, InvalidBaseDirMount) {
  2215. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2216. }
  2217. TEST_F(ServerTest, Binary) {
  2218. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2219. auto res = cli_.Post("/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_.Put("/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_.Patch("/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. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2235. "application/octet-stream");
  2236. ASSERT_TRUE(res);
  2237. ASSERT_EQ(200, res->status);
  2238. ASSERT_EQ(4U, res->body.size());
  2239. }
  2240. TEST_F(ServerTest, BinaryString) {
  2241. auto binary = std::string("\x00\x01\x02\x03", 4);
  2242. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2243. ASSERT_TRUE(res);
  2244. ASSERT_EQ(200, res->status);
  2245. ASSERT_EQ(4U, res->body.size());
  2246. res = cli_.Put("/binary", binary, "application/octet-stream");
  2247. ASSERT_TRUE(res);
  2248. ASSERT_EQ(200, res->status);
  2249. ASSERT_EQ(4U, res->body.size());
  2250. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2251. ASSERT_TRUE(res);
  2252. ASSERT_EQ(200, res->status);
  2253. ASSERT_EQ(4U, res->body.size());
  2254. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2255. ASSERT_TRUE(res);
  2256. ASSERT_EQ(200, res->status);
  2257. ASSERT_EQ(4U, res->body.size());
  2258. }
  2259. TEST_F(ServerTest, EmptyRequest) {
  2260. auto res = cli_.Get("");
  2261. ASSERT_TRUE(!res);
  2262. EXPECT_EQ(Error::Connection, res.error());
  2263. }
  2264. TEST_F(ServerTest, LongRequest) {
  2265. std::string request;
  2266. for (size_t i = 0; i < 545; i++) {
  2267. request += "/TooLongRequest";
  2268. }
  2269. request += "OK";
  2270. auto res = cli_.Get(request.c_str());
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(404, res->status);
  2273. }
  2274. TEST_F(ServerTest, TooLongRequest) {
  2275. std::string request;
  2276. for (size_t i = 0; i < 545; i++) {
  2277. request += "/TooLongRequest";
  2278. }
  2279. request += "_NG";
  2280. auto res = cli_.Get(request.c_str());
  2281. ASSERT_TRUE(res);
  2282. EXPECT_EQ(414, res->status);
  2283. }
  2284. TEST_F(ServerTest, LongHeader) {
  2285. Request req;
  2286. req.method = "GET";
  2287. req.path = "/hi";
  2288. std::string host_and_port;
  2289. host_and_port += HOST;
  2290. host_and_port += ":";
  2291. host_and_port += std::to_string(PORT);
  2292. req.headers.emplace("Host", host_and_port.c_str());
  2293. req.headers.emplace("Accept", "*/*");
  2294. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2295. req.headers.emplace(
  2296. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2325. "@@@@@@@@@@@@@@@@");
  2326. auto res = std::make_shared<Response>();
  2327. auto error = Error::Success;
  2328. auto ret = cli_.send(req, *res, error);
  2329. ASSERT_TRUE(ret);
  2330. EXPECT_EQ(200, res->status);
  2331. }
  2332. TEST_F(ServerTest, LongQueryValue) {
  2333. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2334. ASSERT_TRUE(res);
  2335. EXPECT_EQ(414, res->status);
  2336. }
  2337. TEST_F(ServerTest, TooLongHeader) {
  2338. Request req;
  2339. req.method = "GET";
  2340. req.path = "/hi";
  2341. std::string host_and_port;
  2342. host_and_port += HOST;
  2343. host_and_port += ":";
  2344. host_and_port += std::to_string(PORT);
  2345. req.headers.emplace("Host", host_and_port.c_str());
  2346. req.headers.emplace("Accept", "*/*");
  2347. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2348. req.headers.emplace(
  2349. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2378. "@@@@@@@@@@@@@@@@@");
  2379. auto res = std::make_shared<Response>();
  2380. auto error = Error::Success;
  2381. auto ret = cli_.send(req, *res, error);
  2382. ASSERT_TRUE(ret);
  2383. EXPECT_EQ(200, res->status);
  2384. }
  2385. TEST_F(ServerTest, PercentEncoding) {
  2386. auto res = cli_.Get("/e%6edwith%");
  2387. ASSERT_TRUE(res);
  2388. EXPECT_EQ(200, res->status);
  2389. }
  2390. TEST_F(ServerTest, PercentEncodingUnicode) {
  2391. auto res = cli_.Get("/e%u006edwith%");
  2392. ASSERT_TRUE(res);
  2393. EXPECT_EQ(200, res->status);
  2394. }
  2395. TEST_F(ServerTest, InvalidPercentEncoding) {
  2396. auto res = cli_.Get("/%endwith%");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(404, res->status);
  2399. }
  2400. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2401. auto res = cli_.Get("/%uendwith%");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(404, res->status);
  2404. }
  2405. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2406. auto res = cli_.Get("/hello?aaa=bbb%");
  2407. ASSERT_TRUE(res);
  2408. EXPECT_EQ(404, res->status);
  2409. }
  2410. TEST_F(ServerTest, PlusSignEncoding) {
  2411. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(200, res->status);
  2414. EXPECT_EQ("a +b", res->body);
  2415. }
  2416. TEST_F(ServerTest, MultipartFormData) {
  2417. MultipartFormDataItems items = {
  2418. {"text1", "text default", "", ""},
  2419. {"text2", "aωb", "", ""},
  2420. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2421. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2422. {"file3", "", "", "application/octet-stream"},
  2423. {"file4", "", "", " application/json tmp-string "}};
  2424. auto res = cli_.Post("/multipart", items);
  2425. ASSERT_TRUE(res);
  2426. EXPECT_EQ(200, res->status);
  2427. }
  2428. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2429. MultipartFormDataItems items = {
  2430. {"text", "default text", "", ""},
  2431. {"multi_text1", "aaaaa", "", ""},
  2432. {"multi_text1", "bbbbb", "", ""},
  2433. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2434. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2435. "application/json"},
  2436. };
  2437. auto res = cli_.Post("/multipart/multi_file_values", items);
  2438. ASSERT_TRUE(res);
  2439. EXPECT_EQ(200, res->status);
  2440. }
  2441. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2442. auto res = cli_.Get("/hi");
  2443. ASSERT_TRUE(res);
  2444. EXPECT_EQ(200, res->status);
  2445. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2446. EXPECT_EQ("Hello World!", res->body);
  2447. }
  2448. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2449. Request req;
  2450. req.method = "POST";
  2451. req.path = "/chunked";
  2452. std::string host_and_port;
  2453. host_and_port += HOST;
  2454. host_and_port += ":";
  2455. host_and_port += std::to_string(PORT);
  2456. req.headers.emplace("Host", host_and_port.c_str());
  2457. req.headers.emplace("Accept", "*/*");
  2458. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2459. req.headers.emplace("Content-Type", "text/plain");
  2460. req.headers.emplace("Content-Length", "0");
  2461. req.headers.emplace(
  2462. "Transfer-Encoding",
  2463. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2464. // Client does not chunk, so make a chunked body manually.
  2465. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2466. auto res = std::make_shared<Response>();
  2467. auto error = Error::Success;
  2468. auto ret = cli_.send(req, *res, error);
  2469. ASSERT_TRUE(ret);
  2470. EXPECT_EQ(200, res->status);
  2471. }
  2472. TEST_F(ServerTest, GetStreamed2) {
  2473. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2474. ASSERT_TRUE(res);
  2475. EXPECT_EQ(206, res->status);
  2476. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2477. EXPECT_EQ(std::string("ab"), res->body);
  2478. }
  2479. TEST_F(ServerTest, GetStreamed) {
  2480. auto res = cli_.Get("/streamed");
  2481. ASSERT_TRUE(res);
  2482. EXPECT_EQ(200, res->status);
  2483. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2484. EXPECT_EQ(std::string("aaabbb"), res->body);
  2485. }
  2486. TEST_F(ServerTest, GetStreamedWithRange1) {
  2487. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2488. ASSERT_TRUE(res);
  2489. EXPECT_EQ(206, res->status);
  2490. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2491. EXPECT_EQ(true, res->has_header("Content-Range"));
  2492. EXPECT_EQ(std::string("def"), res->body);
  2493. }
  2494. TEST_F(ServerTest, GetStreamedWithRange2) {
  2495. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2496. ASSERT_TRUE(res);
  2497. EXPECT_EQ(206, res->status);
  2498. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2499. EXPECT_EQ(true, res->has_header("Content-Range"));
  2500. EXPECT_EQ(std::string("bcdefg"), res->body);
  2501. }
  2502. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2503. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2504. ASSERT_TRUE(res);
  2505. EXPECT_EQ(206, res->status);
  2506. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2507. EXPECT_EQ(true, res->has_header("Content-Range"));
  2508. EXPECT_EQ(std::string("efg"), res->body);
  2509. }
  2510. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2511. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2512. ASSERT_TRUE(res);
  2513. EXPECT_EQ(206, res->status);
  2514. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2515. EXPECT_EQ(true, res->has_header("Content-Range"));
  2516. EXPECT_EQ(std::string("abcdefg"), res->body);
  2517. }
  2518. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2519. auto res = cli_.Get("/streamed-with-range",
  2520. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2521. "92233720368547758079223372036854775807"}});
  2522. ASSERT_TRUE(res);
  2523. EXPECT_EQ(416, res->status);
  2524. }
  2525. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2526. auto res =
  2527. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2528. EXPECT_EQ(206, res->status);
  2529. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2530. EXPECT_EQ(true, res->has_header("Content-Range"));
  2531. EXPECT_EQ(std::string("abcdefg"), res->body);
  2532. }
  2533. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2534. auto res =
  2535. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2536. ASSERT_TRUE(res);
  2537. EXPECT_EQ(206, res->status);
  2538. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2539. EXPECT_EQ(false, res->has_header("Content-Range"));
  2540. EXPECT_EQ(267U, res->body.size());
  2541. }
  2542. TEST_F(ServerTest, GetStreamedEndless) {
  2543. uint64_t offset = 0;
  2544. auto res = cli_.Get("/streamed-cancel",
  2545. [&](const char * /*data*/, uint64_t data_length) {
  2546. if (offset < 100) {
  2547. offset += data_length;
  2548. return true;
  2549. }
  2550. return false;
  2551. });
  2552. ASSERT_TRUE(!res);
  2553. EXPECT_EQ(Error::Canceled, res.error());
  2554. }
  2555. TEST_F(ServerTest, ClientStop) {
  2556. std::atomic_size_t count{4};
  2557. std::vector<std::thread> threads;
  2558. for (auto i = count.load(); i != 0; --i) {
  2559. threads.emplace_back([&]() {
  2560. auto res = cli_.Get("/streamed-cancel",
  2561. [&](const char *, uint64_t) { return true; });
  2562. --count;
  2563. ASSERT_TRUE(!res);
  2564. EXPECT_TRUE(res.error() == Error::Canceled ||
  2565. res.error() == Error::Read || res.error() == Error::Write);
  2566. });
  2567. }
  2568. std::this_thread::sleep_for(std::chrono::seconds(2));
  2569. while (count != 0) {
  2570. cli_.stop();
  2571. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2572. }
  2573. for (auto &t : threads) {
  2574. t.join();
  2575. }
  2576. }
  2577. TEST_F(ServerTest, GetWithRange1) {
  2578. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2579. ASSERT_TRUE(res);
  2580. EXPECT_EQ(206, res->status);
  2581. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2582. EXPECT_EQ(true, res->has_header("Content-Range"));
  2583. EXPECT_EQ(std::string("def"), res->body);
  2584. }
  2585. TEST_F(ServerTest, GetWithRange2) {
  2586. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2587. ASSERT_TRUE(res);
  2588. EXPECT_EQ(206, res->status);
  2589. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2590. EXPECT_EQ(true, res->has_header("Content-Range"));
  2591. EXPECT_EQ(std::string("bcdefg"), res->body);
  2592. }
  2593. TEST_F(ServerTest, GetWithRange3) {
  2594. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2595. ASSERT_TRUE(res);
  2596. EXPECT_EQ(206, res->status);
  2597. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2598. EXPECT_EQ(true, res->has_header("Content-Range"));
  2599. EXPECT_EQ(std::string("a"), res->body);
  2600. }
  2601. TEST_F(ServerTest, GetWithRange4) {
  2602. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2603. ASSERT_TRUE(res);
  2604. EXPECT_EQ(206, res->status);
  2605. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2606. EXPECT_EQ(true, res->has_header("Content-Range"));
  2607. EXPECT_EQ(std::string("fg"), res->body);
  2608. }
  2609. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2610. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2611. ASSERT_TRUE(res);
  2612. EXPECT_EQ(416, res->status);
  2613. }
  2614. TEST_F(ServerTest, GetWithRangeMultipart) {
  2615. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2616. ASSERT_TRUE(res);
  2617. EXPECT_EQ(206, res->status);
  2618. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  2619. EXPECT_EQ(false, res->has_header("Content-Range"));
  2620. EXPECT_EQ(267U, res->body.size());
  2621. }
  2622. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2623. auto res =
  2624. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(416, res->status);
  2627. }
  2628. TEST_F(ServerTest, GetStreamedChunked) {
  2629. auto res = cli_.Get("/streamed-chunked");
  2630. ASSERT_TRUE(res);
  2631. EXPECT_EQ(200, res->status);
  2632. EXPECT_EQ(std::string("123456789"), res->body);
  2633. }
  2634. TEST_F(ServerTest, GetStreamedChunked2) {
  2635. auto res = cli_.Get("/streamed-chunked2");
  2636. ASSERT_TRUE(res);
  2637. EXPECT_EQ(200, res->status);
  2638. EXPECT_EQ(std::string("123456789"), res->body);
  2639. }
  2640. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2641. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2642. ASSERT_TRUE(res);
  2643. EXPECT_EQ(200, res->status);
  2644. EXPECT_EQ(std::string("123456789"), res->body);
  2645. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2646. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2647. }
  2648. TEST_F(ServerTest, LargeChunkedPost) {
  2649. Request req;
  2650. req.method = "POST";
  2651. req.path = "/large-chunked";
  2652. std::string host_and_port;
  2653. host_and_port += HOST;
  2654. host_and_port += ":";
  2655. host_and_port += std::to_string(PORT);
  2656. req.headers.emplace("Host", host_and_port.c_str());
  2657. req.headers.emplace("Accept", "*/*");
  2658. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2659. req.headers.emplace("Content-Type", "text/plain");
  2660. req.headers.emplace("Content-Length", "0");
  2661. req.headers.emplace("Transfer-Encoding", "chunked");
  2662. std::string long_string(30 * 1024u, 'a');
  2663. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2664. // Attempt to make a large enough post to exceed OS buffers, to test that
  2665. // the server handles short reads if the full chunk data isn't available.
  2666. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2667. auto res = std::make_shared<Response>();
  2668. auto error = Error::Success;
  2669. auto ret = cli_.send(req, *res, error);
  2670. ASSERT_TRUE(ret);
  2671. EXPECT_EQ(200, res->status);
  2672. }
  2673. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2674. auto res = cli_.Get("/remote_addr");
  2675. ASSERT_TRUE(res);
  2676. EXPECT_EQ(200, res->status);
  2677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2678. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2679. }
  2680. TEST_F(ServerTest, GetMethodLocalAddr) {
  2681. auto res = cli_.Get("/local_addr");
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(200, res->status);
  2684. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2685. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2686. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2687. }
  2688. TEST_F(ServerTest, HTTPResponseSplitting) {
  2689. auto res = cli_.Get("/http_response_splitting");
  2690. ASSERT_TRUE(res);
  2691. EXPECT_EQ(200, res->status);
  2692. }
  2693. TEST_F(ServerTest, SlowRequest) {
  2694. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2695. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2696. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2697. }
  2698. #if 0
  2699. TEST_F(ServerTest, SlowPost) {
  2700. char buffer[64 * 1024];
  2701. memset(buffer, 0x42, sizeof(buffer));
  2702. auto res = cli_.Post(
  2703. "/slowpost", 64 * 1024 * 1024,
  2704. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2705. auto ret = sink.write(buffer, sizeof(buffer));
  2706. EXPECT_TRUE(ret);
  2707. return true;
  2708. },
  2709. "text/plain");
  2710. ASSERT_TRUE(res);
  2711. EXPECT_EQ(200, res->status);
  2712. }
  2713. TEST_F(ServerTest, SlowPostFail) {
  2714. char buffer[64 * 1024];
  2715. memset(buffer, 0x42, sizeof(buffer));
  2716. cli_.set_write_timeout(std::chrono::seconds(0));
  2717. auto res = cli_.Post(
  2718. "/slowpost", 64 * 1024 * 1024,
  2719. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2720. sink.write(buffer, sizeof(buffer));
  2721. return true;
  2722. },
  2723. "text/plain");
  2724. ASSERT_TRUE(!res);
  2725. EXPECT_EQ(Error::Write, res.error());
  2726. }
  2727. #endif
  2728. TEST_F(ServerTest, Put) {
  2729. auto res = cli_.Put("/put", "PUT", "text/plain");
  2730. ASSERT_TRUE(res);
  2731. EXPECT_EQ(200, res->status);
  2732. EXPECT_EQ("PUT", res->body);
  2733. }
  2734. TEST_F(ServerTest, PutWithContentProvider) {
  2735. auto res = cli_.Put(
  2736. "/put", 3,
  2737. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2738. sink.os << "PUT";
  2739. return true;
  2740. },
  2741. "text/plain");
  2742. ASSERT_TRUE(res);
  2743. EXPECT_EQ(200, res->status);
  2744. EXPECT_EQ("PUT", res->body);
  2745. }
  2746. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2747. auto res = cli_.Post(
  2748. "/post", 42,
  2749. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2750. return false;
  2751. },
  2752. "text/plain");
  2753. ASSERT_TRUE(!res);
  2754. EXPECT_EQ(Error::Canceled, res.error());
  2755. }
  2756. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2757. auto res = cli_.Put(
  2758. "/put",
  2759. [](size_t /*offset*/, DataSink &sink) {
  2760. sink.os << "PUT";
  2761. sink.done();
  2762. return true;
  2763. },
  2764. "text/plain");
  2765. ASSERT_TRUE(res);
  2766. EXPECT_EQ(200, res->status);
  2767. EXPECT_EQ("PUT", res->body);
  2768. }
  2769. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2770. auto res = cli_.Post(
  2771. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2772. "text/plain");
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2777. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2778. cli_.set_compress(true);
  2779. auto res = cli_.Put(
  2780. "/put", 3,
  2781. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2782. sink.os << "PUT";
  2783. return true;
  2784. },
  2785. "text/plain");
  2786. ASSERT_TRUE(res);
  2787. EXPECT_EQ(200, res->status);
  2788. EXPECT_EQ("PUT", res->body);
  2789. }
  2790. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2791. cli_.set_compress(true);
  2792. auto res = cli_.Post(
  2793. "/post", 42,
  2794. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2795. return false;
  2796. },
  2797. "text/plain");
  2798. ASSERT_TRUE(!res);
  2799. EXPECT_EQ(Error::Canceled, res.error());
  2800. }
  2801. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2802. cli_.set_compress(true);
  2803. auto res = cli_.Put(
  2804. "/put",
  2805. [](size_t /*offset*/, DataSink &sink) {
  2806. sink.os << "PUT";
  2807. sink.done();
  2808. return true;
  2809. },
  2810. "text/plain");
  2811. ASSERT_TRUE(res);
  2812. EXPECT_EQ(200, res->status);
  2813. EXPECT_EQ("PUT", res->body);
  2814. }
  2815. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2816. cli_.set_compress(true);
  2817. auto res = cli_.Post(
  2818. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2819. "text/plain");
  2820. ASSERT_TRUE(!res);
  2821. EXPECT_EQ(Error::Canceled, res.error());
  2822. }
  2823. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2824. cli_.set_compress(true);
  2825. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2826. ASSERT_TRUE(res);
  2827. EXPECT_EQ(200, res->status);
  2828. EXPECT_EQ(LARGE_DATA, res->body);
  2829. }
  2830. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2832. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2833. Client cli(s.c_str());
  2834. cli.enable_server_certificate_verification(false);
  2835. #else
  2836. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2837. Client cli(s.c_str());
  2838. #endif
  2839. cli.set_compress(true);
  2840. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2841. ASSERT_TRUE(res);
  2842. EXPECT_EQ(200, res->status);
  2843. EXPECT_EQ(LARGE_DATA, res->body);
  2844. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  2845. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2846. }
  2847. TEST_F(ServerTest, PutContentWithDeflate) {
  2848. cli_.set_compress(false);
  2849. Headers headers;
  2850. headers.emplace("Content-Encoding", "deflate");
  2851. // PUT in deflate format:
  2852. auto res = cli_.Put("/put", headers,
  2853. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2854. ASSERT_TRUE(res);
  2855. EXPECT_EQ(200, res->status);
  2856. EXPECT_EQ("PUT", res->body);
  2857. }
  2858. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2859. Headers headers;
  2860. headers.emplace("Accept-Encoding", "gzip, deflate");
  2861. auto res = cli_.Get("/streamed-chunked", headers);
  2862. ASSERT_TRUE(res);
  2863. EXPECT_EQ(200, res->status);
  2864. EXPECT_EQ(std::string("123456789"), res->body);
  2865. }
  2866. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2867. Headers headers;
  2868. headers.emplace("Accept-Encoding", "gzip, deflate");
  2869. auto res = cli_.Get("/streamed-chunked2", headers);
  2870. ASSERT_TRUE(res);
  2871. EXPECT_EQ(200, res->status);
  2872. EXPECT_EQ(std::string("123456789"), res->body);
  2873. }
  2874. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  2875. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  2876. ASSERT_TRUE(res);
  2877. EXPECT_EQ(200, res->status);
  2878. }
  2879. TEST(GzipDecompressor, ChunkedDecompression) {
  2880. std::string data;
  2881. for (size_t i = 0; i < 32 * 1024; ++i) {
  2882. data.push_back(static_cast<char>('a' + i % 26));
  2883. }
  2884. std::string compressed_data;
  2885. {
  2886. httplib::detail::gzip_compressor compressor;
  2887. bool result = compressor.compress(
  2888. data.data(), data.size(),
  2889. /*last=*/true,
  2890. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2891. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2892. compressed_data_size);
  2893. return true;
  2894. });
  2895. ASSERT_TRUE(result);
  2896. }
  2897. std::string decompressed_data;
  2898. {
  2899. httplib::detail::gzip_decompressor decompressor;
  2900. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2901. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2902. size_t chunk_size = 130;
  2903. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2904. chunk_begin += chunk_size) {
  2905. size_t current_chunk_size =
  2906. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2907. bool result = decompressor.decompress(
  2908. compressed_data.data() + chunk_begin, current_chunk_size,
  2909. [&](const char *decompressed_data_chunk,
  2910. size_t decompressed_data_chunk_size) {
  2911. decompressed_data.insert(decompressed_data.size(),
  2912. decompressed_data_chunk,
  2913. decompressed_data_chunk_size);
  2914. return true;
  2915. });
  2916. ASSERT_TRUE(result);
  2917. }
  2918. }
  2919. ASSERT_EQ(data, decompressed_data);
  2920. }
  2921. TEST(GzipDecompressor, DeflateDecompression) {
  2922. std::string original_text = "Raw deflate without gzip";
  2923. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2924. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2925. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2926. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  2927. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2928. std::string decompressed_data;
  2929. {
  2930. httplib::detail::gzip_decompressor decompressor;
  2931. bool result = decompressor.decompress(
  2932. compressed_data.data(), compressed_data.size(),
  2933. [&](const char *decompressed_data_chunk,
  2934. size_t decompressed_data_chunk_size) {
  2935. decompressed_data.insert(decompressed_data.size(),
  2936. decompressed_data_chunk,
  2937. decompressed_data_chunk_size);
  2938. return true;
  2939. });
  2940. ASSERT_TRUE(result);
  2941. }
  2942. ASSERT_EQ(original_text, decompressed_data);
  2943. }
  2944. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  2945. std::string original_text = "Raw deflate without gzip";
  2946. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  2947. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  2948. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  2949. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  2950. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  2951. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  2952. std::string decompressed_data;
  2953. {
  2954. httplib::detail::gzip_decompressor decompressor;
  2955. bool result = decompressor.decompress(
  2956. compressed_data.data(), compressed_data.size(),
  2957. [&](const char *decompressed_data_chunk,
  2958. size_t decompressed_data_chunk_size) {
  2959. decompressed_data.insert(decompressed_data.size(),
  2960. decompressed_data_chunk,
  2961. decompressed_data_chunk_size);
  2962. return true;
  2963. });
  2964. ASSERT_TRUE(result);
  2965. }
  2966. ASSERT_EQ(original_text, decompressed_data);
  2967. }
  2968. #ifdef _WIN32
  2969. TEST(GzipDecompressor, LargeRandomData) {
  2970. // prepare large random data that is difficult to be compressed and is
  2971. // expected to have large size even when compressed
  2972. std::random_device seed_gen;
  2973. std::mt19937 random(seed_gen());
  2974. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2975. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2976. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2977. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2978. // compress data over 4GiB
  2979. std::string compressed_data;
  2980. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2981. httplib::detail::gzip_compressor compressor;
  2982. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2983. data.size() * sizeof(std::uint32_t), true,
  2984. [&](const char *data, size_t size) {
  2985. compressed_data.insert(
  2986. compressed_data.size(), data, size);
  2987. return true;
  2988. });
  2989. ASSERT_TRUE(result);
  2990. // FIXME: compressed data size is expected to be greater than 4GiB,
  2991. // but there is no guarantee
  2992. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2993. // decompress data over 4GiB
  2994. std::string decompressed_data;
  2995. decompressed_data.reserve(data_size);
  2996. httplib::detail::gzip_decompressor decompressor;
  2997. result = decompressor.decompress(
  2998. compressed_data.data(), compressed_data.size(),
  2999. [&](const char *data, size_t size) {
  3000. decompressed_data.insert(decompressed_data.size(), data, size);
  3001. return true;
  3002. });
  3003. ASSERT_TRUE(result);
  3004. // compare
  3005. ASSERT_EQ(data_size, decompressed_data.size());
  3006. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3007. 0);
  3008. }
  3009. #endif
  3010. #endif
  3011. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3012. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3013. Headers headers;
  3014. headers.emplace("Accept-Encoding", "br");
  3015. auto res = cli_.Get("/streamed-chunked", headers);
  3016. ASSERT_TRUE(res);
  3017. EXPECT_EQ(200, res->status);
  3018. EXPECT_EQ(std::string("123456789"), res->body);
  3019. }
  3020. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3021. Headers headers;
  3022. headers.emplace("Accept-Encoding", "br");
  3023. auto res = cli_.Get("/streamed-chunked2", headers);
  3024. ASSERT_TRUE(res);
  3025. EXPECT_EQ(200, res->status);
  3026. EXPECT_EQ(std::string("123456789"), res->body);
  3027. }
  3028. #endif
  3029. TEST_F(ServerTest, Patch) {
  3030. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3031. ASSERT_TRUE(res);
  3032. EXPECT_EQ(200, res->status);
  3033. EXPECT_EQ("PATCH", res->body);
  3034. }
  3035. TEST_F(ServerTest, Delete) {
  3036. auto res = cli_.Delete("/delete");
  3037. ASSERT_TRUE(res);
  3038. EXPECT_EQ(200, res->status);
  3039. EXPECT_EQ("DELETE", res->body);
  3040. }
  3041. TEST_F(ServerTest, DeleteContentReceiver) {
  3042. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3043. ASSERT_TRUE(res);
  3044. EXPECT_EQ(200, res->status);
  3045. EXPECT_EQ("content", res->body);
  3046. }
  3047. TEST_F(ServerTest, Options) {
  3048. auto res = cli_.Options("*");
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ(200, res->status);
  3051. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3052. EXPECT_TRUE(res->body.empty());
  3053. }
  3054. TEST_F(ServerTest, URL) {
  3055. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3056. ASSERT_TRUE(res);
  3057. EXPECT_EQ(200, res->status);
  3058. }
  3059. TEST_F(ServerTest, ArrayParam) {
  3060. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3061. ASSERT_TRUE(res);
  3062. EXPECT_EQ(200, res->status);
  3063. }
  3064. TEST_F(ServerTest, NoMultipleHeaders) {
  3065. Headers headers = {{"Content-Length", "5"}};
  3066. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3067. "text/plain");
  3068. ASSERT_TRUE(res);
  3069. EXPECT_EQ(200, res->status);
  3070. }
  3071. TEST_F(ServerTest, PostContentReceiver) {
  3072. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3073. ASSERT_TRUE(res);
  3074. ASSERT_EQ(200, res->status);
  3075. ASSERT_EQ("content", res->body);
  3076. }
  3077. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3078. MultipartFormDataItems items = {
  3079. {"text1", "text default", "", ""},
  3080. {"text2", "aωb", "", ""},
  3081. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3082. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3083. {"file3", "", "", "application/octet-stream"},
  3084. };
  3085. auto res = cli_.Post("/content_receiver", items);
  3086. ASSERT_TRUE(res);
  3087. EXPECT_EQ(200, res->status);
  3088. }
  3089. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3090. MultipartFormDataItems items = {
  3091. {"text1", "text default", "", ""},
  3092. {"text2", "aωb", "", ""},
  3093. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3094. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3095. {"file3", "", "", "application/octet-stream"},
  3096. };
  3097. auto boundary = std::string("+++++");
  3098. std::string body;
  3099. for (const auto &item : items) {
  3100. body += "--" + boundary + "\r\n";
  3101. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3102. if (!item.filename.empty()) {
  3103. body += "; filename=\"" + item.filename + "\"";
  3104. }
  3105. body += "\r\n";
  3106. if (!item.content_type.empty()) {
  3107. body += "Content-Type: " + item.content_type + "\r\n";
  3108. }
  3109. body += "\r\n";
  3110. body += item.content + "\r\n";
  3111. }
  3112. body += "--" + boundary + "--\r\n";
  3113. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3114. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3115. ASSERT_TRUE(res);
  3116. EXPECT_EQ(200, res->status);
  3117. }
  3118. TEST_F(ServerTest, PostContentReceiverGzip) {
  3119. cli_.set_compress(true);
  3120. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3121. ASSERT_TRUE(res);
  3122. ASSERT_EQ(200, res->status);
  3123. ASSERT_EQ("content", res->body);
  3124. }
  3125. TEST_F(ServerTest, PutContentReceiver) {
  3126. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3127. ASSERT_TRUE(res);
  3128. ASSERT_EQ(200, res->status);
  3129. ASSERT_EQ("content", res->body);
  3130. }
  3131. TEST_F(ServerTest, PatchContentReceiver) {
  3132. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3133. ASSERT_TRUE(res);
  3134. ASSERT_EQ(200, res->status);
  3135. ASSERT_EQ("content", res->body);
  3136. }
  3137. TEST_F(ServerTest, PostQueryStringAndBody) {
  3138. auto res =
  3139. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3140. ASSERT_TRUE(res);
  3141. ASSERT_EQ(200, res->status);
  3142. }
  3143. TEST_F(ServerTest, HTTP2Magic) {
  3144. Request req;
  3145. req.method = "PRI";
  3146. req.path = "*";
  3147. req.body = "SM";
  3148. auto res = std::make_shared<Response>();
  3149. auto error = Error::Success;
  3150. auto ret = cli_.send(req, *res, error);
  3151. ASSERT_TRUE(ret);
  3152. EXPECT_EQ(400, res->status);
  3153. }
  3154. TEST_F(ServerTest, KeepAlive) {
  3155. auto 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("/hi");
  3161. ASSERT_TRUE(res);
  3162. EXPECT_EQ(200, res->status);
  3163. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3164. EXPECT_EQ("Hello World!", res->body);
  3165. res = cli_.Get("/hi");
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(200, res->status);
  3168. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3169. EXPECT_EQ("Hello World!", res->body);
  3170. res = cli_.Get("/not-exist");
  3171. ASSERT_TRUE(res);
  3172. EXPECT_EQ(404, res->status);
  3173. res = cli_.Post("/empty", "", "text/plain");
  3174. ASSERT_TRUE(res);
  3175. EXPECT_EQ(200, res->status);
  3176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3177. EXPECT_EQ("empty", res->body);
  3178. EXPECT_EQ("close", res->get_header_value("Connection"));
  3179. res = cli_.Post(
  3180. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3181. "text/plain");
  3182. ASSERT_TRUE(res);
  3183. EXPECT_EQ(200, res->status);
  3184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3185. EXPECT_EQ("empty", res->body);
  3186. cli_.set_keep_alive(false);
  3187. res = cli_.Get("/last-request");
  3188. ASSERT_TRUE(res);
  3189. EXPECT_EQ(200, res->status);
  3190. EXPECT_EQ("close", res->get_header_value("Connection"));
  3191. }
  3192. TEST_F(ServerTest, TooManyRedirect) {
  3193. cli_.set_follow_location(true);
  3194. auto res = cli_.Get("/redirect/0");
  3195. ASSERT_TRUE(!res);
  3196. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3197. }
  3198. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3199. TEST_F(ServerTest, Gzip) {
  3200. Headers headers;
  3201. headers.emplace("Accept-Encoding", "gzip, deflate");
  3202. auto res = cli_.Get("/compress", headers);
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3206. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3207. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3208. "7890123456789012345678901234567890",
  3209. res->body);
  3210. EXPECT_EQ(200, res->status);
  3211. }
  3212. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3213. auto res = cli_.Get("/compress");
  3214. ASSERT_TRUE(res);
  3215. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3217. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3218. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3219. "7890123456789012345678901234567890",
  3220. res->body);
  3221. EXPECT_EQ(200, res->status);
  3222. }
  3223. TEST_F(ServerTest, GzipWithContentReceiver) {
  3224. Headers headers;
  3225. headers.emplace("Accept-Encoding", "gzip, deflate");
  3226. std::string body;
  3227. auto res = cli_.Get("/compress", headers,
  3228. [&](const char *data, uint64_t data_length) {
  3229. EXPECT_EQ(100U, data_length);
  3230. body.append(data, data_length);
  3231. return true;
  3232. });
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3236. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3237. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3238. "7890123456789012345678901234567890",
  3239. body);
  3240. EXPECT_EQ(200, res->status);
  3241. }
  3242. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3243. Headers headers;
  3244. headers.emplace("Accept-Encoding", "gzip, deflate");
  3245. cli_.set_decompress(false);
  3246. auto res = cli_.Get("/compress", headers);
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3249. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3250. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3251. EXPECT_EQ(33U, res->body.size());
  3252. EXPECT_EQ(200, res->status);
  3253. }
  3254. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3255. std::string body;
  3256. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3257. EXPECT_EQ(100U, data_length);
  3258. body.append(data, data_length);
  3259. return true;
  3260. });
  3261. ASSERT_TRUE(res);
  3262. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3263. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3264. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3265. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3266. "7890123456789012345678901234567890",
  3267. body);
  3268. EXPECT_EQ(200, res->status);
  3269. }
  3270. TEST_F(ServerTest, NoGzip) {
  3271. Headers headers;
  3272. headers.emplace("Accept-Encoding", "gzip, deflate");
  3273. auto res = cli_.Get("/nocompress", headers);
  3274. ASSERT_TRUE(res);
  3275. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3276. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3277. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3278. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3279. "7890123456789012345678901234567890",
  3280. res->body);
  3281. EXPECT_EQ(200, res->status);
  3282. }
  3283. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3284. Headers headers;
  3285. headers.emplace("Accept-Encoding", "gzip, deflate");
  3286. std::string body;
  3287. auto res = cli_.Get("/nocompress", headers,
  3288. [&](const char *data, uint64_t data_length) {
  3289. EXPECT_EQ(100U, data_length);
  3290. body.append(data, data_length);
  3291. return true;
  3292. });
  3293. ASSERT_TRUE(res);
  3294. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3295. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3296. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3297. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3298. "7890123456789012345678901234567890",
  3299. body);
  3300. EXPECT_EQ(200, res->status);
  3301. }
  3302. TEST_F(ServerTest, MultipartFormDataGzip) {
  3303. MultipartFormDataItems items = {
  3304. {"key1", "test", "", ""},
  3305. {"key2", "--abcdefg123", "", ""},
  3306. };
  3307. cli_.set_compress(true);
  3308. auto res = cli_.Post("/compress-multipart", items);
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(200, res->status);
  3311. }
  3312. #endif
  3313. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3314. TEST_F(ServerTest, Brotli) {
  3315. Headers headers;
  3316. headers.emplace("Accept-Encoding", "br");
  3317. auto res = cli_.Get("/compress", headers);
  3318. ASSERT_TRUE(res);
  3319. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3321. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3323. "7890123456789012345678901234567890",
  3324. res->body);
  3325. EXPECT_EQ(200, res->status);
  3326. }
  3327. #endif
  3328. // Sends a raw request to a server listening at HOST:PORT.
  3329. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3330. std::string *resp = nullptr) {
  3331. auto error = Error::Success;
  3332. auto client_sock = detail::create_client_socket(
  3333. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3334. /*connection_timeout_sec=*/5, 0,
  3335. /*read_timeout_sec=*/5, 0,
  3336. /*write_timeout_sec=*/5, 0, std::string(), error);
  3337. if (client_sock == INVALID_SOCKET) { return false; }
  3338. auto ret = detail::process_client_socket(
  3339. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3340. if (req.size() !=
  3341. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3342. return false;
  3343. }
  3344. char buf[512];
  3345. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3346. while (line_reader.getline()) {
  3347. if (resp) { *resp += line_reader.ptr(); }
  3348. }
  3349. return true;
  3350. });
  3351. detail::close_socket(client_sock);
  3352. return ret;
  3353. }
  3354. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3355. Server svr;
  3356. std::string header_value;
  3357. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3358. header_value = req.get_header_value("foo");
  3359. res.set_content("ok", "text/plain");
  3360. });
  3361. thread t = thread([&] { svr.listen(HOST, PORT); });
  3362. auto se = detail::scope_exit([&] {
  3363. svr.stop();
  3364. t.join();
  3365. ASSERT_FALSE(svr.is_running());
  3366. });
  3367. svr.wait_until_ready();
  3368. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3369. // like characters are not treated the same - use vertical tab and escape.
  3370. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3371. "foo: \t \v bar \x1B\t \r\n"
  3372. "Connection: close\r\n"
  3373. "\r\n";
  3374. ASSERT_TRUE(send_request(5, req));
  3375. EXPECT_EQ(header_value, "\v bar \x1B");
  3376. }
  3377. // Sends a raw request and verifies that there isn't a crash or exception.
  3378. static void test_raw_request(const std::string &req,
  3379. std::string *out = nullptr) {
  3380. Server svr;
  3381. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3382. res.set_content("ok", "text/plain");
  3383. });
  3384. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3385. res.set_content("ok", "text/plain");
  3386. });
  3387. // Server read timeout must be longer than the client read timeout for the
  3388. // bug to reproduce, probably to force the server to process a request
  3389. // without a trailing blank line.
  3390. const time_t client_read_timeout_sec = 1;
  3391. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3392. bool listen_thread_ok = false;
  3393. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3394. auto se = detail::scope_exit([&] {
  3395. svr.stop();
  3396. t.join();
  3397. ASSERT_FALSE(svr.is_running());
  3398. EXPECT_TRUE(listen_thread_ok);
  3399. });
  3400. svr.wait_until_ready();
  3401. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3402. }
  3403. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3404. // A certain header line causes an exception if the header property is parsed
  3405. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3406. test_raw_request(
  3407. "GET /hi HTTP/1.1\r\n"
  3408. " : "
  3409. " "
  3410. " ");
  3411. }
  3412. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3413. // A certain header line causes an exception if the header property *name* is
  3414. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3415. // greedy matcher and requires backtracking when there are a lot of ":"
  3416. // characters.
  3417. // This occurs with libc++ but not libstdc++.
  3418. test_raw_request(
  3419. "GET /hi HTTP/1.1\r\n"
  3420. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3421. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3422. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3423. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3424. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3425. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3426. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3427. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3428. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3429. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3430. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3431. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3432. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3433. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3434. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3435. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3436. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3437. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3438. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3439. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3440. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3441. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3442. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3443. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3444. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3445. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3446. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3447. "&&&%%%");
  3448. }
  3449. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3450. // Make sure this doesn't crash the server.
  3451. // In a previous version of the header line regex, the "\r" rendered the line
  3452. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3453. // a new position where the leading white space ended and the field value
  3454. // began.
  3455. // The crash occurs with libc++ but not libstdc++.
  3456. test_raw_request("GET /hi HTTP/1.1\r\n"
  3457. "a:" +
  3458. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3459. "\r\n"
  3460. "\r\n");
  3461. }
  3462. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  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. "nothex\r\n",
  3469. &out);
  3470. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3471. }
  3472. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3473. std::string out;
  3474. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3475. "Content-Type: text/plain\r\n"
  3476. "Transfer-Encoding: chunked\r\n"
  3477. "\r\n"
  3478. "3\r\n"
  3479. "xyz\r\n"
  3480. "NaN\r\n",
  3481. &out);
  3482. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3483. }
  3484. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3485. std::string out;
  3486. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3487. "Content-Type: text/plain\r\n"
  3488. "Transfer-Encoding: chunked\r\n"
  3489. "\r\n"
  3490. // Length is too large for 64 bits.
  3491. "1ffffffffffffffff\r\n"
  3492. "xyz\r\n",
  3493. &out);
  3494. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3495. }
  3496. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3497. test_raw_request("GET /hi HTTP/1.1\r\n"
  3498. "Content-Type: text/plain\r\n\r");
  3499. }
  3500. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3501. std::string out;
  3502. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3503. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3504. }
  3505. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3506. Server svr;
  3507. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3508. res.set_header("Cache-Control", "no-cache");
  3509. res.set_chunked_content_provider(
  3510. "text/event-stream", [](size_t offset, DataSink &sink) {
  3511. std::string s = "data:";
  3512. s += std::to_string(offset);
  3513. s += "\n\n";
  3514. auto ret = sink.write(s.data(), s.size());
  3515. EXPECT_TRUE(ret);
  3516. std::this_thread::sleep_for(std::chrono::seconds(1));
  3517. return true;
  3518. });
  3519. });
  3520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3521. svr.wait_until_ready();
  3522. Client client(HOST, PORT);
  3523. const Headers headers = {{"Accept", "text/event-stream"}};
  3524. auto get_thread = std::thread([&client, &headers]() {
  3525. auto res = client.Get(
  3526. "/events", headers,
  3527. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3528. });
  3529. auto se = detail::scope_exit([&] {
  3530. svr.stop();
  3531. get_thread.join();
  3532. listen_thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. // Give GET time to get a few messages.
  3536. std::this_thread::sleep_for(std::chrono::seconds(2));
  3537. }
  3538. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3539. httplib::Server svr;
  3540. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3541. httplib::Response &res) { res.status = 200; });
  3542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3543. svr.wait_until_ready();
  3544. Client cli(HOST, PORT);
  3545. auto res = cli.Post("/hi", "data", "text/plain");
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(200, res->status);
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. res = cli.Post("/hi", "data", "text/plain");
  3552. ASSERT_FALSE(res);
  3553. }
  3554. TEST(ServerStopTest, ListenFailure) {
  3555. Server svr;
  3556. auto t = thread([&]() {
  3557. auto ret = svr.listen("????", PORT);
  3558. EXPECT_FALSE(ret);
  3559. });
  3560. svr.wait_until_ready();
  3561. svr.stop();
  3562. t.join();
  3563. }
  3564. TEST(StreamingTest, NoContentLengthStreaming) {
  3565. Server svr;
  3566. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3567. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3568. if (offset < 6) {
  3569. sink.os << (offset < 3 ? "a" : "b");
  3570. } else {
  3571. sink.done();
  3572. }
  3573. return true;
  3574. });
  3575. });
  3576. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3577. auto listen_se = detail::scope_exit([&] {
  3578. svr.stop();
  3579. listen_thread.join();
  3580. ASSERT_FALSE(svr.is_running());
  3581. });
  3582. svr.wait_until_ready();
  3583. Client client(HOST, PORT);
  3584. auto get_thread = std::thread([&client]() {
  3585. std::string s;
  3586. auto res =
  3587. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3588. s += std::string(data, len);
  3589. return true;
  3590. });
  3591. EXPECT_EQ("aaabbb", s);
  3592. });
  3593. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3594. // Give GET time to get a few messages.
  3595. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3596. }
  3597. TEST(MountTest, Unmount) {
  3598. Server svr;
  3599. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3600. auto se = detail::scope_exit([&] {
  3601. svr.stop();
  3602. listen_thread.join();
  3603. ASSERT_FALSE(svr.is_running());
  3604. });
  3605. svr.wait_until_ready();
  3606. Client cli("localhost", PORT);
  3607. svr.set_mount_point("/mount2", "./www2");
  3608. auto res = cli.Get("/");
  3609. ASSERT_TRUE(res);
  3610. EXPECT_EQ(404, res->status);
  3611. res = cli.Get("/mount2/dir/test.html");
  3612. ASSERT_TRUE(res);
  3613. EXPECT_EQ(200, res->status);
  3614. svr.set_mount_point("/", "./www");
  3615. res = cli.Get("/dir/");
  3616. ASSERT_TRUE(res);
  3617. EXPECT_EQ(200, res->status);
  3618. svr.remove_mount_point("/");
  3619. res = cli.Get("/dir/");
  3620. ASSERT_TRUE(res);
  3621. EXPECT_EQ(404, res->status);
  3622. svr.remove_mount_point("/mount2");
  3623. res = cli.Get("/mount2/dir/test.html");
  3624. ASSERT_TRUE(res);
  3625. EXPECT_EQ(404, res->status);
  3626. }
  3627. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3628. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3629. Server svr;
  3630. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3631. throw std::runtime_error("exception...");
  3632. });
  3633. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3634. throw std::runtime_error("exception\r\n...");
  3635. });
  3636. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3637. auto se = detail::scope_exit([&] {
  3638. svr.stop();
  3639. listen_thread.join();
  3640. ASSERT_FALSE(svr.is_running());
  3641. });
  3642. svr.wait_until_ready();
  3643. Client cli("localhost", PORT);
  3644. {
  3645. auto res = cli.Get("/exception");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(500, res->status);
  3648. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3649. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3650. }
  3651. {
  3652. auto res = cli.Get("/unknown");
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(500, res->status);
  3655. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3656. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3657. }
  3658. }
  3659. #endif
  3660. TEST(KeepAliveTest, ReadTimeout) {
  3661. Server svr;
  3662. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3663. std::this_thread::sleep_for(std::chrono::seconds(2));
  3664. res.set_content("a", "text/plain");
  3665. });
  3666. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3667. res.set_content("b", "text/plain");
  3668. });
  3669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3670. auto se = detail::scope_exit([&] {
  3671. svr.stop();
  3672. listen_thread.join();
  3673. ASSERT_FALSE(svr.is_running());
  3674. });
  3675. svr.wait_until_ready();
  3676. Client cli("localhost", PORT);
  3677. cli.set_keep_alive(true);
  3678. cli.set_read_timeout(std::chrono::seconds(1));
  3679. auto resa = cli.Get("/a");
  3680. ASSERT_FALSE(resa);
  3681. EXPECT_EQ(Error::Read, resa.error());
  3682. auto resb = cli.Get("/b");
  3683. ASSERT_TRUE(resb);
  3684. EXPECT_EQ(200, resb->status);
  3685. EXPECT_EQ("b", resb->body);
  3686. }
  3687. TEST(KeepAliveTest, Issue1041) {
  3688. Server svr;
  3689. svr.set_keep_alive_timeout(3);
  3690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3691. res.set_content("Hello World!", "text/plain");
  3692. });
  3693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3694. auto se = detail::scope_exit([&] {
  3695. svr.stop();
  3696. listen_thread.join();
  3697. ASSERT_FALSE(svr.is_running());
  3698. });
  3699. svr.wait_until_ready();
  3700. Client cli(HOST, PORT);
  3701. cli.set_keep_alive(true);
  3702. auto result = cli.Get("/hi");
  3703. ASSERT_TRUE(result);
  3704. EXPECT_EQ(200, result->status);
  3705. std::this_thread::sleep_for(std::chrono::seconds(5));
  3706. result = cli.Get("/hi");
  3707. ASSERT_TRUE(result);
  3708. EXPECT_EQ(200, result->status);
  3709. }
  3710. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3711. TEST(KeepAliveTest, SSLClientReconnection) {
  3712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3713. ASSERT_TRUE(svr.is_valid());
  3714. svr.set_keep_alive_timeout(1);
  3715. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3716. res.set_content("Hello World!", "text/plain");
  3717. });
  3718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3719. auto se = detail::scope_exit([&] {
  3720. svr.stop();
  3721. listen_thread.join();
  3722. ASSERT_FALSE(svr.is_running());
  3723. });
  3724. svr.wait_until_ready();
  3725. SSLClient cli(HOST, PORT);
  3726. cli.enable_server_certificate_verification(false);
  3727. cli.set_keep_alive(true);
  3728. auto result = cli.Get("/hi");
  3729. ASSERT_TRUE(result);
  3730. EXPECT_EQ(200, result->status);
  3731. result = cli.Get("/hi");
  3732. ASSERT_TRUE(result);
  3733. EXPECT_EQ(200, result->status);
  3734. std::this_thread::sleep_for(std::chrono::seconds(2));
  3735. // Recoonect
  3736. result = cli.Get("/hi");
  3737. ASSERT_TRUE(result);
  3738. EXPECT_EQ(200, result->status);
  3739. result = cli.Get("/hi");
  3740. ASSERT_TRUE(result);
  3741. EXPECT_EQ(200, result->status);
  3742. }
  3743. #endif
  3744. TEST(ClientProblemDetectionTest, ContentProvider) {
  3745. Server svr;
  3746. size_t content_length = 1024 * 1024;
  3747. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3748. res.set_content_provider(
  3749. content_length, "text/plain",
  3750. [&](size_t offset, size_t length, DataSink &sink) {
  3751. auto out_len = std::min(length, static_cast<size_t>(1024));
  3752. std::string out(out_len, '@');
  3753. sink.write(out.data(), out_len);
  3754. return offset < 4096;
  3755. },
  3756. [](bool success) { ASSERT_FALSE(success); });
  3757. });
  3758. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3759. res.set_content_provider(
  3760. 0, "text/plain",
  3761. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3762. EXPECT_TRUE(false);
  3763. return true;
  3764. },
  3765. [](bool success) { ASSERT_FALSE(success); });
  3766. });
  3767. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3768. auto se = detail::scope_exit([&] {
  3769. svr.stop();
  3770. listen_thread.join();
  3771. ASSERT_FALSE(svr.is_running());
  3772. });
  3773. svr.wait_until_ready();
  3774. Client cli("localhost", PORT);
  3775. {
  3776. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3777. size_t /*data_length*/) { return false; });
  3778. ASSERT_FALSE(res);
  3779. }
  3780. {
  3781. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3782. size_t /*data_length*/) { return false; });
  3783. ASSERT_TRUE(res);
  3784. }
  3785. }
  3786. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3787. Server svr;
  3788. svr.set_error_handler([](Request const &, Response &res) -> void {
  3789. res.set_chunked_content_provider(
  3790. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3791. sink.os << "hello";
  3792. sink.os << "world";
  3793. sink.done();
  3794. return true;
  3795. });
  3796. });
  3797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3798. auto se = detail::scope_exit([&] {
  3799. svr.stop();
  3800. listen_thread.join();
  3801. ASSERT_FALSE(svr.is_running());
  3802. });
  3803. svr.wait_until_ready();
  3804. Client cli("localhost", PORT);
  3805. auto res = cli.Get("/");
  3806. ASSERT_TRUE(res);
  3807. EXPECT_EQ(404, res->status);
  3808. EXPECT_EQ("helloworld", res->body);
  3809. }
  3810. TEST(LongPollingTest, ClientCloseDetection) {
  3811. Server svr;
  3812. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  3813. res.set_chunked_content_provider(
  3814. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3815. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  3816. sink.os << "hello";
  3817. auto count = 10;
  3818. while (count > 0 && sink.is_writable()) {
  3819. this_thread::sleep_for(chrono::milliseconds(10));
  3820. }
  3821. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  3822. return true;
  3823. });
  3824. });
  3825. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3826. auto se = detail::scope_exit([&] {
  3827. svr.stop();
  3828. listen_thread.join();
  3829. ASSERT_FALSE(svr.is_running());
  3830. });
  3831. svr.wait_until_ready();
  3832. Client cli("localhost", PORT);
  3833. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  3834. EXPECT_EQ("hello", string(data, data_length));
  3835. return false; // close the socket immediately.
  3836. });
  3837. ASSERT_FALSE(res);
  3838. }
  3839. TEST(GetWithParametersTest, GetWithParameters) {
  3840. Server svr;
  3841. svr.Get("/", [&](const Request &req, Response &) {
  3842. EXPECT_EQ("world", req.get_param_value("hello"));
  3843. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3844. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3845. });
  3846. svr.Get("/params", [&](const Request &req, Response &) {
  3847. EXPECT_EQ("world", req.get_param_value("hello"));
  3848. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3849. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3850. });
  3851. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3852. EXPECT_EQ("resource-id", req.matches[1]);
  3853. EXPECT_EQ("foo", req.get_param_value("param1"));
  3854. EXPECT_EQ("bar", req.get_param_value("param2"));
  3855. });
  3856. svr.Get("/users/:id", [&](const Request &req, Response &) {
  3857. EXPECT_EQ("user-id", req.path_params.at("id"));
  3858. EXPECT_EQ("foo", req.get_param_value("param1"));
  3859. EXPECT_EQ("bar", req.get_param_value("param2"));
  3860. });
  3861. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3862. auto se = detail::scope_exit([&] {
  3863. svr.stop();
  3864. listen_thread.join();
  3865. ASSERT_FALSE(svr.is_running());
  3866. });
  3867. svr.wait_until_ready();
  3868. {
  3869. Client cli(HOST, PORT);
  3870. Params params;
  3871. params.emplace("hello", "world");
  3872. params.emplace("hello2", "world2");
  3873. params.emplace("hello3", "world3");
  3874. auto res = cli.Get("/", params, Headers{});
  3875. ASSERT_TRUE(res);
  3876. EXPECT_EQ(200, res->status);
  3877. }
  3878. {
  3879. Client cli(HOST, PORT);
  3880. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(200, res->status);
  3883. }
  3884. {
  3885. Client cli(HOST, PORT);
  3886. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(200, res->status);
  3889. }
  3890. {
  3891. Client cli(HOST, PORT);
  3892. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(200, res->status);
  3895. }
  3896. }
  3897. TEST(GetWithParametersTest, GetWithParameters2) {
  3898. Server svr;
  3899. svr.Get("/", [&](const Request &req, Response &res) {
  3900. auto text = req.get_param_value("hello");
  3901. res.set_content(text, "text/plain");
  3902. });
  3903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3904. auto se = detail::scope_exit([&] {
  3905. svr.stop();
  3906. listen_thread.join();
  3907. ASSERT_FALSE(svr.is_running());
  3908. });
  3909. svr.wait_until_ready();
  3910. Client cli("localhost", PORT);
  3911. Params params;
  3912. params.emplace("hello", "world");
  3913. std::string body;
  3914. auto res = cli.Get("/", params, Headers{},
  3915. [&](const char *data, size_t data_length) {
  3916. body.append(data, data_length);
  3917. return true;
  3918. });
  3919. ASSERT_TRUE(res);
  3920. EXPECT_EQ(200, res->status);
  3921. EXPECT_EQ("world", body);
  3922. }
  3923. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3924. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  3925. auto host = "httpbin.org";
  3926. auto path = std::string{"/range/32"};
  3927. #else
  3928. auto host = "nghttp2.org";
  3929. auto path = std::string{"/httpbin/range/32"};
  3930. #endif
  3931. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3932. SSLClient cli(host);
  3933. #else
  3934. Client cli(host);
  3935. #endif
  3936. cli.set_default_headers({make_range_header({{1, 10}})});
  3937. cli.set_connection_timeout(5);
  3938. {
  3939. auto res = cli.Get(path);
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ("bcdefghijk", res->body);
  3942. EXPECT_EQ(206, res->status);
  3943. }
  3944. {
  3945. auto res = cli.Get(path);
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ("bcdefghijk", res->body);
  3948. EXPECT_EQ(206, res->status);
  3949. }
  3950. }
  3951. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3952. Server svr;
  3953. svr.set_default_headers({{"Hello", "World"}});
  3954. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3955. res.set_content("ok", "text/plain");
  3956. });
  3957. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3958. auto se = detail::scope_exit([&] {
  3959. svr.stop();
  3960. listen_thread.join();
  3961. ASSERT_FALSE(svr.is_running());
  3962. });
  3963. svr.wait_until_ready();
  3964. Client cli("localhost", PORT);
  3965. auto res = cli.Get("/");
  3966. ASSERT_TRUE(res);
  3967. EXPECT_EQ(200, res->status);
  3968. EXPECT_EQ("ok", res->body);
  3969. EXPECT_EQ("World", res->get_header_value("Hello"));
  3970. }
  3971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3972. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3974. ASSERT_TRUE(svr.is_valid());
  3975. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3976. std::this_thread::sleep_for(std::chrono::seconds(2));
  3977. res.set_content("a", "text/plain");
  3978. });
  3979. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3980. res.set_content("b", "text/plain");
  3981. });
  3982. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3983. auto se = detail::scope_exit([&] {
  3984. svr.stop();
  3985. listen_thread.join();
  3986. ASSERT_FALSE(svr.is_running());
  3987. });
  3988. svr.wait_until_ready();
  3989. SSLClient cli("localhost", PORT);
  3990. cli.enable_server_certificate_verification(false);
  3991. cli.set_keep_alive(true);
  3992. cli.set_read_timeout(std::chrono::seconds(1));
  3993. auto resa = cli.Get("/a");
  3994. ASSERT_TRUE(!resa);
  3995. EXPECT_EQ(Error::Read, resa.error());
  3996. auto resb = cli.Get("/b");
  3997. ASSERT_TRUE(resb);
  3998. EXPECT_EQ(200, resb->status);
  3999. EXPECT_EQ("b", resb->body);
  4000. }
  4001. #endif
  4002. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4003. protected:
  4004. ServerTestWithAI_PASSIVE()
  4005. : cli_(HOST, PORT)
  4006. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4007. ,
  4008. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4009. #endif
  4010. {
  4011. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4012. cli_.enable_server_certificate_verification(false);
  4013. #endif
  4014. }
  4015. virtual void SetUp() {
  4016. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4017. res.set_content("Hello World!", "text/plain");
  4018. });
  4019. t_ = thread(
  4020. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4021. svr_.wait_until_ready();
  4022. }
  4023. virtual void TearDown() {
  4024. svr_.stop();
  4025. t_.join();
  4026. }
  4027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4028. SSLClient cli_;
  4029. SSLServer svr_;
  4030. #else
  4031. Client cli_;
  4032. Server svr_;
  4033. #endif
  4034. thread t_;
  4035. };
  4036. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4037. auto res = cli_.Get("/hi");
  4038. ASSERT_TRUE(res);
  4039. EXPECT_EQ(200, res->status);
  4040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4041. EXPECT_EQ("Hello World!", res->body);
  4042. }
  4043. class ServerUpDownTest : public ::testing::Test {
  4044. protected:
  4045. ServerUpDownTest() : cli_(HOST, PORT) {}
  4046. virtual void SetUp() {
  4047. t_ = thread([&]() {
  4048. svr_.bind_to_any_port(HOST);
  4049. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4050. ASSERT_TRUE(svr_.listen_after_bind());
  4051. });
  4052. svr_.wait_until_ready();
  4053. }
  4054. virtual void TearDown() {
  4055. svr_.stop();
  4056. t_.join();
  4057. }
  4058. Client cli_;
  4059. Server svr_;
  4060. thread t_;
  4061. };
  4062. TEST_F(ServerUpDownTest, QuickStartStop) {
  4063. // Should not crash, especially when run with
  4064. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4065. }
  4066. class PayloadMaxLengthTest : public ::testing::Test {
  4067. protected:
  4068. PayloadMaxLengthTest()
  4069. : cli_(HOST, PORT)
  4070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4071. ,
  4072. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4073. #endif
  4074. {
  4075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4076. cli_.enable_server_certificate_verification(false);
  4077. #endif
  4078. }
  4079. virtual void SetUp() {
  4080. svr_.set_payload_max_length(8);
  4081. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4082. res.set_content("test", "text/plain");
  4083. });
  4084. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4085. svr_.wait_until_ready();
  4086. }
  4087. virtual void TearDown() {
  4088. svr_.stop();
  4089. t_.join();
  4090. }
  4091. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4092. SSLClient cli_;
  4093. SSLServer svr_;
  4094. #else
  4095. Client cli_;
  4096. Server svr_;
  4097. #endif
  4098. thread t_;
  4099. };
  4100. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4101. auto res = cli_.Post("/test", "123456789", "text/plain");
  4102. ASSERT_TRUE(res);
  4103. EXPECT_EQ(413, res->status);
  4104. res = cli_.Post("/test", "12345678", "text/plain");
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(200, res->status);
  4107. }
  4108. TEST(HostAndPortPropertiesTest, NoSSL) {
  4109. httplib::Client cli("www.google.com", 1234);
  4110. ASSERT_EQ("www.google.com", cli.host());
  4111. ASSERT_EQ(1234, cli.port());
  4112. }
  4113. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4114. httplib::Client cli("www.google.com:1234");
  4115. ASSERT_EQ("www.google.com", cli.host());
  4116. ASSERT_EQ(1234, cli.port());
  4117. }
  4118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4119. TEST(HostAndPortPropertiesTest, SSL) {
  4120. httplib::SSLClient cli("www.google.com");
  4121. ASSERT_EQ("www.google.com", cli.host());
  4122. ASSERT_EQ(443, cli.port());
  4123. }
  4124. #endif
  4125. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4126. TEST(SSLClientTest, UpdateCAStore) {
  4127. httplib::SSLClient httplib_client("www.google.com");
  4128. auto ca_store_1 = X509_STORE_new();
  4129. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4130. nullptr);
  4131. httplib_client.set_ca_cert_store(ca_store_1);
  4132. auto ca_store_2 = X509_STORE_new();
  4133. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4134. nullptr);
  4135. httplib_client.set_ca_cert_store(ca_store_2);
  4136. }
  4137. TEST(SSLClientTest, ServerNameIndication_Online) {
  4138. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4139. auto host = "httpbin.org";
  4140. auto path = std::string{"/get"};
  4141. #else
  4142. auto host = "nghttp2.org";
  4143. auto path = std::string{"/httpbin/get"};
  4144. #endif
  4145. SSLClient cli(host, 443);
  4146. auto res = cli.Get(path);
  4147. ASSERT_TRUE(res);
  4148. ASSERT_EQ(200, res->status);
  4149. }
  4150. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4151. Client cli("https://google.com");
  4152. auto res = cli.Get("/");
  4153. ASSERT_TRUE(res);
  4154. ASSERT_EQ(301, res->status);
  4155. }
  4156. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4157. SSLClient cli("google.com");
  4158. cli.enable_server_certificate_verification(true);
  4159. cli.set_ca_cert_path("hello");
  4160. auto res = cli.Get("/");
  4161. ASSERT_TRUE(!res);
  4162. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4163. }
  4164. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4165. SSLClient cli("google.com");
  4166. cli.set_ca_cert_path(CA_CERT_FILE);
  4167. auto res = cli.Get("/");
  4168. ASSERT_TRUE(res);
  4169. ASSERT_EQ(301, res->status);
  4170. }
  4171. TEST(SSLClientTest, ServerCertificateVerification4) {
  4172. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4173. ASSERT_TRUE(svr.is_valid());
  4174. svr.Get("/test", [&](const Request &, Response &res) {
  4175. res.set_content("test", "text/plain");
  4176. svr.stop();
  4177. ASSERT_TRUE(true);
  4178. });
  4179. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4180. auto se = detail::scope_exit([&] {
  4181. t.join();
  4182. ASSERT_FALSE(svr.is_running());
  4183. });
  4184. svr.wait_until_ready();
  4185. SSLClient cli("127.0.0.1", PORT);
  4186. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4187. cli.enable_server_certificate_verification(true);
  4188. cli.set_connection_timeout(30);
  4189. auto res = cli.Get("/test");
  4190. ASSERT_TRUE(res);
  4191. ASSERT_EQ(200, res->status);
  4192. }
  4193. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4194. std::string cert;
  4195. detail::read_file(CA_CERT_FILE, cert);
  4196. SSLClient cli("google.com");
  4197. cli.load_ca_cert_store(cert.data(), cert.size());
  4198. const auto res = cli.Get("/");
  4199. ASSERT_TRUE(res);
  4200. ASSERT_EQ(301, res->status);
  4201. }
  4202. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4203. // clang-format off
  4204. static constexpr char cert[] =
  4205. "GlobalSign Root CA\n"
  4206. "==================\n"
  4207. "-----BEGIN CERTIFICATE-----\n"
  4208. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4209. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4210. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4211. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4212. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4213. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4214. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4215. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4216. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4217. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4218. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4219. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4220. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4221. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4222. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4223. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4224. "-----END CERTIFICATE-----\n";
  4225. // clang-format on
  4226. SSLClient cli("google.com");
  4227. cli.load_ca_cert_store(cert, sizeof(cert));
  4228. const auto res = cli.Get("/");
  4229. ASSERT_TRUE(res);
  4230. ASSERT_EQ(301, res->status);
  4231. }
  4232. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4233. SSLClient cli("www.youtube.com");
  4234. cli.set_ca_cert_path(CA_CERT_FILE);
  4235. cli.enable_server_certificate_verification(true);
  4236. cli.set_follow_location(true);
  4237. auto res = cli.Get("/");
  4238. ASSERT_TRUE(res);
  4239. ASSERT_EQ(200, res->status);
  4240. }
  4241. #if 0
  4242. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4243. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4244. ASSERT_TRUE(cli != nullptr);
  4245. cli->set_address_family(AF_INET6);
  4246. cli->set_interface("en0");
  4247. auto res = cli->Get("/get");
  4248. ASSERT_TRUE(res);
  4249. ASSERT_EQ(200, res->status);
  4250. }
  4251. #endif
  4252. TEST(SSLClientServerTest, ClientCertPresent) {
  4253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4254. CLIENT_CA_CERT_DIR);
  4255. ASSERT_TRUE(svr.is_valid());
  4256. svr.Get("/test", [&](const Request &req, Response &res) {
  4257. res.set_content("test", "text/plain");
  4258. svr.stop();
  4259. ASSERT_TRUE(true);
  4260. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4261. ASSERT_TRUE(peer_cert != nullptr);
  4262. auto subject_name = X509_get_subject_name(peer_cert);
  4263. ASSERT_TRUE(subject_name != nullptr);
  4264. std::string common_name;
  4265. {
  4266. char name[BUFSIZ];
  4267. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4268. name, sizeof(name));
  4269. common_name.assign(name, static_cast<size_t>(name_len));
  4270. }
  4271. EXPECT_EQ("Common Name", common_name);
  4272. X509_free(peer_cert);
  4273. });
  4274. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4275. auto se = detail::scope_exit([&] {
  4276. t.join();
  4277. ASSERT_FALSE(svr.is_running());
  4278. });
  4279. svr.wait_until_ready();
  4280. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4281. cli.enable_server_certificate_verification(false);
  4282. cli.set_connection_timeout(30);
  4283. auto res = cli.Get("/test");
  4284. ASSERT_TRUE(res);
  4285. ASSERT_EQ(200, res->status);
  4286. }
  4287. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4288. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4289. X509 *server_cert;
  4290. EVP_PKEY *server_private_key;
  4291. X509_STORE *client_ca_cert_store;
  4292. X509 *client_cert;
  4293. EVP_PKEY *client_private_key;
  4294. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4295. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4296. fclose(f);
  4297. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4298. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4299. fclose(f);
  4300. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4301. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4302. client_ca_cert_store = X509_STORE_new();
  4303. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4304. X509_free(client_cert);
  4305. fclose(f);
  4306. f = fopen(CLIENT_CERT_FILE, "r+");
  4307. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4308. fclose(f);
  4309. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4310. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4311. fclose(f);
  4312. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4313. ASSERT_TRUE(svr.is_valid());
  4314. svr.Get("/test", [&](const Request &req, Response &res) {
  4315. res.set_content("test", "text/plain");
  4316. svr.stop();
  4317. ASSERT_TRUE(true);
  4318. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4319. ASSERT_TRUE(peer_cert != nullptr);
  4320. auto subject_name = X509_get_subject_name(peer_cert);
  4321. ASSERT_TRUE(subject_name != nullptr);
  4322. std::string common_name;
  4323. {
  4324. char name[BUFSIZ];
  4325. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4326. name, sizeof(name));
  4327. common_name.assign(name, static_cast<size_t>(name_len));
  4328. }
  4329. EXPECT_EQ("Common Name", common_name);
  4330. X509_free(peer_cert);
  4331. });
  4332. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4333. auto se = detail::scope_exit([&] {
  4334. t.join();
  4335. ASSERT_FALSE(svr.is_running());
  4336. });
  4337. svr.wait_until_ready();
  4338. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4339. cli.enable_server_certificate_verification(false);
  4340. cli.set_connection_timeout(30);
  4341. auto res = cli.Get("/test");
  4342. ASSERT_TRUE(res);
  4343. ASSERT_EQ(200, res->status);
  4344. X509_free(server_cert);
  4345. EVP_PKEY_free(server_private_key);
  4346. X509_free(client_cert);
  4347. EVP_PKEY_free(client_private_key);
  4348. }
  4349. #endif
  4350. TEST(SSLClientServerTest, ClientCertMissing) {
  4351. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4352. CLIENT_CA_CERT_DIR);
  4353. ASSERT_TRUE(svr.is_valid());
  4354. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. t.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. SSLClient cli(HOST, PORT);
  4363. auto res = cli.Get("/test");
  4364. cli.set_connection_timeout(30);
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4367. }
  4368. TEST(SSLClientServerTest, TrustDirOptional) {
  4369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4370. ASSERT_TRUE(svr.is_valid());
  4371. svr.Get("/test", [&](const Request &, Response &res) {
  4372. res.set_content("test", "text/plain");
  4373. svr.stop();
  4374. });
  4375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4376. auto se = detail::scope_exit([&] {
  4377. t.join();
  4378. ASSERT_FALSE(svr.is_running());
  4379. });
  4380. svr.wait_until_ready();
  4381. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4382. cli.enable_server_certificate_verification(false);
  4383. cli.set_connection_timeout(30);
  4384. auto res = cli.Get("/test");
  4385. ASSERT_TRUE(res);
  4386. ASSERT_EQ(200, res->status);
  4387. }
  4388. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4389. class NoListenSSLServer : public SSLServer {
  4390. public:
  4391. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4392. const char *client_ca_cert_file_path,
  4393. const char *client_ca_cert_dir_path = nullptr)
  4394. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4395. client_ca_cert_dir_path),
  4396. stop_(false) {}
  4397. std::atomic_bool stop_;
  4398. private:
  4399. bool process_and_close_socket(socket_t /*sock*/) override {
  4400. // Don't create SSL context
  4401. while (!stop_.load()) {
  4402. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4403. }
  4404. return true;
  4405. }
  4406. };
  4407. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4408. CLIENT_CA_CERT_FILE);
  4409. ASSERT_TRUE(svr.is_valid());
  4410. svr.Get("/test", [&](const Request &, Response &res) {
  4411. res.set_content("test", "text/plain");
  4412. });
  4413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4414. auto se = detail::scope_exit([&] {
  4415. svr.stop_ = true;
  4416. svr.stop();
  4417. t.join();
  4418. ASSERT_FALSE(svr.is_running());
  4419. });
  4420. svr.wait_until_ready();
  4421. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4422. cli.enable_server_certificate_verification(false);
  4423. cli.set_connection_timeout(1);
  4424. auto res = cli.Get("/test");
  4425. ASSERT_TRUE(!res);
  4426. EXPECT_EQ(Error::SSLConnection, res.error());
  4427. }
  4428. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4429. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4430. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4431. SSL_CTX_set_options(&ssl_ctx,
  4432. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4433. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4434. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4435. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4436. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4437. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4438. "ECDHE-DSS-AES128-SHA256:"
  4439. "ECDHE-RSA-AES256-SHA256:"
  4440. "ECDHE-DSS-AES256-SHA256:";
  4441. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4442. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4443. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4444. SSL_FILETYPE_PEM) != 1) {
  4445. return false;
  4446. }
  4447. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4448. CLIENT_CA_CERT_DIR);
  4449. SSL_CTX_set_verify(
  4450. &ssl_ctx,
  4451. SSL_VERIFY_PEER |
  4452. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4453. nullptr);
  4454. return true;
  4455. };
  4456. SSLServer svr(setup_ssl_ctx_callback);
  4457. ASSERT_TRUE(svr.is_valid());
  4458. svr.Get("/test", [&](const Request &req, Response &res) {
  4459. res.set_content("test", "text/plain");
  4460. svr.stop();
  4461. ASSERT_TRUE(true);
  4462. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4463. ASSERT_TRUE(peer_cert != nullptr);
  4464. auto subject_name = X509_get_subject_name(peer_cert);
  4465. ASSERT_TRUE(subject_name != nullptr);
  4466. std::string common_name;
  4467. {
  4468. char name[BUFSIZ];
  4469. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4470. name, sizeof(name));
  4471. common_name.assign(name, static_cast<size_t>(name_len));
  4472. }
  4473. EXPECT_EQ("Common Name", common_name);
  4474. X509_free(peer_cert);
  4475. });
  4476. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4477. auto se = detail::scope_exit([&] {
  4478. t.join();
  4479. ASSERT_FALSE(svr.is_running());
  4480. });
  4481. svr.wait_until_ready();
  4482. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4483. cli.enable_server_certificate_verification(false);
  4484. cli.set_connection_timeout(30);
  4485. auto res = cli.Get("/test");
  4486. ASSERT_TRUE(res);
  4487. ASSERT_EQ(200, res->status);
  4488. }
  4489. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4490. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4491. // prepare large data
  4492. std::random_device seed_gen;
  4493. std::mt19937 random(seed_gen());
  4494. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4495. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4496. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4497. // server
  4498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4499. ASSERT_TRUE(svr.is_valid());
  4500. svr.Post("/binary", [&](const Request &req, Response &res) {
  4501. EXPECT_EQ(large_size_byte, req.body.size());
  4502. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4503. res.set_content(req.body, "application/octet-stream");
  4504. });
  4505. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4506. auto se = detail::scope_exit([&] {
  4507. svr.stop();
  4508. listen_thread.join();
  4509. ASSERT_FALSE(svr.is_running());
  4510. });
  4511. svr.wait_until_ready();
  4512. // client POST
  4513. SSLClient cli("localhost", PORT);
  4514. cli.enable_server_certificate_verification(false);
  4515. cli.set_read_timeout(std::chrono::seconds(100));
  4516. cli.set_write_timeout(std::chrono::seconds(100));
  4517. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4518. large_size_byte, "application/octet-stream");
  4519. // compare
  4520. EXPECT_EQ(200, res->status);
  4521. EXPECT_EQ(large_size_byte, res->body.size());
  4522. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4523. }
  4524. #endif
  4525. #ifdef _WIN32
  4526. TEST(CleanupTest, WSACleanup) {
  4527. int ret = WSACleanup();
  4528. ASSERT_EQ(0, ret);
  4529. }
  4530. #endif
  4531. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4532. TEST(NoSSLSupport, SimpleInterface) {
  4533. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4534. }
  4535. #endif
  4536. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4537. TEST(InvalidScheme, SimpleInterface) {
  4538. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4539. }
  4540. #endif
  4541. TEST(NoScheme, SimpleInterface) {
  4542. Client cli("yahoo.com:80");
  4543. ASSERT_TRUE(cli.is_valid());
  4544. }
  4545. TEST(SendAPI, SimpleInterface_Online) {
  4546. Client cli("http://yahoo.com");
  4547. Request req;
  4548. req.method = "GET";
  4549. req.path = "/";
  4550. auto res = cli.send(req);
  4551. ASSERT_TRUE(res);
  4552. EXPECT_EQ(301, res->status);
  4553. }
  4554. TEST(ClientImplMethods, GetSocketTest) {
  4555. httplib::Server svr;
  4556. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4557. res.status = 200;
  4558. });
  4559. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4560. auto se = detail::scope_exit([&] {
  4561. svr.stop();
  4562. thread.join();
  4563. ASSERT_FALSE(svr.is_running());
  4564. });
  4565. svr.wait_until_ready();
  4566. {
  4567. httplib::Client cli("http://127.0.0.1:3333");
  4568. cli.set_keep_alive(true);
  4569. // Use the behavior of cpp-httplib of opening the connection
  4570. // only when the first request happens. If that changes,
  4571. // this test would be obsolete.
  4572. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4573. // This also implicitly tests the server. But other tests would fail much
  4574. // earlier than this one to be considered.
  4575. auto res = cli.Get("/");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(200, res->status);
  4578. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4579. }
  4580. }
  4581. // Disabled due to out-of-memory problem on GitHub Actions
  4582. #ifdef _WIN64
  4583. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4584. // allocate content size larger than 2GB in memory
  4585. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4586. char *content = (char *)malloc(content_size);
  4587. ASSERT_TRUE(content);
  4588. Server svr;
  4589. svr.Get("/foo",
  4590. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  4591. res.set_content(content, content_size, "application/octet-stream");
  4592. });
  4593. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4594. auto se = detail::scope_exit([&] {
  4595. svr.stop();
  4596. listen_thread.join();
  4597. if (content) free(content);
  4598. ASSERT_FALSE(svr.is_running());
  4599. });
  4600. svr.wait_until_ready();
  4601. Client cli(HOST, PORT);
  4602. auto res = cli.Get("/foo");
  4603. ASSERT_TRUE(res);
  4604. EXPECT_EQ(200, res->status);
  4605. EXPECT_EQ(content_size, res->body.length());
  4606. }
  4607. #endif
  4608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4609. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4610. Client cli("http://yahoo.com");
  4611. auto res = cli.Get("/");
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(301, res->status);
  4614. cli.set_follow_location(true);
  4615. res = cli.Get("/");
  4616. ASSERT_TRUE(res);
  4617. EXPECT_EQ(200, res->status);
  4618. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4619. }
  4620. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4621. Client cli("https://yahoo.com");
  4622. auto res = cli.Get("/");
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(301, res->status);
  4625. cli.set_follow_location(true);
  4626. res = cli.Get("/");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(200, res->status);
  4629. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4630. }
  4631. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4632. Client cli("https://yahoo.com");
  4633. auto res = cli.Get("/");
  4634. ASSERT_TRUE(res);
  4635. ASSERT_FALSE(!res);
  4636. ASSERT_TRUE(res);
  4637. ASSERT_FALSE(res == nullptr);
  4638. ASSERT_TRUE(res != nullptr);
  4639. EXPECT_EQ(Error::Success, res.error());
  4640. EXPECT_EQ(301, res.value().status);
  4641. EXPECT_EQ(301, (*res).status);
  4642. EXPECT_EQ(301, res->status);
  4643. cli.set_follow_location(true);
  4644. res = cli.Get("/");
  4645. ASSERT_TRUE(res);
  4646. EXPECT_EQ(Error::Success, res.error());
  4647. EXPECT_EQ(200, res.value().status);
  4648. EXPECT_EQ(200, (*res).status);
  4649. EXPECT_EQ(200, res->status);
  4650. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4651. }
  4652. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4653. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4654. Client cli("https://cdnjs.cloudflare.com");
  4655. auto res =
  4656. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4657. ASSERT_TRUE(res);
  4658. EXPECT_EQ(200, res->status);
  4659. EXPECT_EQ(287630U, res->body.size());
  4660. EXPECT_EQ("application/javascript; charset=utf-8",
  4661. res->get_header_value("Content-Type"));
  4662. }
  4663. #endif
  4664. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4665. Client cli("https://nghttp2.org");
  4666. cli.set_follow_location(true);
  4667. auto res =
  4668. cli.Get("/httpbin/"
  4669. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4670. ASSERT_TRUE(res);
  4671. EXPECT_EQ(200, res->status);
  4672. }
  4673. TEST(HttpsToHttpRedirectTest2, 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. params.emplace("status_code", "302");
  4679. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4680. ASSERT_TRUE(res);
  4681. EXPECT_EQ(200, res->status);
  4682. }
  4683. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4684. Client cli("https://nghttp2.org");
  4685. cli.set_follow_location(true);
  4686. Params params;
  4687. params.emplace("url", "http://www.google.com");
  4688. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4689. ASSERT_TRUE(res);
  4690. EXPECT_EQ(200, res->status);
  4691. }
  4692. TEST(HttpToHttpsRedirectTest, CertFile) {
  4693. Server svr;
  4694. ASSERT_TRUE(svr.is_valid());
  4695. svr.Get("/index", [&](const Request &, Response &res) {
  4696. res.set_redirect("https://127.0.0.1:1235/index");
  4697. svr.stop();
  4698. });
  4699. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4700. ASSERT_TRUE(ssl_svr.is_valid());
  4701. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4702. res.set_content("test", "text/plain");
  4703. ssl_svr.stop();
  4704. });
  4705. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4706. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4707. auto se = detail::scope_exit([&] {
  4708. t2.join();
  4709. t.join();
  4710. ASSERT_FALSE(svr.is_running());
  4711. });
  4712. svr.wait_until_ready();
  4713. ssl_svr.wait_until_ready();
  4714. Client cli("127.0.0.1", PORT);
  4715. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4716. cli.enable_server_certificate_verification(true);
  4717. cli.set_follow_location(true);
  4718. cli.set_connection_timeout(30);
  4719. auto res = cli.Get("/index");
  4720. ASSERT_TRUE(res);
  4721. ASSERT_EQ(200, res->status);
  4722. }
  4723. TEST(MultipartFormDataTest, LargeData) {
  4724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4725. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4726. const ContentReader &content_reader) {
  4727. if (req.is_multipart_form_data()) {
  4728. MultipartFormDataItems files;
  4729. content_reader(
  4730. [&](const MultipartFormData &file) {
  4731. files.push_back(file);
  4732. return true;
  4733. },
  4734. [&](const char *data, size_t data_length) {
  4735. files.back().content.append(data, data_length);
  4736. return true;
  4737. });
  4738. EXPECT_TRUE(std::string(files[0].name) == "document");
  4739. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4740. EXPECT_TRUE(files[0].filename == "2MB_data");
  4741. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4742. EXPECT_TRUE(files[1].name == "hello");
  4743. EXPECT_TRUE(files[1].content == "world");
  4744. EXPECT_TRUE(files[1].filename == "");
  4745. EXPECT_TRUE(files[1].content_type == "");
  4746. } else {
  4747. std::string body;
  4748. content_reader([&](const char *data, size_t data_length) {
  4749. body.append(data, data_length);
  4750. return true;
  4751. });
  4752. }
  4753. });
  4754. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4755. auto se = detail::scope_exit([&] {
  4756. svr.stop();
  4757. t.join();
  4758. ASSERT_FALSE(svr.is_running());
  4759. });
  4760. svr.wait_until_ready();
  4761. {
  4762. std::string data(1024 * 1024 * 2, '.');
  4763. std::stringstream buffer;
  4764. buffer << data;
  4765. Client cli("https://localhost:8080");
  4766. cli.enable_server_certificate_verification(false);
  4767. MultipartFormDataItems items{
  4768. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4769. {"hello", "world", "", ""},
  4770. };
  4771. auto res = cli.Post("/post", items);
  4772. ASSERT_TRUE(res);
  4773. ASSERT_EQ(200, res->status);
  4774. }
  4775. }
  4776. TEST(MultipartFormDataTest, DataProviderItems) {
  4777. std::random_device seed_gen;
  4778. std::mt19937 random(seed_gen());
  4779. std::string rand1;
  4780. rand1.resize(1000);
  4781. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4782. std::string rand2;
  4783. rand2.resize(3000);
  4784. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4785. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4786. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4787. const ContentReader &content_reader) {
  4788. ASSERT_FALSE(req.is_multipart_form_data());
  4789. std::string body;
  4790. content_reader([&](const char *data, size_t data_length) {
  4791. body.append(data, data_length);
  4792. return true;
  4793. });
  4794. EXPECT_EQ(body, "");
  4795. });
  4796. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4797. const ContentReader &content_reader) {
  4798. ASSERT_TRUE(req.is_multipart_form_data());
  4799. MultipartFormDataItems files;
  4800. content_reader(
  4801. [&](const MultipartFormData &file) {
  4802. files.push_back(file);
  4803. return true;
  4804. },
  4805. [&](const char *data, size_t data_length) {
  4806. files.back().content.append(data, data_length);
  4807. return true;
  4808. });
  4809. ASSERT_TRUE(files.size() == 2);
  4810. EXPECT_EQ(std::string(files[0].name), "name1");
  4811. EXPECT_EQ(files[0].content, "Testing123");
  4812. EXPECT_EQ(files[0].filename, "filename1");
  4813. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4814. EXPECT_EQ(files[1].name, "name2");
  4815. EXPECT_EQ(files[1].content, "Testing456");
  4816. EXPECT_EQ(files[1].filename, "");
  4817. EXPECT_EQ(files[1].content_type, "");
  4818. });
  4819. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4820. const ContentReader &content_reader) {
  4821. ASSERT_TRUE(req.is_multipart_form_data());
  4822. MultipartFormDataItems files;
  4823. content_reader(
  4824. [&](const MultipartFormData &file) {
  4825. files.push_back(file);
  4826. return true;
  4827. },
  4828. [&](const char *data, size_t data_length) {
  4829. files.back().content.append(data, data_length);
  4830. return true;
  4831. });
  4832. ASSERT_TRUE(files.size() == 2);
  4833. EXPECT_EQ(files[0].name, "name3");
  4834. EXPECT_EQ(files[0].content, rand1);
  4835. EXPECT_EQ(files[0].filename, "filename3");
  4836. EXPECT_EQ(files[0].content_type, "");
  4837. EXPECT_EQ(files[1].name, "name4");
  4838. EXPECT_EQ(files[1].content, rand2);
  4839. EXPECT_EQ(files[1].filename, "filename4");
  4840. EXPECT_EQ(files[1].content_type, "");
  4841. });
  4842. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4843. const ContentReader &content_reader) {
  4844. ASSERT_TRUE(req.is_multipart_form_data());
  4845. MultipartFormDataItems files;
  4846. content_reader(
  4847. [&](const MultipartFormData &file) {
  4848. files.push_back(file);
  4849. return true;
  4850. },
  4851. [&](const char *data, size_t data_length) {
  4852. files.back().content.append(data, data_length);
  4853. return true;
  4854. });
  4855. ASSERT_TRUE(files.size() == 4);
  4856. EXPECT_EQ(std::string(files[0].name), "name1");
  4857. EXPECT_EQ(files[0].content, "Testing123");
  4858. EXPECT_EQ(files[0].filename, "filename1");
  4859. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4860. EXPECT_EQ(files[1].name, "name2");
  4861. EXPECT_EQ(files[1].content, "Testing456");
  4862. EXPECT_EQ(files[1].filename, "");
  4863. EXPECT_EQ(files[1].content_type, "");
  4864. EXPECT_EQ(files[2].name, "name3");
  4865. EXPECT_EQ(files[2].content, rand1);
  4866. EXPECT_EQ(files[2].filename, "filename3");
  4867. EXPECT_EQ(files[2].content_type, "");
  4868. EXPECT_EQ(files[3].name, "name4");
  4869. EXPECT_EQ(files[3].content, rand2);
  4870. EXPECT_EQ(files[3].filename, "filename4");
  4871. EXPECT_EQ(files[3].content_type, "");
  4872. });
  4873. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4874. auto se = detail::scope_exit([&] {
  4875. svr.stop();
  4876. t.join();
  4877. ASSERT_FALSE(svr.is_running());
  4878. });
  4879. svr.wait_until_ready();
  4880. {
  4881. Client cli("https://localhost:8080");
  4882. cli.enable_server_certificate_verification(false);
  4883. MultipartFormDataItems items{
  4884. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4885. {"name2", "Testing456", "", ""}, // not a file
  4886. };
  4887. {
  4888. auto res = cli.Post("/post-none", {}, {}, {});
  4889. ASSERT_TRUE(res);
  4890. ASSERT_EQ(200, res->status);
  4891. }
  4892. MultipartFormDataProviderItems providers;
  4893. {
  4894. auto res =
  4895. cli.Post("/post-items", {}, items, providers); // empty providers
  4896. ASSERT_TRUE(res);
  4897. ASSERT_EQ(200, res->status);
  4898. }
  4899. providers.push_back({"name3",
  4900. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4901. // test the offset is given correctly at each step
  4902. if (!offset)
  4903. sink.os.write(rand1.data(), 30);
  4904. else if (offset == 30)
  4905. sink.os.write(rand1.data() + 30, 300);
  4906. else if (offset == 330)
  4907. sink.os.write(rand1.data() + 330, 670);
  4908. else if (offset == rand1.size())
  4909. sink.done();
  4910. return true;
  4911. },
  4912. "filename3",
  4913. {}});
  4914. providers.push_back({"name4",
  4915. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4916. // test the offset is given correctly at each step
  4917. if (!offset)
  4918. sink.os.write(rand2.data(), 2000);
  4919. else if (offset == 2000)
  4920. sink.os.write(rand2.data() + 2000, 1);
  4921. else if (offset == 2001)
  4922. sink.os.write(rand2.data() + 2001, 999);
  4923. else if (offset == rand2.size())
  4924. sink.done();
  4925. return true;
  4926. },
  4927. "filename4",
  4928. {}});
  4929. {
  4930. auto res = cli.Post("/post-providers", {}, {}, providers);
  4931. ASSERT_TRUE(res);
  4932. ASSERT_EQ(200, res->status);
  4933. }
  4934. {
  4935. auto res = cli.Post("/post-both", {}, items, providers);
  4936. ASSERT_TRUE(res);
  4937. ASSERT_EQ(200, res->status);
  4938. }
  4939. }
  4940. }
  4941. TEST(MultipartFormDataTest, BadHeader) {
  4942. Server svr;
  4943. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4944. res.set_content("ok", "text/plain");
  4945. });
  4946. thread t = thread([&] { svr.listen(HOST, PORT); });
  4947. auto se = detail::scope_exit([&] {
  4948. svr.stop();
  4949. t.join();
  4950. ASSERT_FALSE(svr.is_running());
  4951. });
  4952. svr.wait_until_ready();
  4953. const std::string body =
  4954. "This is the preamble. It is to be ignored, though it\r\n"
  4955. "is a handy place for composition agents to include an\r\n"
  4956. "explanatory note to non-MIME conformant readers.\r\n"
  4957. "\r\n"
  4958. "\r\n"
  4959. "--simple boundary\r\n"
  4960. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4961. ": BAD...\r\n"
  4962. "\r\n"
  4963. "value1\r\n"
  4964. "--simple boundary\r\n"
  4965. "Content-Disposition: form-data; name=\"field2\"; "
  4966. "filename=\"example.txt\"\r\n"
  4967. "\r\n"
  4968. "value2\r\n"
  4969. "--simple boundary--\r\n"
  4970. "This is the epilogue. It is also to be ignored.\r\n";
  4971. std::string content_type =
  4972. R"(multipart/form-data; boundary="simple boundary")";
  4973. Client cli(HOST, PORT);
  4974. auto res = cli.Post("/post", body, content_type.c_str());
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(400, res->status);
  4977. }
  4978. TEST(MultipartFormDataTest, WithPreamble) {
  4979. Server svr;
  4980. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4981. res.set_content("ok", "text/plain");
  4982. });
  4983. thread t = thread([&] { svr.listen(HOST, PORT); });
  4984. auto se = detail::scope_exit([&] {
  4985. svr.stop();
  4986. t.join();
  4987. ASSERT_FALSE(svr.is_running());
  4988. });
  4989. svr.wait_until_ready();
  4990. const std::string body =
  4991. "This is the preamble. It is to be ignored, though it\r\n"
  4992. "is a handy place for composition agents to include an\r\n"
  4993. "explanatory note to non-MIME conformant readers.\r\n"
  4994. "\r\n"
  4995. "\r\n"
  4996. "--simple boundary\r\n"
  4997. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4998. "\r\n"
  4999. "value1\r\n"
  5000. "--simple boundary\r\n"
  5001. "Content-Disposition: form-data; name=\"field2\"; "
  5002. "filename=\"example.txt\"\r\n"
  5003. "\r\n"
  5004. "value2\r\n"
  5005. "--simple boundary--\r\n"
  5006. "This is the epilogue. It is also to be ignored.\r\n";
  5007. std::string content_type =
  5008. R"(multipart/form-data; boundary="simple boundary")";
  5009. Client cli(HOST, PORT);
  5010. auto res = cli.Post("/post", body, content_type.c_str());
  5011. ASSERT_TRUE(res);
  5012. EXPECT_EQ(200, res->status);
  5013. }
  5014. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5016. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5017. const ContentReader &content_reader) {
  5018. if (req.is_multipart_form_data()) {
  5019. MultipartFormDataItems files;
  5020. content_reader(
  5021. [&](const MultipartFormData &file) {
  5022. files.push_back(file);
  5023. return true;
  5024. },
  5025. [&](const char *data, size_t data_length) {
  5026. files.back().content.append(data, data_length);
  5027. return true;
  5028. });
  5029. EXPECT_TRUE(std::string(files[0].name) == "document");
  5030. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5031. EXPECT_TRUE(files[0].filename == "2MB_data");
  5032. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5033. EXPECT_TRUE(files[1].name == "hello");
  5034. EXPECT_TRUE(files[1].content == "world");
  5035. EXPECT_TRUE(files[1].filename == "");
  5036. EXPECT_TRUE(files[1].content_type == "");
  5037. } else {
  5038. std::string body;
  5039. content_reader([&](const char *data, size_t data_length) {
  5040. body.append(data, data_length);
  5041. return true;
  5042. });
  5043. }
  5044. });
  5045. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5046. auto se = detail::scope_exit([&] {
  5047. svr.stop();
  5048. t.join();
  5049. ASSERT_FALSE(svr.is_running());
  5050. });
  5051. svr.wait_until_ready();
  5052. {
  5053. std::string data(1024 * 1024 * 2, '.');
  5054. std::stringstream buffer;
  5055. buffer << data;
  5056. Client cli("https://localhost:8080");
  5057. cli.enable_server_certificate_verification(false);
  5058. MultipartFormDataItems items{
  5059. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5060. {"hello", "world", "", ""},
  5061. };
  5062. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5063. ASSERT_TRUE(res);
  5064. ASSERT_EQ(200, res->status);
  5065. }
  5066. }
  5067. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5068. std::string data(1024 * 1024 * 2, '&');
  5069. std::stringstream buffer;
  5070. buffer << data;
  5071. Client cli("https://localhost:8080");
  5072. MultipartFormDataItems items{
  5073. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5074. {"hello", "world", "", ""},
  5075. };
  5076. for (const char &c : " \t\r\n") {
  5077. auto res =
  5078. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5079. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5080. ASSERT_FALSE(res);
  5081. }
  5082. }
  5083. TEST(MultipartFormDataTest, PutFormData) {
  5084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5085. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5086. const ContentReader &content_reader) {
  5087. if (req.is_multipart_form_data()) {
  5088. MultipartFormDataItems files;
  5089. content_reader(
  5090. [&](const MultipartFormData &file) {
  5091. files.push_back(file);
  5092. return true;
  5093. },
  5094. [&](const char *data, size_t data_length) {
  5095. files.back().content.append(data, data_length);
  5096. return true;
  5097. });
  5098. EXPECT_TRUE(std::string(files[0].name) == "document");
  5099. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5100. EXPECT_TRUE(files[0].filename == "2MB_data");
  5101. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5102. EXPECT_TRUE(files[1].name == "hello");
  5103. EXPECT_TRUE(files[1].content == "world");
  5104. EXPECT_TRUE(files[1].filename == "");
  5105. EXPECT_TRUE(files[1].content_type == "");
  5106. } else {
  5107. std::string body;
  5108. content_reader([&](const char *data, size_t data_length) {
  5109. body.append(data, data_length);
  5110. return true;
  5111. });
  5112. }
  5113. });
  5114. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5115. auto se = detail::scope_exit([&] {
  5116. svr.stop();
  5117. t.join();
  5118. ASSERT_FALSE(svr.is_running());
  5119. });
  5120. svr.wait_until_ready();
  5121. {
  5122. std::string data(1024 * 1024 * 2, '&');
  5123. std::stringstream buffer;
  5124. buffer << data;
  5125. Client cli("https://localhost:8080");
  5126. cli.enable_server_certificate_verification(false);
  5127. MultipartFormDataItems items{
  5128. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5129. {"hello", "world", "", ""},
  5130. };
  5131. auto res = cli.Put("/put", items);
  5132. ASSERT_TRUE(res);
  5133. ASSERT_EQ(200, res->status);
  5134. }
  5135. }
  5136. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5138. svr.Put("/put_customboundary",
  5139. [&](const Request &req, const Response & /*res*/,
  5140. const ContentReader &content_reader) {
  5141. if (req.is_multipart_form_data()) {
  5142. MultipartFormDataItems files;
  5143. content_reader(
  5144. [&](const MultipartFormData &file) {
  5145. files.push_back(file);
  5146. return true;
  5147. },
  5148. [&](const char *data, size_t data_length) {
  5149. files.back().content.append(data, data_length);
  5150. return true;
  5151. });
  5152. EXPECT_TRUE(std::string(files[0].name) == "document");
  5153. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5154. EXPECT_TRUE(files[0].filename == "2MB_data");
  5155. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5156. EXPECT_TRUE(files[1].name == "hello");
  5157. EXPECT_TRUE(files[1].content == "world");
  5158. EXPECT_TRUE(files[1].filename == "");
  5159. EXPECT_TRUE(files[1].content_type == "");
  5160. } else {
  5161. std::string body;
  5162. content_reader([&](const char *data, size_t data_length) {
  5163. body.append(data, data_length);
  5164. return true;
  5165. });
  5166. }
  5167. });
  5168. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5169. auto se = detail::scope_exit([&] {
  5170. svr.stop();
  5171. t.join();
  5172. ASSERT_FALSE(svr.is_running());
  5173. });
  5174. svr.wait_until_ready();
  5175. {
  5176. std::string data(1024 * 1024 * 2, '&');
  5177. std::stringstream buffer;
  5178. buffer << data;
  5179. Client cli("https://localhost:8080");
  5180. cli.enable_server_certificate_verification(false);
  5181. MultipartFormDataItems items{
  5182. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5183. {"hello", "world", "", ""},
  5184. };
  5185. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5186. ASSERT_TRUE(res);
  5187. ASSERT_EQ(200, res->status);
  5188. }
  5189. }
  5190. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5191. std::string data(1024 * 1024 * 2, '&');
  5192. std::stringstream buffer;
  5193. buffer << data;
  5194. Client cli("https://localhost:8080");
  5195. cli.enable_server_certificate_verification(false);
  5196. MultipartFormDataItems items{
  5197. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5198. {"hello", "world", "", ""},
  5199. };
  5200. for (const char &c : " \t\r\n") {
  5201. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5202. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5203. ASSERT_FALSE(res);
  5204. }
  5205. }
  5206. TEST(MultipartFormDataTest, AlternateFilename) {
  5207. auto handled = false;
  5208. Server svr;
  5209. svr.Post("/test", [&](const Request &req, Response &res) {
  5210. ASSERT_EQ(3u, req.files.size());
  5211. auto it = req.files.begin();
  5212. ASSERT_EQ("file1", it->second.name);
  5213. ASSERT_EQ("A.txt", it->second.filename);
  5214. ASSERT_EQ("text/plain", it->second.content_type);
  5215. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5216. ++it;
  5217. ASSERT_EQ("file2", it->second.name);
  5218. ASSERT_EQ("a.html", it->second.filename);
  5219. ASSERT_EQ("text/html", it->second.content_type);
  5220. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5221. it->second.content);
  5222. ++it;
  5223. ASSERT_EQ("text", it->second.name);
  5224. ASSERT_EQ("", it->second.filename);
  5225. ASSERT_EQ("", it->second.content_type);
  5226. ASSERT_EQ("text default", it->second.content);
  5227. res.set_content("ok", "text/plain");
  5228. handled = true;
  5229. });
  5230. thread t = thread([&] { svr.listen(HOST, PORT); });
  5231. auto se = detail::scope_exit([&] {
  5232. svr.stop();
  5233. t.join();
  5234. ASSERT_FALSE(svr.is_running());
  5235. ASSERT_TRUE(handled);
  5236. });
  5237. svr.wait_until_ready();
  5238. auto req = "POST /test HTTP/1.1\r\n"
  5239. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5240. "Content-Length: 399\r\n"
  5241. "\r\n"
  5242. "----------\r\n"
  5243. "Content-Disposition: form-data; name=\"text\"\r\n"
  5244. "\r\n"
  5245. "text default\r\n"
  5246. "----------\r\n"
  5247. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  5248. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5249. "Content-Type: text/plain\r\n"
  5250. "\r\n"
  5251. "Content of a.txt.\r\n"
  5252. "\r\n"
  5253. "----------\r\n"
  5254. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5255. "\"a.html\"\r\n"
  5256. "Content-Type: text/html\r\n"
  5257. "\r\n"
  5258. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5259. "\r\n"
  5260. "------------\r\n";
  5261. ASSERT_TRUE(send_request(1, req));
  5262. }
  5263. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5264. auto handled = false;
  5265. Server svr;
  5266. svr.Post("/test", [&](const Request &req, Response &) {
  5267. ASSERT_EQ(2u, req.files.size());
  5268. auto it = req.files.begin();
  5269. ASSERT_EQ("text1", it->second.name);
  5270. ASSERT_EQ("text1", it->second.content);
  5271. ++it;
  5272. ASSERT_EQ("text2", it->second.name);
  5273. ASSERT_EQ("text2", it->second.content);
  5274. handled = true;
  5275. });
  5276. thread t = thread([&] { svr.listen(HOST, PORT); });
  5277. auto se = detail::scope_exit([&] {
  5278. svr.stop();
  5279. t.join();
  5280. ASSERT_FALSE(svr.is_running());
  5281. ASSERT_TRUE(handled);
  5282. });
  5283. svr.wait_until_ready();
  5284. auto req = "POST /test HTTP/1.1\r\n"
  5285. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5286. "Content-Length: 146\r\n"
  5287. "\r\n----------\r\n"
  5288. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5289. "\r\n"
  5290. "text1"
  5291. "\r\n----------\r\n"
  5292. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5293. "\r\n"
  5294. "text2"
  5295. "\r\n------------";
  5296. std::string resonse;
  5297. ASSERT_TRUE(send_request(1, req, &resonse));
  5298. ASSERT_EQ("200", resonse.substr(9, 3));
  5299. }
  5300. TEST(MultipartFormDataTest, ContentLength) {
  5301. auto handled = false;
  5302. Server svr;
  5303. svr.Post("/test", [&](const Request &req, Response &) {
  5304. ASSERT_EQ(2u, req.files.size());
  5305. auto it = req.files.begin();
  5306. ASSERT_EQ("text1", it->second.name);
  5307. ASSERT_EQ("text1", it->second.content);
  5308. ++it;
  5309. ASSERT_EQ("text2", it->second.name);
  5310. ASSERT_EQ("text2", it->second.content);
  5311. handled = true;
  5312. });
  5313. thread t = thread([&] { svr.listen(HOST, PORT); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. t.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. ASSERT_TRUE(handled);
  5319. });
  5320. svr.wait_until_ready();
  5321. auto req = "POST /test HTTP/1.1\r\n"
  5322. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5323. "Content-Length: 167\r\n"
  5324. "\r\n----------\r\n"
  5325. "Content-Disposition: form-data; name=\"text1\"\r\n"
  5326. "Content-Length: 5\r\n"
  5327. "\r\n"
  5328. "text1"
  5329. "\r\n----------\r\n"
  5330. "Content-Disposition: form-data; name=\"text2\"\r\n"
  5331. "\r\n"
  5332. "text2"
  5333. "\r\n------------\r\n";
  5334. std::string resonse;
  5335. ASSERT_TRUE(send_request(1, req, &resonse));
  5336. ASSERT_EQ("200", resonse.substr(9, 3));
  5337. }
  5338. #endif
  5339. #ifndef _WIN32
  5340. class UnixSocketTest : public ::testing::Test {
  5341. protected:
  5342. void TearDown() override { std::remove(pathname_.c_str()); }
  5343. void client_GET(const std::string &addr) {
  5344. httplib::Client cli{addr};
  5345. cli.set_address_family(AF_UNIX);
  5346. ASSERT_TRUE(cli.is_valid());
  5347. const auto &result = cli.Get(pattern_);
  5348. ASSERT_TRUE(result) << "error: " << result.error();
  5349. const auto &resp = result.value();
  5350. EXPECT_EQ(resp.status, 200);
  5351. EXPECT_EQ(resp.body, content_);
  5352. }
  5353. const std::string pathname_{"./httplib-server.sock"};
  5354. const std::string pattern_{"/hi"};
  5355. const std::string content_{"Hello World!"};
  5356. };
  5357. TEST_F(UnixSocketTest, pathname) {
  5358. httplib::Server svr;
  5359. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5360. res.set_content(content_, "text/plain");
  5361. });
  5362. std::thread t{[&] {
  5363. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5364. }};
  5365. auto se = detail::scope_exit([&] {
  5366. svr.stop();
  5367. t.join();
  5368. ASSERT_FALSE(svr.is_running());
  5369. });
  5370. svr.wait_until_ready();
  5371. ASSERT_TRUE(svr.is_running());
  5372. client_GET(pathname_);
  5373. }
  5374. #if defined(__linux__) || \
  5375. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5376. TEST_F(UnixSocketTest, PeerPid) {
  5377. httplib::Server svr;
  5378. std::string remote_port_val;
  5379. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5380. res.set_content(content_, "text/plain");
  5381. remote_port_val = req.get_header_value("REMOTE_PORT");
  5382. });
  5383. std::thread t{[&] {
  5384. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5385. }};
  5386. auto se = detail::scope_exit([&] {
  5387. svr.stop();
  5388. t.join();
  5389. ASSERT_FALSE(svr.is_running());
  5390. });
  5391. svr.wait_until_ready();
  5392. ASSERT_TRUE(svr.is_running());
  5393. client_GET(pathname_);
  5394. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5395. }
  5396. #endif
  5397. #ifdef __linux__
  5398. TEST_F(UnixSocketTest, abstract) {
  5399. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5400. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5401. httplib::Server svr;
  5402. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5403. res.set_content(content_, "text/plain");
  5404. });
  5405. std::thread t{[&] {
  5406. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5407. }};
  5408. auto se = detail::scope_exit([&] {
  5409. svr.stop();
  5410. t.join();
  5411. ASSERT_FALSE(svr.is_running());
  5412. });
  5413. svr.wait_until_ready();
  5414. ASSERT_TRUE(svr.is_running());
  5415. client_GET(abstract_addr);
  5416. }
  5417. #endif
  5418. TEST(SocketStream, is_writable_UNIX) {
  5419. int fds[2];
  5420. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5421. const auto asSocketStream = [&](socket_t fd,
  5422. std::function<bool(Stream &)> func) {
  5423. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5424. };
  5425. asSocketStream(fds[0], [&](Stream &s0) {
  5426. EXPECT_EQ(s0.socket(), fds[0]);
  5427. EXPECT_TRUE(s0.is_writable());
  5428. EXPECT_EQ(0, close(fds[1]));
  5429. EXPECT_FALSE(s0.is_writable());
  5430. return true;
  5431. });
  5432. EXPECT_EQ(0, close(fds[0]));
  5433. }
  5434. TEST(SocketStream, is_writable_INET) {
  5435. sockaddr_in addr;
  5436. memset(&addr, 0, sizeof(addr));
  5437. addr.sin_family = AF_INET;
  5438. addr.sin_port = htons(PORT + 1);
  5439. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5440. int disconnected_svr_sock = -1;
  5441. std::thread svr{[&] {
  5442. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5443. ASSERT_LE(0, s);
  5444. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5445. ASSERT_EQ(0, listen(s, 1));
  5446. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5447. ASSERT_EQ(0, close(s));
  5448. }};
  5449. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5450. std::thread cli{[&] {
  5451. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5452. ASSERT_LE(0, s);
  5453. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5454. ASSERT_EQ(0, close(s));
  5455. }};
  5456. cli.join();
  5457. svr.join();
  5458. ASSERT_NE(disconnected_svr_sock, -1);
  5459. const auto asSocketStream = [&](socket_t fd,
  5460. std::function<bool(Stream &)> func) {
  5461. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5462. };
  5463. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5464. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5465. EXPECT_FALSE(ss.is_writable());
  5466. return true;
  5467. });
  5468. ASSERT_EQ(0, close(disconnected_svr_sock));
  5469. }
  5470. #endif // #ifndef _WIN32
  5471. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5472. static constexpr unsigned int number_of_task{1000000};
  5473. std::atomic_uint count{0};
  5474. std::unique_ptr<TaskQueue> task_queue{
  5475. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5476. for (unsigned int i = 0; i < number_of_task; ++i) {
  5477. task_queue->enqueue(
  5478. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5479. }
  5480. EXPECT_NO_THROW(task_queue->shutdown());
  5481. EXPECT_EQ(number_of_task, count.load());
  5482. }
  5483. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5484. Server svr;
  5485. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5486. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5487. });
  5488. svr.Get("/hello", [](const Request &req, Response &res) {
  5489. res.set_content(req.get_param_value("key"), "text/plain");
  5490. });
  5491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5492. auto se = detail::scope_exit([&] {
  5493. svr.stop();
  5494. thread.join();
  5495. ASSERT_FALSE(svr.is_running());
  5496. });
  5497. svr.wait_until_ready();
  5498. {
  5499. Client cli(HOST, PORT);
  5500. cli.set_follow_location(true);
  5501. auto res = cli.Get("/");
  5502. ASSERT_TRUE(res);
  5503. EXPECT_EQ(200, res->status);
  5504. EXPECT_EQ("val&key2=val2", res->body);
  5505. }
  5506. }
  5507. TEST(VulnerabilityTest, CRLFInjection) {
  5508. Server svr;
  5509. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  5510. res.set_content("Hello 1", "text/plain");
  5511. });
  5512. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  5513. res.set_content("Hello 2", "text/plain");
  5514. });
  5515. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  5516. res.set_content("Hello 3", "text/plain");
  5517. });
  5518. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  5519. res.set_content("Hello 4", "text/plain");
  5520. });
  5521. svr.set_logger([](const Request &req, const Response & /*res*/) {
  5522. for (const auto &x : req.headers) {
  5523. auto key = x.first;
  5524. EXPECT_STRNE("evil", key.c_str());
  5525. }
  5526. });
  5527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5528. auto se = detail::scope_exit([&] {
  5529. svr.stop();
  5530. thread.join();
  5531. ASSERT_FALSE(svr.is_running());
  5532. });
  5533. svr.wait_until_ready();
  5534. {
  5535. Client cli(HOST, PORT);
  5536. cli.Post("/test1", "A=B",
  5537. "application/x-www-form-urlencoded\r\nevil: hello1");
  5538. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  5539. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  5540. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  5541. }
  5542. }
  5543. TEST(PathParamsTest, StaticMatch) {
  5544. const auto pattern = "/users/all";
  5545. detail::PathParamsMatcher matcher(pattern);
  5546. Request request;
  5547. request.path = "/users/all";
  5548. ASSERT_TRUE(matcher.match(request));
  5549. std::unordered_map<std::string, std::string> expected_params = {};
  5550. EXPECT_EQ(request.path_params, expected_params);
  5551. }
  5552. TEST(PathParamsTest, StaticMismatch) {
  5553. const auto pattern = "/users/all";
  5554. detail::PathParamsMatcher matcher(pattern);
  5555. Request request;
  5556. request.path = "/users/1";
  5557. ASSERT_FALSE(matcher.match(request));
  5558. }
  5559. TEST(PathParamsTest, SingleParamInTheMiddle) {
  5560. const auto pattern = "/users/:id/subscriptions";
  5561. detail::PathParamsMatcher matcher(pattern);
  5562. Request request;
  5563. request.path = "/users/42/subscriptions";
  5564. ASSERT_TRUE(matcher.match(request));
  5565. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5566. EXPECT_EQ(request.path_params, expected_params);
  5567. }
  5568. TEST(PathParamsTest, SingleParamInTheEnd) {
  5569. const auto pattern = "/users/:id";
  5570. detail::PathParamsMatcher matcher(pattern);
  5571. Request request;
  5572. request.path = "/users/24";
  5573. ASSERT_TRUE(matcher.match(request));
  5574. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  5575. EXPECT_EQ(request.path_params, expected_params);
  5576. }
  5577. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  5578. const auto pattern = "/users/:id/";
  5579. detail::PathParamsMatcher matcher(pattern);
  5580. Request request;
  5581. request.path = "/users/42/";
  5582. ASSERT_TRUE(matcher.match(request));
  5583. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  5584. EXPECT_EQ(request.path_params, expected_params);
  5585. }
  5586. TEST(PathParamsTest, EmptyParam) {
  5587. const auto pattern = "/users/:id/";
  5588. detail::PathParamsMatcher matcher(pattern);
  5589. Request request;
  5590. request.path = "/users//";
  5591. ASSERT_TRUE(matcher.match(request));
  5592. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  5593. EXPECT_EQ(request.path_params, expected_params);
  5594. }
  5595. TEST(PathParamsTest, FragmentMismatch) {
  5596. const auto pattern = "/users/:id/";
  5597. detail::PathParamsMatcher matcher(pattern);
  5598. Request request;
  5599. request.path = "/admins/24/";
  5600. ASSERT_FALSE(matcher.match(request));
  5601. }
  5602. TEST(PathParamsTest, ExtraFragments) {
  5603. const auto pattern = "/users/:id";
  5604. detail::PathParamsMatcher matcher(pattern);
  5605. Request request;
  5606. request.path = "/users/42/subscriptions";
  5607. ASSERT_FALSE(matcher.match(request));
  5608. }
  5609. TEST(PathParamsTest, MissingTrailingParam) {
  5610. const auto pattern = "/users/:id";
  5611. detail::PathParamsMatcher matcher(pattern);
  5612. Request request;
  5613. request.path = "/users";
  5614. ASSERT_FALSE(matcher.match(request));
  5615. }
  5616. TEST(PathParamsTest, MissingParamInTheMiddle) {
  5617. const auto pattern = "/users/:id/subscriptions";
  5618. detail::PathParamsMatcher matcher(pattern);
  5619. Request request;
  5620. request.path = "/users/subscriptions";
  5621. ASSERT_FALSE(matcher.match(request));
  5622. }
  5623. TEST(PathParamsTest, MultipleParams) {
  5624. const auto pattern = "/users/:userid/subscriptions/:subid";
  5625. detail::PathParamsMatcher matcher(pattern);
  5626. Request request;
  5627. request.path = "/users/42/subscriptions/2";
  5628. ASSERT_TRUE(matcher.match(request));
  5629. std::unordered_map<std::string, std::string> expected_params = {
  5630. {"userid", "42"}, {"subid", "2"}};
  5631. EXPECT_EQ(request.path_params, expected_params);
  5632. }
  5633. TEST(PathParamsTest, SequenceOfParams) {
  5634. const auto pattern = "/values/:x/:y/:z";
  5635. detail::PathParamsMatcher matcher(pattern);
  5636. Request request;
  5637. request.path = "/values/1/2/3";
  5638. ASSERT_TRUE(matcher.match(request));
  5639. std::unordered_map<std::string, std::string> expected_params = {
  5640. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  5641. EXPECT_EQ(request.path_params, expected_params);
  5642. }