test.cc 198 KB

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