test.cc 224 KB

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