test.cc 224 KB

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