test.cc 226 KB

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