test.cc 194 KB

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