test.cc 207 KB

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