test.cc 234 KB

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