test.cc 293 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodeURLTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_url(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodeURLTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(TrimTests, TrimStringTests) {
  252. EXPECT_EQ("abc", detail::trim_copy("abc"));
  253. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  254. EXPECT_TRUE(detail::trim_copy("").empty());
  255. }
  256. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  257. // Simple case without quality values
  258. std::vector<std::string> result1;
  259. EXPECT_TRUE(detail::parse_accept_header(
  260. "text/html,application/json,text/plain", result1));
  261. EXPECT_EQ(result1.size(), 3);
  262. EXPECT_EQ(result1[0], "text/html");
  263. EXPECT_EQ(result1[1], "application/json");
  264. EXPECT_EQ(result1[2], "text/plain");
  265. // With quality values
  266. std::vector<std::string> result2;
  267. EXPECT_TRUE(detail::parse_accept_header(
  268. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  269. EXPECT_EQ(result2.size(), 3);
  270. EXPECT_EQ(result2[0], "application/json"); // highest q value
  271. EXPECT_EQ(result2[1], "text/html");
  272. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  273. }
  274. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  275. // Mixed with and without quality values
  276. std::vector<std::string> result;
  277. EXPECT_TRUE(detail::parse_accept_header(
  278. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  279. EXPECT_EQ(result.size(), 3);
  280. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  281. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  282. EXPECT_EQ(result[2], "application/json"); // q=0.5
  283. }
  284. TEST(ParseAcceptHeaderTest, EdgeCases) {
  285. // Empty header
  286. std::vector<std::string> empty_result;
  287. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  288. EXPECT_TRUE(empty_result.empty());
  289. // Single type
  290. std::vector<std::string> single_result;
  291. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  292. EXPECT_EQ(single_result.size(), 1);
  293. EXPECT_EQ(single_result[0], "application/json");
  294. // Wildcard types
  295. std::vector<std::string> wildcard_result;
  296. EXPECT_TRUE(detail::parse_accept_header(
  297. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  298. EXPECT_EQ(wildcard_result.size(), 3);
  299. EXPECT_EQ(wildcard_result[0], "application/json");
  300. EXPECT_EQ(wildcard_result[1], "text/*");
  301. EXPECT_EQ(wildcard_result[2], "*/*");
  302. }
  303. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  304. // Common browser Accept header
  305. std::vector<std::string> browser_result;
  306. EXPECT_TRUE(
  307. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  308. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  309. browser_result));
  310. EXPECT_EQ(browser_result.size(), 6);
  311. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  312. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  313. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  314. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  315. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  316. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  317. // API client header
  318. std::vector<std::string> api_result;
  319. EXPECT_TRUE(detail::parse_accept_header(
  320. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  321. api_result));
  322. EXPECT_EQ(api_result.size(), 3);
  323. EXPECT_EQ(api_result[0], "application/json");
  324. EXPECT_EQ(api_result[1], "application/xml");
  325. EXPECT_EQ(api_result[2], "text/plain");
  326. }
  327. TEST(ParseAcceptHeaderTest, SpecialCases) {
  328. // Quality value with 3 decimal places
  329. std::vector<std::string> decimal_result;
  330. EXPECT_TRUE(detail::parse_accept_header(
  331. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  332. EXPECT_EQ(decimal_result.size(), 2);
  333. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  334. EXPECT_EQ(decimal_result[1], "text/html");
  335. // Zero quality (should still be included but with lowest priority)
  336. std::vector<std::string> zero_q_result;
  337. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  338. zero_q_result));
  339. EXPECT_EQ(zero_q_result.size(), 2);
  340. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  341. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  342. // No spaces around commas
  343. std::vector<std::string> no_space_result;
  344. EXPECT_TRUE(detail::parse_accept_header(
  345. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  346. no_space_result));
  347. EXPECT_EQ(no_space_result.size(), 3);
  348. EXPECT_EQ(no_space_result[0], "text/html");
  349. EXPECT_EQ(no_space_result[1], "application/json");
  350. EXPECT_EQ(no_space_result[2], "text/plain");
  351. }
  352. TEST(ParseAcceptHeaderTest, InvalidCases) {
  353. std::vector<std::string> result;
  354. // Invalid quality value (> 1.0)
  355. EXPECT_FALSE(
  356. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  357. // Invalid quality value (< 0.0)
  358. EXPECT_FALSE(
  359. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  360. // Invalid quality value (not a number)
  361. EXPECT_FALSE(detail::parse_accept_header(
  362. "text/html;q=invalid,application/json", result));
  363. // Empty quality value
  364. EXPECT_FALSE(
  365. detail::parse_accept_header("text/html;q=,application/json", result));
  366. // Invalid media type format (no slash and not wildcard)
  367. EXPECT_FALSE(
  368. detail::parse_accept_header("invalidtype,application/json", result));
  369. // Empty media type
  370. result.clear();
  371. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  372. // Only commas
  373. result.clear();
  374. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  375. // Valid cases should still work
  376. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  377. EXPECT_EQ(result.size(), 1);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1);
  384. EXPECT_EQ(result[0], "text/*");
  385. }
  386. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  387. Server svr;
  388. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  389. EXPECT_EQ(req.accept_content_types.size(), 3);
  390. EXPECT_EQ(req.accept_content_types[0], "application/json");
  391. EXPECT_EQ(req.accept_content_types[1], "text/html");
  392. EXPECT_EQ(req.accept_content_types[2], "*/*");
  393. res.set_content("ok", "text/plain");
  394. });
  395. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  396. EXPECT_TRUE(false);
  397. res.set_content("bad request", "text/plain");
  398. });
  399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  400. auto se = detail::scope_exit([&] {
  401. svr.stop();
  402. listen_thread.join();
  403. ASSERT_FALSE(svr.is_running());
  404. });
  405. svr.wait_until_ready();
  406. Client cli("localhost", PORT);
  407. {
  408. auto res =
  409. cli.Get("/accept_ok",
  410. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ(StatusCode::OK_200, res->status);
  413. }
  414. {
  415. auto res = cli.Get("/accept_bad_request",
  416. {{"Accept", "text/html;q=abc,application/json"}});
  417. ASSERT_TRUE(res);
  418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  419. }
  420. }
  421. TEST(DivideTest, DivideStringTests) {
  422. auto divide = [](const std::string &str, char d) {
  423. std::string lhs;
  424. std::string rhs;
  425. detail::divide(str, d,
  426. [&](const char *lhs_data, std::size_t lhs_size,
  427. const char *rhs_data, std::size_t rhs_size) {
  428. lhs.assign(lhs_data, lhs_size);
  429. rhs.assign(rhs_data, rhs_size);
  430. });
  431. return std::make_pair(std::move(lhs), std::move(rhs));
  432. };
  433. {
  434. const auto res = divide("", '=');
  435. EXPECT_EQ(res.first, "");
  436. EXPECT_EQ(res.second, "");
  437. }
  438. {
  439. const auto res = divide("=", '=');
  440. EXPECT_EQ(res.first, "");
  441. EXPECT_EQ(res.second, "");
  442. }
  443. {
  444. const auto res = divide(" ", '=');
  445. EXPECT_EQ(res.first, " ");
  446. EXPECT_EQ(res.second, "");
  447. }
  448. {
  449. const auto res = divide("a", '=');
  450. EXPECT_EQ(res.first, "a");
  451. EXPECT_EQ(res.second, "");
  452. }
  453. {
  454. const auto res = divide("a=", '=');
  455. EXPECT_EQ(res.first, "a");
  456. EXPECT_EQ(res.second, "");
  457. }
  458. {
  459. const auto res = divide("=b", '=');
  460. EXPECT_EQ(res.first, "");
  461. EXPECT_EQ(res.second, "b");
  462. }
  463. {
  464. const auto res = divide("a=b", '=');
  465. EXPECT_EQ(res.first, "a");
  466. EXPECT_EQ(res.second, "b");
  467. }
  468. {
  469. const auto res = divide("a=b=", '=');
  470. EXPECT_EQ(res.first, "a");
  471. EXPECT_EQ(res.second, "b=");
  472. }
  473. {
  474. const auto res = divide("a=b=c", '=');
  475. EXPECT_EQ(res.first, "a");
  476. EXPECT_EQ(res.second, "b=c");
  477. }
  478. }
  479. TEST(SplitTest, ParseQueryString) {
  480. string s = "key1=val1&key2=val2&key3=val3";
  481. Params dic;
  482. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  483. [&](const char *b, const char *e) {
  484. string key, val;
  485. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  486. if (key.empty()) {
  487. key.assign(b2, e2);
  488. } else {
  489. val.assign(b2, e2);
  490. }
  491. });
  492. dic.emplace(key, val);
  493. });
  494. EXPECT_EQ("val1", dic.find("key1")->second);
  495. EXPECT_EQ("val2", dic.find("key2")->second);
  496. EXPECT_EQ("val3", dic.find("key3")->second);
  497. }
  498. TEST(SplitTest, ParseInvalidQueryTests) {
  499. {
  500. string s = " ";
  501. Params dict;
  502. detail::parse_query_text(s, dict);
  503. EXPECT_TRUE(dict.empty());
  504. }
  505. {
  506. string s = " = =";
  507. Params dict;
  508. detail::parse_query_text(s, dict);
  509. EXPECT_TRUE(dict.empty());
  510. }
  511. }
  512. TEST(ParseQueryTest, ParseQueryString) {
  513. {
  514. std::string s = "key1=val1&key2=val2&key3=val3";
  515. Params dic;
  516. detail::parse_query_text(s, dic);
  517. EXPECT_EQ("val1", dic.find("key1")->second);
  518. EXPECT_EQ("val2", dic.find("key2")->second);
  519. EXPECT_EQ("val3", dic.find("key3")->second);
  520. }
  521. {
  522. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  523. Params dic;
  524. detail::parse_query_text(s, dic);
  525. EXPECT_EQ("", dic.find("key1")->second);
  526. EXPECT_EQ("val1", dic.find("key2")->second);
  527. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  528. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  529. }
  530. }
  531. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  532. Params dic;
  533. EXPECT_EQ(detail::params_to_query_str(dic), "");
  534. dic.emplace("key1", "val1");
  535. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  536. dic.emplace("key2", "val2");
  537. dic.emplace("key3", "val3");
  538. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  539. }
  540. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  541. string content_type = "multipart/form-data; boundary=something";
  542. string boundary;
  543. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  544. EXPECT_TRUE(ret);
  545. EXPECT_EQ(boundary, "something");
  546. }
  547. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  548. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  549. string boundary;
  550. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  551. EXPECT_TRUE(ret);
  552. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  553. }
  554. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  555. string content_type =
  556. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  557. string boundary;
  558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  559. EXPECT_TRUE(ret);
  560. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  561. }
  562. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  563. string content_type =
  564. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  565. string boundary;
  566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  567. EXPECT_TRUE(ret);
  568. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  569. }
  570. TEST(GetHeaderValueTest, DefaultValue) {
  571. Headers headers = {{"Dummy", "Dummy"}};
  572. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  573. EXPECT_STREQ("text/plain", val);
  574. }
  575. TEST(GetHeaderValueTest, DefaultValueInt) {
  576. Headers headers = {{"Dummy", "Dummy"}};
  577. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  578. EXPECT_EQ(100ull, val);
  579. }
  580. TEST(GetHeaderValueTest, RegularValue) {
  581. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  582. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  583. EXPECT_STREQ("text/html", val);
  584. }
  585. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  586. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  587. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  588. EXPECT_STREQ("text/html", val);
  589. }
  590. TEST(GetHeaderValueTest, SetContent) {
  591. Response res;
  592. res.set_content("html", "text/html");
  593. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  594. res.set_content("text", "text/plain");
  595. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  596. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  597. }
  598. TEST(GetHeaderValueTest, RegularValueInt) {
  599. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  600. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  601. EXPECT_EQ(100ull, val);
  602. }
  603. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  604. Headers headers = {{"Content-Length", "x"}};
  605. auto is_invalid_value = false;
  606. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  607. is_invalid_value);
  608. EXPECT_EQ(0ull, val);
  609. EXPECT_TRUE(is_invalid_value);
  610. }
  611. TEST(GetHeaderValueTest, Range) {
  612. {
  613. Headers headers = {make_range_header({{1, -1}})};
  614. auto val = detail::get_header_value(headers, "Range", 0, 0);
  615. EXPECT_STREQ("bytes=1-", val);
  616. }
  617. {
  618. Headers headers = {make_range_header({{-1, 1}})};
  619. auto val = detail::get_header_value(headers, "Range", 0, 0);
  620. EXPECT_STREQ("bytes=-1", val);
  621. }
  622. {
  623. Headers headers = {make_range_header({{1, 10}})};
  624. auto val = detail::get_header_value(headers, "Range", 0, 0);
  625. EXPECT_STREQ("bytes=1-10", val);
  626. }
  627. {
  628. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  629. auto val = detail::get_header_value(headers, "Range", 0, 0);
  630. EXPECT_STREQ("bytes=1-10, 100-", val);
  631. }
  632. {
  633. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  634. auto val = detail::get_header_value(headers, "Range", 0, 0);
  635. EXPECT_STREQ("bytes=1-10, 100-200", val);
  636. }
  637. {
  638. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  639. auto val = detail::get_header_value(headers, "Range", 0, 0);
  640. EXPECT_STREQ("bytes=0-0, -1", val);
  641. }
  642. }
  643. TEST(ParseHeaderValueTest, Range) {
  644. {
  645. Ranges ranges;
  646. auto ret = detail::parse_range_header("bytes=1-", ranges);
  647. EXPECT_TRUE(ret);
  648. EXPECT_EQ(1u, ranges.size());
  649. EXPECT_EQ(1u, ranges[0].first);
  650. EXPECT_EQ(-1, ranges[0].second);
  651. }
  652. {
  653. Ranges ranges;
  654. auto ret = detail::parse_range_header("bytes=-1", ranges);
  655. EXPECT_TRUE(ret);
  656. EXPECT_EQ(1u, ranges.size());
  657. EXPECT_EQ(-1, ranges[0].first);
  658. EXPECT_EQ(1u, ranges[0].second);
  659. }
  660. {
  661. Ranges ranges;
  662. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(1u, ranges.size());
  665. EXPECT_EQ(1u, ranges[0].first);
  666. EXPECT_EQ(10u, ranges[0].second);
  667. }
  668. {
  669. Ranges ranges;
  670. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  671. EXPECT_FALSE(ret);
  672. }
  673. {
  674. Ranges ranges;
  675. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  676. EXPECT_TRUE(ret);
  677. EXPECT_EQ(2u, ranges.size());
  678. EXPECT_EQ(1u, ranges[0].first);
  679. EXPECT_EQ(10u, ranges[0].second);
  680. EXPECT_EQ(100u, ranges[1].first);
  681. EXPECT_EQ(-1, ranges[1].second);
  682. }
  683. {
  684. Ranges ranges;
  685. auto ret =
  686. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  687. EXPECT_TRUE(ret);
  688. EXPECT_EQ(3u, ranges.size());
  689. EXPECT_EQ(1u, ranges[0].first);
  690. EXPECT_EQ(10u, ranges[0].second);
  691. EXPECT_EQ(100u, ranges[1].first);
  692. EXPECT_EQ(200u, ranges[1].second);
  693. EXPECT_EQ(300u, ranges[2].first);
  694. EXPECT_EQ(400u, ranges[2].second);
  695. }
  696. {
  697. Ranges ranges;
  698. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  699. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  700. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  701. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  702. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  703. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  704. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  705. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  706. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  707. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  708. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  709. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  710. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  711. EXPECT_TRUE(ranges.empty());
  712. }
  713. }
  714. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  715. Request req;
  716. req.set_header("Accept-Encoding", "gzip");
  717. Response res;
  718. res.set_header("Content-Type", "text/plain");
  719. auto ret = detail::encoding_type(req, res);
  720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  721. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  722. #else
  723. EXPECT_TRUE(ret == detail::EncodingType::None);
  724. #endif
  725. }
  726. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  727. Request req;
  728. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  729. Response res;
  730. res.set_header("Content-Type", "text/plain");
  731. auto ret = detail::encoding_type(req, res);
  732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  733. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  734. #elif CPPHTTPLIB_ZLIB_SUPPORT
  735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  736. #elif CPPHTTPLIB_ZSTD_SUPPORT
  737. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  738. #else
  739. EXPECT_TRUE(ret == detail::EncodingType::None);
  740. #endif
  741. }
  742. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  743. Request req;
  744. req.set_header("Accept-Encoding",
  745. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  746. Response res;
  747. res.set_header("Content-Type", "text/plain");
  748. auto ret = detail::encoding_type(req, res);
  749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  750. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  751. #elif CPPHTTPLIB_ZLIB_SUPPORT
  752. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  753. #elif CPPHTTPLIB_ZSTD_SUPPORT
  754. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  755. #else
  756. EXPECT_TRUE(ret == detail::EncodingType::None);
  757. #endif
  758. }
  759. TEST(BufferStreamTest, read) {
  760. detail::BufferStream strm1;
  761. Stream &strm = strm1;
  762. EXPECT_EQ(5, strm.write("hello"));
  763. char buf[512];
  764. EXPECT_EQ(2, strm.read(buf, 2));
  765. EXPECT_EQ('h', buf[0]);
  766. EXPECT_EQ('e', buf[1]);
  767. EXPECT_EQ(2, strm.read(buf, 2));
  768. EXPECT_EQ('l', buf[0]);
  769. EXPECT_EQ('l', buf[1]);
  770. EXPECT_EQ(1, strm.read(buf, 1));
  771. EXPECT_EQ('o', buf[0]);
  772. EXPECT_EQ(0, strm.read(buf, 1));
  773. }
  774. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  777. auto port = 443;
  778. SSLClient cli(host, port);
  779. #else
  780. auto port = 80;
  781. Client cli(host, port);
  782. #endif
  783. cli.set_connection_timeout(2);
  784. auto res =
  785. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  786. ASSERT_TRUE(res);
  787. std::string out;
  788. read_file("./image.jpg", out);
  789. EXPECT_EQ(StatusCode::OK_200, res->status);
  790. EXPECT_EQ(out, res->body);
  791. }
  792. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  793. auto host = "www.httpwatch.com";
  794. auto ip = hosted_at(host);
  795. EXPECT_EQ("23.96.13.243", ip);
  796. std::vector<std::string> addrs;
  797. hosted_at(host, addrs);
  798. EXPECT_EQ(1u, addrs.size());
  799. }
  800. #if 0 // It depends on each test environment...
  801. TEST(HostnameToIPConversionTest, YouTube_Online) {
  802. auto host = "www.youtube.com";
  803. std::vector<std::string> addrs;
  804. hosted_at(host, addrs);
  805. EXPECT_EQ(20u, addrs.size());
  806. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  807. EXPECT_TRUE(it != addrs.end());
  808. }
  809. #endif
  810. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  811. auto host = "www.httpwatch.com";
  812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  813. auto port = 443;
  814. SSLClient cli(host, port);
  815. #else
  816. auto port = 80;
  817. Client cli(host, port);
  818. #endif
  819. cli.set_connection_timeout(2);
  820. std::string body;
  821. auto res =
  822. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  823. [&](const char *data, size_t data_length) {
  824. body.append(data, data_length);
  825. return true;
  826. });
  827. ASSERT_TRUE(res);
  828. std::string out;
  829. read_file("./image.jpg", out);
  830. EXPECT_EQ(StatusCode::OK_200, res->status);
  831. EXPECT_EQ(out, body);
  832. }
  833. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  834. auto host = "www.httpwatch.com";
  835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  836. auto port = 443;
  837. SSLClient cli(host, port);
  838. #else
  839. auto port = 80;
  840. Client cli(host, port);
  841. #endif
  842. cli.set_connection_timeout(2);
  843. std::string body;
  844. auto res = cli.Get(
  845. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  846. [&](const Response &response) {
  847. EXPECT_EQ(StatusCode::OK_200, response.status);
  848. return true;
  849. },
  850. [&](const char *data, size_t data_length) {
  851. body.append(data, data_length);
  852. return true;
  853. });
  854. ASSERT_TRUE(res);
  855. std::string out;
  856. read_file("./image.jpg", out);
  857. EXPECT_EQ(StatusCode::OK_200, res->status);
  858. EXPECT_EQ(out, body);
  859. }
  860. TEST(RangeTest, FromHTTPBin_Online) {
  861. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  862. auto host = "httpbin.org";
  863. auto path = std::string{"/range/32"};
  864. #else
  865. auto host = "nghttp2.org";
  866. auto path = std::string{"/httpbin/range/32"};
  867. #endif
  868. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  869. auto port = 443;
  870. SSLClient cli(host, port);
  871. #else
  872. auto port = 80;
  873. Client cli(host, port);
  874. #endif
  875. cli.set_connection_timeout(5);
  876. {
  877. auto res = cli.Get(path);
  878. ASSERT_TRUE(res);
  879. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  880. EXPECT_EQ(StatusCode::OK_200, res->status);
  881. }
  882. {
  883. Headers headers = {make_range_header({{1, -1}})};
  884. auto res = cli.Get(path, headers);
  885. ASSERT_TRUE(res);
  886. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  888. }
  889. {
  890. Headers headers = {make_range_header({{1, 10}})};
  891. auto res = cli.Get(path, headers);
  892. ASSERT_TRUE(res);
  893. EXPECT_EQ("bcdefghijk", res->body);
  894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  895. }
  896. {
  897. Headers headers = {make_range_header({{0, 31}})};
  898. auto res = cli.Get(path, headers);
  899. ASSERT_TRUE(res);
  900. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  901. EXPECT_EQ(StatusCode::OK_200, res->status);
  902. }
  903. {
  904. Headers headers = {make_range_header({{0, -1}})};
  905. auto res = cli.Get(path, headers);
  906. ASSERT_TRUE(res);
  907. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  908. EXPECT_EQ(StatusCode::OK_200, res->status);
  909. }
  910. {
  911. Headers headers = {make_range_header({{0, 32}})};
  912. auto res = cli.Get(path, headers);
  913. ASSERT_TRUE(res);
  914. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  915. }
  916. }
  917. TEST(ConnectionErrorTest, InvalidHost) {
  918. auto host = "-abcde.com";
  919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  920. auto port = 443;
  921. SSLClient cli(host, port);
  922. #else
  923. auto port = 80;
  924. Client cli(host, port);
  925. #endif
  926. cli.set_connection_timeout(std::chrono::seconds(2));
  927. auto res = cli.Get("/");
  928. ASSERT_TRUE(!res);
  929. EXPECT_EQ(Error::Connection, res.error());
  930. }
  931. TEST(ConnectionErrorTest, InvalidHost2) {
  932. auto host = "httpbin.org/";
  933. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  934. SSLClient cli(host);
  935. #else
  936. Client cli(host);
  937. #endif
  938. cli.set_connection_timeout(std::chrono::seconds(2));
  939. auto res = cli.Get("/");
  940. ASSERT_TRUE(!res);
  941. EXPECT_EQ(Error::Connection, res.error());
  942. }
  943. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  944. auto host = "httpbin.org/";
  945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  946. SSLClient cli(host);
  947. #else
  948. Client cli(host);
  949. #endif
  950. cli.set_connection_timeout(std::chrono::seconds(2));
  951. auto res = cli.Get("/");
  952. ASSERT_TRUE(!res);
  953. stringstream s;
  954. s << "error code: " << res.error();
  955. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  956. }
  957. TEST(ConnectionErrorTest, InvalidPort) {
  958. auto host = "localhost";
  959. auto port = 44380;
  960. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  961. SSLClient cli(host, port);
  962. #else
  963. Client cli(host, port);
  964. #endif
  965. cli.set_connection_timeout(std::chrono::seconds(2));
  966. auto res = cli.Get("/");
  967. ASSERT_TRUE(!res);
  968. EXPECT_TRUE(Error::Connection == res.error() ||
  969. Error::ConnectionTimeout == res.error());
  970. }
  971. TEST(ConnectionErrorTest, Timeout_Online) {
  972. auto host = "google.com";
  973. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  974. auto port = 44380;
  975. SSLClient cli(host, port);
  976. #else
  977. auto port = 8080;
  978. Client cli(host, port);
  979. #endif
  980. cli.set_connection_timeout(std::chrono::seconds(2));
  981. // only probe one address type so that the error reason
  982. // correlates to the timed-out IPv4, not the unsupported
  983. // IPv6 connection attempt
  984. cli.set_address_family(AF_INET);
  985. auto res = cli.Get("/");
  986. ASSERT_TRUE(!res);
  987. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  988. }
  989. TEST(CancelTest, NoCancel_Online) {
  990. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  991. auto host = "httpbin.org";
  992. auto path = std::string{"/range/32"};
  993. #else
  994. auto host = "nghttp2.org";
  995. auto path = std::string{"/httpbin/range/32"};
  996. #endif
  997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  998. auto port = 443;
  999. SSLClient cli(host, port);
  1000. #else
  1001. auto port = 80;
  1002. Client cli(host, port);
  1003. #endif
  1004. cli.set_connection_timeout(std::chrono::seconds(5));
  1005. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1006. ASSERT_TRUE(res);
  1007. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1008. EXPECT_EQ(StatusCode::OK_200, res->status);
  1009. }
  1010. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1011. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1012. auto host = "httpbin.org";
  1013. auto path = std::string{"/range/32"};
  1014. #else
  1015. auto host = "nghttp2.org";
  1016. auto path = std::string{"/httpbin/range/32"};
  1017. #endif
  1018. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1019. auto port = 443;
  1020. SSLClient cli(host, port);
  1021. #else
  1022. auto port = 80;
  1023. Client cli(host, port);
  1024. #endif
  1025. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1026. cli.set_connection_timeout(std::chrono::seconds(5));
  1027. ASSERT_TRUE(!res);
  1028. EXPECT_EQ(Error::Canceled, res.error());
  1029. }
  1030. TEST(CancelTest, WithCancelLargePayload_Online) {
  1031. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1032. auto host = "httpbin.org";
  1033. auto path = std::string{"/range/65536"};
  1034. #else
  1035. auto host = "nghttp2.org";
  1036. auto path = std::string{"/httpbin/range/65536"};
  1037. #endif
  1038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1039. auto port = 443;
  1040. SSLClient cli(host, port);
  1041. #else
  1042. auto port = 80;
  1043. Client cli(host, port);
  1044. #endif
  1045. cli.set_connection_timeout(std::chrono::seconds(5));
  1046. uint32_t count = 0;
  1047. auto res =
  1048. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1049. ASSERT_TRUE(!res);
  1050. EXPECT_EQ(Error::Canceled, res.error());
  1051. }
  1052. TEST(CancelTest, NoCancelPost) {
  1053. Server svr;
  1054. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1055. res.set_content("Hello World!", "text/plain");
  1056. });
  1057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1058. auto se = detail::scope_exit([&] {
  1059. svr.stop();
  1060. thread.join();
  1061. ASSERT_FALSE(svr.is_running());
  1062. });
  1063. svr.wait_until_ready();
  1064. Client cli(HOST, PORT);
  1065. cli.set_connection_timeout(std::chrono::seconds(5));
  1066. auto res =
  1067. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1068. "application/json", [](uint64_t, uint64_t) { return true; });
  1069. ASSERT_TRUE(res);
  1070. EXPECT_EQ("Hello World!", res->body);
  1071. EXPECT_EQ(StatusCode::OK_200, res->status);
  1072. }
  1073. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1074. Server svr;
  1075. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1076. res.set_content("Hello World!", "text/plain");
  1077. });
  1078. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1079. auto se = detail::scope_exit([&] {
  1080. svr.stop();
  1081. thread.join();
  1082. ASSERT_FALSE(svr.is_running());
  1083. });
  1084. svr.wait_until_ready();
  1085. Client cli(HOST, PORT);
  1086. cli.set_connection_timeout(std::chrono::seconds(5));
  1087. auto res =
  1088. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1089. "application/json", [](uint64_t, uint64_t) { return false; });
  1090. ASSERT_TRUE(!res);
  1091. EXPECT_EQ(Error::Canceled, res.error());
  1092. }
  1093. TEST(CancelTest, WithCancelLargePayloadPost) {
  1094. Server svr;
  1095. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1096. res.set_content(LARGE_DATA, "text/plain");
  1097. });
  1098. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1099. auto se = detail::scope_exit([&] {
  1100. svr.stop();
  1101. thread.join();
  1102. ASSERT_FALSE(svr.is_running());
  1103. });
  1104. svr.wait_until_ready();
  1105. Client cli(HOST, PORT);
  1106. cli.set_connection_timeout(std::chrono::seconds(5));
  1107. auto res =
  1108. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1109. "application/json", [](uint64_t, uint64_t) { return false; });
  1110. ASSERT_TRUE(!res);
  1111. EXPECT_EQ(Error::Canceled, res.error());
  1112. }
  1113. TEST(CancelTest, NoCancelPut) {
  1114. Server svr;
  1115. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1116. res.set_content("Hello World!", "text/plain");
  1117. });
  1118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1119. auto se = detail::scope_exit([&] {
  1120. svr.stop();
  1121. thread.join();
  1122. ASSERT_FALSE(svr.is_running());
  1123. });
  1124. svr.wait_until_ready();
  1125. Client cli(HOST, PORT);
  1126. cli.set_connection_timeout(std::chrono::seconds(5));
  1127. auto res =
  1128. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1129. "application/json", [](uint64_t, uint64_t) { return true; });
  1130. ASSERT_TRUE(res);
  1131. EXPECT_EQ("Hello World!", res->body);
  1132. EXPECT_EQ(StatusCode::OK_200, res->status);
  1133. }
  1134. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1135. Server svr;
  1136. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1137. res.set_content("Hello World!", "text/plain");
  1138. });
  1139. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1140. auto se = detail::scope_exit([&] {
  1141. svr.stop();
  1142. thread.join();
  1143. ASSERT_FALSE(svr.is_running());
  1144. });
  1145. svr.wait_until_ready();
  1146. Client cli(HOST, PORT);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res =
  1149. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1150. "application/json", [](uint64_t, uint64_t) { return false; });
  1151. ASSERT_TRUE(!res);
  1152. EXPECT_EQ(Error::Canceled, res.error());
  1153. }
  1154. TEST(CancelTest, WithCancelLargePayloadPut) {
  1155. Server svr;
  1156. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1157. res.set_content(LARGE_DATA, "text/plain");
  1158. });
  1159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1160. auto se = detail::scope_exit([&] {
  1161. svr.stop();
  1162. thread.join();
  1163. ASSERT_FALSE(svr.is_running());
  1164. });
  1165. svr.wait_until_ready();
  1166. Client cli(HOST, PORT);
  1167. cli.set_connection_timeout(std::chrono::seconds(5));
  1168. auto res =
  1169. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1170. "application/json", [](uint64_t, uint64_t) { return false; });
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Canceled, res.error());
  1173. }
  1174. TEST(CancelTest, NoCancelPatch) {
  1175. Server svr;
  1176. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1177. res.set_content("Hello World!", "text/plain");
  1178. });
  1179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1180. auto se = detail::scope_exit([&] {
  1181. svr.stop();
  1182. thread.join();
  1183. ASSERT_FALSE(svr.is_running());
  1184. });
  1185. svr.wait_until_ready();
  1186. Client cli(HOST, PORT);
  1187. cli.set_connection_timeout(std::chrono::seconds(5));
  1188. auto res =
  1189. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1190. "application/json", [](uint64_t, uint64_t) { return true; });
  1191. ASSERT_TRUE(res);
  1192. EXPECT_EQ("Hello World!", res->body);
  1193. EXPECT_EQ(StatusCode::OK_200, res->status);
  1194. }
  1195. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1196. Server svr;
  1197. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1198. res.set_content("Hello World!", "text/plain");
  1199. });
  1200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1201. auto se = detail::scope_exit([&] {
  1202. svr.stop();
  1203. thread.join();
  1204. ASSERT_FALSE(svr.is_running());
  1205. });
  1206. svr.wait_until_ready();
  1207. Client cli(HOST, PORT);
  1208. cli.set_connection_timeout(std::chrono::seconds(5));
  1209. auto res =
  1210. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1211. "application/json", [](uint64_t, uint64_t) { return false; });
  1212. ASSERT_TRUE(!res);
  1213. EXPECT_EQ(Error::Canceled, res.error());
  1214. }
  1215. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1216. Server svr;
  1217. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1218. res.set_content(LARGE_DATA, "text/plain");
  1219. });
  1220. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1221. auto se = detail::scope_exit([&] {
  1222. svr.stop();
  1223. thread.join();
  1224. ASSERT_FALSE(svr.is_running());
  1225. });
  1226. svr.wait_until_ready();
  1227. Client cli(HOST, PORT);
  1228. cli.set_connection_timeout(std::chrono::seconds(5));
  1229. auto res =
  1230. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1231. "application/json", [](uint64_t, uint64_t) { return false; });
  1232. ASSERT_TRUE(!res);
  1233. EXPECT_EQ(Error::Canceled, res.error());
  1234. }
  1235. TEST(CancelTest, NoCancelDelete) {
  1236. Server svr;
  1237. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1238. res.set_content("Hello World!", "text/plain");
  1239. });
  1240. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. thread.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. Client cli(HOST, PORT);
  1248. cli.set_connection_timeout(std::chrono::seconds(5));
  1249. auto res =
  1250. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1251. "application/json", [](uint64_t, uint64_t) { return true; });
  1252. ASSERT_TRUE(res);
  1253. EXPECT_EQ("Hello World!", res->body);
  1254. EXPECT_EQ(StatusCode::OK_200, res->status);
  1255. }
  1256. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1257. Server svr;
  1258. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1259. res.set_content("Hello World!", "text/plain");
  1260. });
  1261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1262. auto se = detail::scope_exit([&] {
  1263. svr.stop();
  1264. thread.join();
  1265. ASSERT_FALSE(svr.is_running());
  1266. });
  1267. svr.wait_until_ready();
  1268. Client cli(HOST, PORT);
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. auto res =
  1271. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1272. "application/json", [](uint64_t, uint64_t) { return false; });
  1273. ASSERT_TRUE(!res);
  1274. EXPECT_EQ(Error::Canceled, res.error());
  1275. }
  1276. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1277. Server svr;
  1278. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1279. res.set_content(LARGE_DATA, "text/plain");
  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. svr.wait_until_ready();
  1288. Client cli(HOST, PORT);
  1289. cli.set_connection_timeout(std::chrono::seconds(5));
  1290. auto res =
  1291. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1292. "application/json", [](uint64_t, uint64_t) { return false; });
  1293. ASSERT_TRUE(!res);
  1294. EXPECT_EQ(Error::Canceled, res.error());
  1295. }
  1296. static std::string remove_whitespace(const std::string &input) {
  1297. std::string output;
  1298. output.reserve(input.size());
  1299. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1300. [](unsigned char c) { return !std::isspace(c); });
  1301. return output;
  1302. }
  1303. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1304. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1305. auto host = "httpbin.org";
  1306. auto path = std::string{"/basic-auth/hello/world"};
  1307. #else
  1308. auto host = "nghttp2.org";
  1309. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1310. #endif
  1311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1312. auto port = 443;
  1313. SSLClient cli(host, port);
  1314. #else
  1315. auto port = 80;
  1316. Client cli(host, port);
  1317. #endif
  1318. {
  1319. auto res = cli.Get(path);
  1320. ASSERT_TRUE(res);
  1321. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1322. }
  1323. {
  1324. auto res =
  1325. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1326. ASSERT_TRUE(res);
  1327. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1328. remove_whitespace(res->body));
  1329. EXPECT_EQ(StatusCode::OK_200, res->status);
  1330. }
  1331. {
  1332. cli.set_basic_auth("hello", "world");
  1333. auto res = cli.Get(path);
  1334. ASSERT_TRUE(res);
  1335. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1336. remove_whitespace(res->body));
  1337. EXPECT_EQ(StatusCode::OK_200, res->status);
  1338. }
  1339. {
  1340. cli.set_basic_auth("hello", "bad");
  1341. auto res = cli.Get(path);
  1342. ASSERT_TRUE(res);
  1343. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1344. }
  1345. {
  1346. cli.set_basic_auth("bad", "world");
  1347. auto res = cli.Get(path);
  1348. ASSERT_TRUE(res);
  1349. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1350. }
  1351. }
  1352. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1353. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1354. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1355. auto host = "httpbin.org";
  1356. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1357. auto paths = std::vector<std::string>{
  1358. "/digest-auth/auth/hello/world/MD5",
  1359. "/digest-auth/auth/hello/world/SHA-256",
  1360. "/digest-auth/auth/hello/world/SHA-512",
  1361. "/digest-auth/auth-int/hello/world/MD5",
  1362. };
  1363. #else
  1364. auto host = "nghttp2.org";
  1365. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1366. auto paths = std::vector<std::string>{
  1367. "/httpbin/digest-auth/auth/hello/world/MD5",
  1368. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1369. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1370. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1371. };
  1372. #endif
  1373. auto port = 443;
  1374. SSLClient cli(host, port);
  1375. {
  1376. auto res = cli.Get(unauth_path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. {
  1381. cli.set_digest_auth("hello", "world");
  1382. for (const auto &path : paths) {
  1383. auto res = cli.Get(path.c_str());
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1386. remove_whitespace(res->body));
  1387. EXPECT_EQ(StatusCode::OK_200, res->status);
  1388. }
  1389. cli.set_digest_auth("hello", "bad");
  1390. for (const auto &path : paths) {
  1391. auto res = cli.Get(path.c_str());
  1392. ASSERT_TRUE(res);
  1393. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1394. }
  1395. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1396. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1397. // cli.set_digest_auth("bad", "world");
  1398. // for (const auto& path : paths) {
  1399. // auto res = cli.Get(path.c_str());
  1400. // ASSERT_TRUE(res);
  1401. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1402. // }
  1403. }
  1404. }
  1405. #endif
  1406. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1407. auto host = "google.com";
  1408. auto another_host = "example.com";
  1409. auto wrong_ip = "0.0.0.0";
  1410. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1411. SSLClient cli(host);
  1412. #else
  1413. Client cli(host);
  1414. #endif
  1415. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1416. auto res = cli.Get("/");
  1417. ASSERT_TRUE(res);
  1418. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1419. }
  1420. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1421. auto host = "google.com";
  1422. auto wrong_ip = "0.0.0.0";
  1423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1424. SSLClient cli(host);
  1425. #else
  1426. Client cli(host);
  1427. #endif
  1428. cli.set_hostname_addr_map({{host, wrong_ip}});
  1429. auto res = cli.Get("/");
  1430. ASSERT_TRUE(!res);
  1431. EXPECT_EQ(Error::Connection, res.error());
  1432. }
  1433. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1434. auto host = "nghttp2.org";
  1435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1436. SSLClient cli(host);
  1437. #else
  1438. Client cli(host);
  1439. #endif
  1440. cli.set_follow_location(true);
  1441. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1442. ASSERT_TRUE(res);
  1443. EXPECT_EQ(StatusCode::OK_200, res->status);
  1444. }
  1445. TEST(RedirectTest, Redirect_Online) {
  1446. auto host = "nghttp2.org";
  1447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1448. SSLClient cli(host);
  1449. #else
  1450. Client cli(host);
  1451. #endif
  1452. cli.set_follow_location(true);
  1453. auto res = cli.Get("/httpbin/redirect/3");
  1454. ASSERT_TRUE(res);
  1455. EXPECT_EQ(StatusCode::OK_200, res->status);
  1456. }
  1457. TEST(RelativeRedirectTest, Redirect_Online) {
  1458. auto host = "nghttp2.org";
  1459. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1460. SSLClient cli(host);
  1461. #else
  1462. Client cli(host);
  1463. #endif
  1464. cli.set_follow_location(true);
  1465. auto res = cli.Get("/httpbin/relative-redirect/3");
  1466. ASSERT_TRUE(res);
  1467. EXPECT_EQ(StatusCode::OK_200, res->status);
  1468. }
  1469. TEST(TooManyRedirectTest, Redirect_Online) {
  1470. auto host = "nghttp2.org";
  1471. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1472. SSLClient cli(host);
  1473. #else
  1474. Client cli(host);
  1475. #endif
  1476. cli.set_follow_location(true);
  1477. auto res = cli.Get("/httpbin/redirect/21");
  1478. ASSERT_TRUE(!res);
  1479. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1480. }
  1481. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1482. TEST(YahooRedirectTest, Redirect_Online) {
  1483. Client cli("yahoo.com");
  1484. auto res = cli.Get("/");
  1485. ASSERT_TRUE(res);
  1486. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1487. cli.set_follow_location(true);
  1488. res = cli.Get("/");
  1489. ASSERT_TRUE(res);
  1490. EXPECT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1492. }
  1493. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1494. #define REDIR_HOST "httpbingo.org"
  1495. #define REDIR_PATH "/redirect-to"
  1496. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1497. SSLClient cli(REDIR_HOST);
  1498. cli.set_follow_location(true);
  1499. auto res =
  1500. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1501. ASSERT_TRUE(res);
  1502. EXPECT_EQ(StatusCode::OK_200, res->status);
  1503. }
  1504. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1505. SSLClient cli(REDIR_HOST);
  1506. cli.set_follow_location(true);
  1507. Params params;
  1508. params.emplace("url", "http://example.com");
  1509. params.emplace("status_code", "302");
  1510. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1511. ASSERT_TRUE(res);
  1512. EXPECT_EQ(StatusCode::OK_200, res->status);
  1513. }
  1514. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1515. SSLClient cli(REDIR_HOST);
  1516. cli.set_follow_location(true);
  1517. Params params;
  1518. params.emplace("url", "http://example.com");
  1519. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1520. ASSERT_TRUE(res);
  1521. EXPECT_EQ(StatusCode::OK_200, res->status);
  1522. }
  1523. TEST(UrlWithSpace, Redirect_Online) {
  1524. SSLClient cli("edge.forgecdn.net");
  1525. cli.set_follow_location(true);
  1526. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1530. }
  1531. #endif
  1532. #if !defined(_WIN32) && !defined(_WIN64)
  1533. TEST(ReceiveSignals, Signal) {
  1534. auto setupSignalHandlers = []() {
  1535. struct sigaction act;
  1536. sigemptyset(&act.sa_mask);
  1537. act.sa_flags = SA_SIGINFO;
  1538. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1539. switch (sig) {
  1540. case SIGINT:
  1541. default: break;
  1542. }
  1543. };
  1544. ::sigaction(SIGINT, &act, nullptr);
  1545. };
  1546. Server svr;
  1547. int port = 0;
  1548. auto thread = std::thread([&]() {
  1549. setupSignalHandlers();
  1550. port = svr.bind_to_any_port("localhost");
  1551. svr.listen_after_bind();
  1552. });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. ASSERT_TRUE(svr.is_running());
  1560. pthread_kill(thread.native_handle(), SIGINT);
  1561. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1562. ASSERT_TRUE(svr.is_running());
  1563. }
  1564. #endif
  1565. TEST(RedirectToDifferentPort, Redirect) {
  1566. Server svr1;
  1567. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1568. res.set_content("Hello World!", "text/plain");
  1569. });
  1570. int svr1_port = 0;
  1571. auto thread1 = std::thread([&]() {
  1572. svr1_port = svr1.bind_to_any_port("localhost");
  1573. svr1.listen_after_bind();
  1574. });
  1575. Server svr2;
  1576. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1577. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1578. });
  1579. int svr2_port = 0;
  1580. auto thread2 = std::thread([&]() {
  1581. svr2_port = svr2.bind_to_any_port("localhost");
  1582. svr2.listen_after_bind();
  1583. });
  1584. auto se = detail::scope_exit([&] {
  1585. svr2.stop();
  1586. thread2.join();
  1587. svr1.stop();
  1588. thread1.join();
  1589. ASSERT_FALSE(svr2.is_running());
  1590. ASSERT_FALSE(svr1.is_running());
  1591. });
  1592. svr1.wait_until_ready();
  1593. svr2.wait_until_ready();
  1594. Client cli("localhost", svr2_port);
  1595. cli.set_follow_location(true);
  1596. auto res = cli.Get("/2");
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ(StatusCode::OK_200, res->status);
  1599. EXPECT_EQ("Hello World!", res->body);
  1600. }
  1601. TEST(RedirectFromPageWithContent, Redirect) {
  1602. Server svr;
  1603. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1604. res.set_content("___", "text/plain");
  1605. res.set_redirect("/2");
  1606. });
  1607. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1608. res.set_content("Hello World!", "text/plain");
  1609. });
  1610. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1611. auto se = detail::scope_exit([&] {
  1612. svr.stop();
  1613. th.join();
  1614. ASSERT_FALSE(svr.is_running());
  1615. });
  1616. svr.wait_until_ready();
  1617. {
  1618. Client cli("localhost", PORT);
  1619. cli.set_follow_location(true);
  1620. std::string body;
  1621. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1622. body.append(data, data_length);
  1623. return true;
  1624. });
  1625. ASSERT_TRUE(res);
  1626. EXPECT_EQ(StatusCode::OK_200, res->status);
  1627. EXPECT_EQ("Hello World!", body);
  1628. }
  1629. {
  1630. Client cli("localhost", PORT);
  1631. std::string body;
  1632. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1633. body.append(data, data_length);
  1634. return true;
  1635. });
  1636. ASSERT_TRUE(res);
  1637. EXPECT_EQ(StatusCode::Found_302, res->status);
  1638. EXPECT_EQ("___", body);
  1639. }
  1640. }
  1641. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1642. Server svr;
  1643. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1644. res.set_content("___", "text/plain");
  1645. // res.set_redirect("/2");
  1646. res.set_redirect("http://[::1]:1234/2");
  1647. });
  1648. svr.Get("/2", [&](const Request &req, Response &res) {
  1649. auto host_header = req.headers.find("Host");
  1650. ASSERT_TRUE(host_header != req.headers.end());
  1651. EXPECT_EQ("[::1]:1234", host_header->second);
  1652. res.set_content("Hello World!", "text/plain");
  1653. });
  1654. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1655. auto se = detail::scope_exit([&] {
  1656. svr.stop();
  1657. th.join();
  1658. ASSERT_FALSE(svr.is_running());
  1659. });
  1660. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1661. // actually starts anything, so the condition !svr.is_running() will
  1662. // always remain true, and the loop never stops.
  1663. // This basically counts how many milliseconds have passed since the
  1664. // call to svr.listen(), and if after 5 seconds nothing started yet
  1665. // aborts the test.
  1666. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1667. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1668. ASSERT_LT(milliseconds, 5000U);
  1669. }
  1670. {
  1671. Client cli("http://[::1]:1234");
  1672. cli.set_follow_location(true);
  1673. std::string body;
  1674. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1675. body.append(data, data_length);
  1676. return true;
  1677. });
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::OK_200, res->status);
  1680. EXPECT_EQ("Hello World!", body);
  1681. }
  1682. {
  1683. Client cli("http://[::1]:1234");
  1684. std::string body;
  1685. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1686. body.append(data, data_length);
  1687. return true;
  1688. });
  1689. ASSERT_TRUE(res);
  1690. EXPECT_EQ(StatusCode::Found_302, res->status);
  1691. EXPECT_EQ("___", body);
  1692. }
  1693. }
  1694. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1695. Server svr;
  1696. svr.Get("/foo", [](const Request &req, Response &res) {
  1697. auto a = req.params.find("a");
  1698. if (a != req.params.end()) {
  1699. res.set_content((*a).second, "text/plain");
  1700. res.status = StatusCode::OK_200;
  1701. } else {
  1702. res.status = StatusCode::BadRequest_400;
  1703. }
  1704. });
  1705. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1706. auto se = detail::scope_exit([&] {
  1707. svr.stop();
  1708. thread.join();
  1709. ASSERT_FALSE(svr.is_running());
  1710. });
  1711. svr.wait_until_ready();
  1712. {
  1713. Client cli(HOST, PORT);
  1714. cli.set_url_encode(false);
  1715. auto res = cli.Get("/foo?a=explicitly+encoded");
  1716. ASSERT_TRUE(res);
  1717. EXPECT_EQ(StatusCode::OK_200, res->status);
  1718. // This expects it back with a space, as the `+` won't have been
  1719. // url-encoded, and server-side the params get decoded turning `+`
  1720. // into spaces.
  1721. EXPECT_EQ("explicitly encoded", res->body);
  1722. }
  1723. }
  1724. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1725. Server svr;
  1726. svr.Get("/", [](const Request &req, Response &) {
  1727. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1728. });
  1729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1730. auto se = detail::scope_exit([&] {
  1731. svr.stop();
  1732. thread.join();
  1733. ASSERT_FALSE(svr.is_running());
  1734. });
  1735. svr.wait_until_ready();
  1736. {
  1737. Client cli(HOST, PORT);
  1738. cli.set_url_encode(false);
  1739. auto res = cli.Get("/?something=%0A");
  1740. ASSERT_TRUE(res);
  1741. EXPECT_EQ(StatusCode::OK_200, res->status);
  1742. }
  1743. }
  1744. TEST(BindServerTest, DISABLED_BindDualStack) {
  1745. Server svr;
  1746. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1747. res.set_content("Hello World!", "text/plain");
  1748. });
  1749. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1750. auto se = detail::scope_exit([&] {
  1751. svr.stop();
  1752. thread.join();
  1753. ASSERT_FALSE(svr.is_running());
  1754. });
  1755. svr.wait_until_ready();
  1756. {
  1757. Client cli("127.0.0.1", PORT);
  1758. auto res = cli.Get("/1");
  1759. ASSERT_TRUE(res);
  1760. EXPECT_EQ(StatusCode::OK_200, res->status);
  1761. EXPECT_EQ("Hello World!", res->body);
  1762. }
  1763. {
  1764. Client cli("::1", PORT);
  1765. auto res = cli.Get("/1");
  1766. ASSERT_TRUE(res);
  1767. EXPECT_EQ(StatusCode::OK_200, res->status);
  1768. EXPECT_EQ("Hello World!", res->body);
  1769. }
  1770. }
  1771. TEST(BindServerTest, BindAndListenSeparately) {
  1772. Server svr;
  1773. int port = svr.bind_to_any_port("0.0.0.0");
  1774. ASSERT_TRUE(svr.is_valid());
  1775. ASSERT_TRUE(port > 0);
  1776. svr.stop();
  1777. }
  1778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1779. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1781. CLIENT_CA_CERT_DIR);
  1782. int port = svr.bind_to_any_port("0.0.0.0");
  1783. ASSERT_TRUE(svr.is_valid());
  1784. ASSERT_TRUE(port > 0);
  1785. svr.stop();
  1786. }
  1787. #endif
  1788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1789. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1790. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1791. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1792. int port = svr.bind_to_any_port("0.0.0.0");
  1793. ASSERT_TRUE(svr.is_valid());
  1794. ASSERT_TRUE(port > 0);
  1795. svr.stop();
  1796. }
  1797. #endif
  1798. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1799. X509 *readCertificate(const std::string &strFileName) {
  1800. std::ifstream inStream(strFileName);
  1801. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1802. std::istreambuf_iterator<char>());
  1803. if (strCertPEM.empty()) return (nullptr);
  1804. BIO *pbCert = BIO_new(BIO_s_mem());
  1805. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1806. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1807. BIO_free(pbCert);
  1808. return (pCert);
  1809. }
  1810. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1811. std::ifstream inStream(strFileName);
  1812. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1813. std::istreambuf_iterator<char>());
  1814. if (strPrivateKeyPEM.empty()) return (nullptr);
  1815. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1816. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1817. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1818. BIO_free(pbPrivKey);
  1819. return (pPrivateKey);
  1820. }
  1821. TEST(BindServerTest, UpdateCerts) {
  1822. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1823. int port = svr.bind_to_any_port("0.0.0.0");
  1824. ASSERT_TRUE(svr.is_valid());
  1825. ASSERT_TRUE(port > 0);
  1826. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1827. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1828. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1829. ASSERT_TRUE(cert != nullptr);
  1830. ASSERT_TRUE(ca_cert != nullptr);
  1831. ASSERT_TRUE(key != nullptr);
  1832. X509_STORE *cert_store = X509_STORE_new();
  1833. X509_STORE_add_cert(cert_store, ca_cert);
  1834. svr.update_certs(cert, key, cert_store);
  1835. ASSERT_TRUE(svr.is_valid());
  1836. svr.stop();
  1837. X509_free(cert);
  1838. X509_free(ca_cert);
  1839. EVP_PKEY_free(key);
  1840. }
  1841. #endif
  1842. TEST(ErrorHandlerTest, ContentLength) {
  1843. Server svr;
  1844. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1845. res.status = StatusCode::OK_200;
  1846. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1847. "text/html"); // <= Content-Length still 13
  1848. });
  1849. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1850. res.set_content("Hello World!\n", "text/plain");
  1851. res.status = 524;
  1852. });
  1853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. thread.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli(HOST, PORT);
  1862. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::OK_200, res->status);
  1865. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1866. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1867. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1868. }
  1869. }
  1870. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1871. TEST(ExceptionTest, WithoutExceptionHandler) {
  1872. Server svr;
  1873. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1874. throw std::runtime_error("exception...");
  1875. });
  1876. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1877. throw std::runtime_error("exception\r\n...");
  1878. });
  1879. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. listen_thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. Client cli("localhost", PORT);
  1887. {
  1888. auto res = cli.Get("/exception");
  1889. ASSERT_TRUE(res);
  1890. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1891. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1892. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1893. }
  1894. {
  1895. auto res = cli.Get("/unknown");
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1898. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1899. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1900. }
  1901. }
  1902. TEST(ExceptionTest, WithExceptionHandler) {
  1903. Server svr;
  1904. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1905. std::exception_ptr ep) {
  1906. EXPECT_FALSE(ep == nullptr);
  1907. try {
  1908. std::rethrow_exception(ep);
  1909. } catch (std::exception &e) {
  1910. EXPECT_EQ("abc", std::string(e.what()));
  1911. } catch (...) {}
  1912. res.status = StatusCode::InternalServerError_500;
  1913. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1914. "text/html"); // <= Content-Length still 13 at this point
  1915. });
  1916. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1917. res.set_content("Hello World!\n", "text/plain");
  1918. throw std::runtime_error("abc");
  1919. });
  1920. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1921. auto se = detail::scope_exit([&] {
  1922. svr.stop();
  1923. thread.join();
  1924. ASSERT_FALSE(svr.is_running());
  1925. });
  1926. svr.wait_until_ready();
  1927. for (size_t i = 0; i < 10; i++) {
  1928. Client cli(HOST, PORT);
  1929. for (size_t j = 0; j < 100; j++) {
  1930. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1931. ASSERT_TRUE(res);
  1932. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1933. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1934. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1935. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1936. }
  1937. cli.set_keep_alive(true);
  1938. for (size_t j = 0; j < 100; j++) {
  1939. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1942. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1943. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1944. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1945. }
  1946. }
  1947. }
  1948. TEST(ExceptionTest, AndErrorHandler) {
  1949. Server svr;
  1950. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1951. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1952. });
  1953. svr.set_exception_handler(
  1954. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1955. EXPECT_FALSE(ep == nullptr);
  1956. try {
  1957. std::rethrow_exception(ep);
  1958. } catch (std::exception &e) {
  1959. res.set_content(e.what(), "text/html");
  1960. } catch (...) {}
  1961. res.status = StatusCode::InternalServerError_500;
  1962. });
  1963. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1964. throw std::runtime_error("EXCEPTION");
  1965. });
  1966. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1967. res.set_content("ERROR", "text/html");
  1968. res.status = StatusCode::InternalServerError_500;
  1969. });
  1970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1971. auto se = detail::scope_exit([&] {
  1972. svr.stop();
  1973. thread.join();
  1974. ASSERT_FALSE(svr.is_running());
  1975. });
  1976. svr.wait_until_ready();
  1977. Client cli(HOST, PORT);
  1978. {
  1979. auto res = cli.Get("/exception");
  1980. ASSERT_TRUE(res);
  1981. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1982. EXPECT_EQ("EXCEPTION", res->body);
  1983. }
  1984. {
  1985. auto res = cli.Get("/error");
  1986. ASSERT_TRUE(res);
  1987. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1988. EXPECT_EQ("ERROR", res->body);
  1989. }
  1990. {
  1991. auto res = cli.Get("/invalid");
  1992. ASSERT_TRUE(res);
  1993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1994. EXPECT_EQ("NOT_FOUND", res->body);
  1995. }
  1996. }
  1997. #endif
  1998. TEST(NoContentTest, ContentLength) {
  1999. Server svr;
  2000. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2001. res.status = StatusCode::NoContent_204;
  2002. });
  2003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2004. auto se = detail::scope_exit([&] {
  2005. svr.stop();
  2006. thread.join();
  2007. ASSERT_FALSE(svr.is_running());
  2008. });
  2009. svr.wait_until_ready();
  2010. {
  2011. Client cli(HOST, PORT);
  2012. auto res = cli.Get("/hi");
  2013. ASSERT_TRUE(res);
  2014. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2015. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2016. }
  2017. }
  2018. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2019. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2021. ASSERT_TRUE(svr.is_valid());
  2022. #else
  2023. Server svr;
  2024. #endif
  2025. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2026. if (req.path == "/routing_handler") {
  2027. res.set_header("PRE_ROUTING", "on");
  2028. res.set_content("Routing Handler", "text/plain");
  2029. return httplib::Server::HandlerResponse::Handled;
  2030. }
  2031. return httplib::Server::HandlerResponse::Unhandled;
  2032. });
  2033. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2034. res.set_content("Error", "text/html");
  2035. });
  2036. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2037. if (req.path == "/routing_handler") {
  2038. res.set_header("POST_ROUTING", "on");
  2039. }
  2040. });
  2041. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2042. res.set_content("Hello World!\n", "text/plain");
  2043. });
  2044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2045. auto se = detail::scope_exit([&] {
  2046. svr.stop();
  2047. thread.join();
  2048. ASSERT_FALSE(svr.is_running());
  2049. });
  2050. svr.wait_until_ready();
  2051. {
  2052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2053. SSLClient cli(HOST, PORT);
  2054. cli.enable_server_certificate_verification(false);
  2055. #else
  2056. Client cli(HOST, PORT);
  2057. #endif
  2058. auto res = cli.Get("/routing_handler");
  2059. ASSERT_TRUE(res);
  2060. EXPECT_EQ(StatusCode::OK_200, res->status);
  2061. EXPECT_EQ("Routing Handler", res->body);
  2062. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2063. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2064. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2065. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2066. }
  2067. {
  2068. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2069. SSLClient cli(HOST, PORT);
  2070. cli.enable_server_certificate_verification(false);
  2071. #else
  2072. Client cli(HOST, PORT);
  2073. #endif
  2074. auto res = cli.Get("/hi");
  2075. ASSERT_TRUE(res);
  2076. EXPECT_EQ(StatusCode::OK_200, res->status);
  2077. EXPECT_EQ("Hello World!\n", res->body);
  2078. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2079. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2080. }
  2081. {
  2082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2083. SSLClient cli(HOST, PORT);
  2084. cli.enable_server_certificate_verification(false);
  2085. #else
  2086. Client cli(HOST, PORT);
  2087. #endif
  2088. auto res = cli.Get("/aaa");
  2089. ASSERT_TRUE(res);
  2090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2091. EXPECT_EQ("Error", res->body);
  2092. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2093. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2094. }
  2095. }
  2096. TEST(RequestHandlerTest, PreRequestHandler) {
  2097. auto route_path = "/user/:user";
  2098. Server svr;
  2099. svr.Get("/hi", [](const Request &, Response &res) {
  2100. res.set_content("hi", "text/plain");
  2101. });
  2102. svr.Get(route_path, [](const Request &req, Response &res) {
  2103. res.set_content(req.path_params.at("user"), "text/plain");
  2104. });
  2105. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2106. if (req.matched_route == route_path) {
  2107. auto user = req.path_params.at("user");
  2108. if (user != "john") {
  2109. res.status = StatusCode::Forbidden_403;
  2110. res.set_content("error", "text/html");
  2111. return Server::HandlerResponse::Handled;
  2112. }
  2113. }
  2114. return Server::HandlerResponse::Unhandled;
  2115. });
  2116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2117. auto se = detail::scope_exit([&] {
  2118. svr.stop();
  2119. thread.join();
  2120. ASSERT_FALSE(svr.is_running());
  2121. });
  2122. svr.wait_until_ready();
  2123. Client cli(HOST, PORT);
  2124. {
  2125. auto res = cli.Get("/hi");
  2126. ASSERT_TRUE(res);
  2127. EXPECT_EQ(StatusCode::OK_200, res->status);
  2128. EXPECT_EQ("hi", res->body);
  2129. }
  2130. {
  2131. auto res = cli.Get("/user/john");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::OK_200, res->status);
  2134. EXPECT_EQ("john", res->body);
  2135. }
  2136. {
  2137. auto res = cli.Get("/user/invalid-user");
  2138. ASSERT_TRUE(res);
  2139. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2140. EXPECT_EQ("error", res->body);
  2141. }
  2142. }
  2143. TEST(InvalidFormatTest, StatusCode) {
  2144. Server svr;
  2145. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2146. res.set_content("Hello World!\n", "text/plain");
  2147. res.status = 9999; // Status should be a three-digit code...
  2148. });
  2149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2150. auto se = detail::scope_exit([&] {
  2151. svr.stop();
  2152. thread.join();
  2153. ASSERT_FALSE(svr.is_running());
  2154. });
  2155. svr.wait_until_ready();
  2156. {
  2157. Client cli(HOST, PORT);
  2158. auto res = cli.Get("/hi");
  2159. ASSERT_FALSE(res);
  2160. }
  2161. }
  2162. TEST(URLFragmentTest, WithFragment) {
  2163. Server svr;
  2164. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2165. EXPECT_TRUE(req.target == "/hi");
  2166. });
  2167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2168. auto se = detail::scope_exit([&] {
  2169. svr.stop();
  2170. thread.join();
  2171. ASSERT_FALSE(svr.is_running());
  2172. });
  2173. svr.wait_until_ready();
  2174. {
  2175. Client cli(HOST, PORT);
  2176. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2177. EXPECT_TRUE(res);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. res = cli.Get("/hi%23key1=val1=key2=val2");
  2180. EXPECT_TRUE(res);
  2181. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2182. }
  2183. }
  2184. TEST(HeaderWriter, SetHeaderWriter) {
  2185. Server svr;
  2186. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2187. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2188. return detail::write_headers(strm, hdrs);
  2189. });
  2190. svr.Get("/hi", [](const Request &req, Response &res) {
  2191. auto it = req.headers.find("CustomClientHeader");
  2192. EXPECT_TRUE(it != req.headers.end());
  2193. EXPECT_EQ(it->second, "CustomClientValue");
  2194. res.set_content("Hello World!\n", "text/plain");
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2206. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2207. return detail::write_headers(strm, hdrs);
  2208. });
  2209. auto res = cli.Get("/hi");
  2210. EXPECT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::OK_200, res->status);
  2212. auto it = res->headers.find("CustomServerHeader");
  2213. EXPECT_TRUE(it != res->headers.end());
  2214. EXPECT_EQ(it->second, "CustomServerValue");
  2215. }
  2216. }
  2217. class ServerTest : public ::testing::Test {
  2218. protected:
  2219. ServerTest()
  2220. : cli_(HOST, PORT)
  2221. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2222. ,
  2223. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2224. #endif
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. cli_.enable_server_certificate_verification(false);
  2228. #endif
  2229. }
  2230. virtual void SetUp() {
  2231. svr_.set_mount_point("/", "./www");
  2232. svr_.set_mount_point("/mount", "./www2");
  2233. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2234. svr_.Get("/hi",
  2235. [&](const Request & /*req*/, Response &res) {
  2236. res.set_content("Hello World!", "text/plain");
  2237. })
  2238. .Get("/file_content",
  2239. [&](const Request & /*req*/, Response &res) {
  2240. res.set_file_content("./www/dir/test.html");
  2241. })
  2242. .Get("/file_content_with_content_type",
  2243. [&](const Request & /*req*/, Response &res) {
  2244. res.set_file_content("./www/file", "text/plain");
  2245. })
  2246. .Get("/invalid_file_content",
  2247. [&](const Request & /*req*/, Response &res) {
  2248. res.set_file_content("./www/dir/invalid_file_path");
  2249. })
  2250. .Get("/http_response_splitting",
  2251. [&](const Request & /*req*/, Response &res) {
  2252. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2253. EXPECT_EQ(0U, res.headers.size());
  2254. EXPECT_FALSE(res.has_header("a"));
  2255. res.set_header("a", "1\nSet-Cookie: a=1");
  2256. EXPECT_EQ(0U, res.headers.size());
  2257. EXPECT_FALSE(res.has_header("a"));
  2258. res.set_header("a", "1\rSet-Cookie: a=1");
  2259. EXPECT_EQ(0U, res.headers.size());
  2260. EXPECT_FALSE(res.has_header("a"));
  2261. res.set_header("a\r\nb", "0");
  2262. EXPECT_EQ(0U, res.headers.size());
  2263. EXPECT_FALSE(res.has_header("a"));
  2264. res.set_header("a\rb", "0");
  2265. EXPECT_EQ(0U, res.headers.size());
  2266. EXPECT_FALSE(res.has_header("a"));
  2267. res.set_header("a\nb", "0");
  2268. EXPECT_EQ(0U, res.headers.size());
  2269. EXPECT_FALSE(res.has_header("a"));
  2270. res.set_redirect("1\r\nSet-Cookie: a=1");
  2271. EXPECT_EQ(0U, res.headers.size());
  2272. EXPECT_FALSE(res.has_header("Location"));
  2273. })
  2274. .Get("/slow",
  2275. [&](const Request & /*req*/, Response &res) {
  2276. std::this_thread::sleep_for(std::chrono::seconds(2));
  2277. res.set_content("slow", "text/plain");
  2278. })
  2279. #if 0
  2280. .Post("/slowpost",
  2281. [&](const Request & /*req*/, Response &res) {
  2282. std::this_thread::sleep_for(std::chrono::seconds(2));
  2283. res.set_content("slow", "text/plain");
  2284. })
  2285. #endif
  2286. .Get("/remote_addr",
  2287. [&](const Request &req, Response &res) {
  2288. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2289. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2290. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2291. EXPECT_EQ(req.remote_port,
  2292. std::stoi(req.get_header_value("REMOTE_PORT")));
  2293. res.set_content(remote_addr.c_str(), "text/plain");
  2294. })
  2295. .Get("/local_addr",
  2296. [&](const Request &req, Response &res) {
  2297. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2298. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2299. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2300. auto local_port = req.get_header_value("LOCAL_PORT");
  2301. EXPECT_EQ(req.local_addr, local_addr);
  2302. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2303. res.set_content(local_addr.append(":").append(local_port),
  2304. "text/plain");
  2305. })
  2306. .Get("/endwith%",
  2307. [&](const Request & /*req*/, Response &res) {
  2308. res.set_content("Hello World!", "text/plain");
  2309. })
  2310. .Get("/a\\+\\+b",
  2311. [&](const Request &req, Response &res) {
  2312. ASSERT_TRUE(req.has_param("a +b"));
  2313. auto val = req.get_param_value("a +b");
  2314. res.set_content(val, "text/plain");
  2315. })
  2316. .Get("/", [&](const Request & /*req*/,
  2317. Response &res) { res.set_redirect("/hi"); })
  2318. .Post("/1",
  2319. [](const Request & /*req*/, Response &res) {
  2320. res.set_redirect("/2", StatusCode::SeeOther_303);
  2321. })
  2322. .Get("/2",
  2323. [](const Request & /*req*/, Response &res) {
  2324. res.set_content("redirected.", "text/plain");
  2325. res.status = StatusCode::OK_200;
  2326. })
  2327. .Post("/person",
  2328. [&](const Request &req, Response &res) {
  2329. if (req.has_param("name") && req.has_param("note")) {
  2330. persons_[req.get_param_value("name")] =
  2331. req.get_param_value("note");
  2332. } else {
  2333. res.status = StatusCode::BadRequest_400;
  2334. }
  2335. })
  2336. .Put("/person",
  2337. [&](const Request &req, Response &res) {
  2338. if (req.has_param("name") && req.has_param("note")) {
  2339. persons_[req.get_param_value("name")] =
  2340. req.get_param_value("note");
  2341. } else {
  2342. res.status = StatusCode::BadRequest_400;
  2343. }
  2344. })
  2345. .Get("/person/(.*)",
  2346. [&](const Request &req, Response &res) {
  2347. string name = req.matches[1];
  2348. if (persons_.find(name) != persons_.end()) {
  2349. auto note = persons_[name];
  2350. res.set_content(note, "text/plain");
  2351. } else {
  2352. res.status = StatusCode::NotFound_404;
  2353. }
  2354. })
  2355. .Delete("/person",
  2356. [&](const Request &req, Response &res) {
  2357. if (req.has_param("name")) {
  2358. string name = req.get_param_value("name");
  2359. if (persons_.find(name) != persons_.end()) {
  2360. persons_.erase(name);
  2361. res.set_content("DELETED", "text/plain");
  2362. } else {
  2363. res.status = StatusCode::NotFound_404;
  2364. }
  2365. } else {
  2366. res.status = StatusCode::BadRequest_400;
  2367. }
  2368. })
  2369. .Post("/x-www-form-urlencoded-json",
  2370. [&](const Request &req, Response &res) {
  2371. auto json = req.get_param_value("json");
  2372. ASSERT_EQ(JSON_DATA, json);
  2373. res.set_content(json, "appliation/json");
  2374. res.status = StatusCode::OK_200;
  2375. })
  2376. .Get("/streamed-chunked",
  2377. [&](const Request & /*req*/, Response &res) {
  2378. res.set_chunked_content_provider(
  2379. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2380. sink.os << "123";
  2381. sink.os << "456";
  2382. sink.os << "789";
  2383. sink.done();
  2384. return true;
  2385. });
  2386. })
  2387. .Get("/streamed-chunked2",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. auto i = new int(0);
  2390. res.set_chunked_content_provider(
  2391. "text/plain",
  2392. [i](size_t /*offset*/, DataSink &sink) {
  2393. switch (*i) {
  2394. case 0: sink.os << "123"; break;
  2395. case 1: sink.os << "456"; break;
  2396. case 2: sink.os << "789"; break;
  2397. case 3: sink.done(); break;
  2398. }
  2399. (*i)++;
  2400. return true;
  2401. },
  2402. [i](bool success) {
  2403. EXPECT_TRUE(success);
  2404. delete i;
  2405. });
  2406. })
  2407. .Get("/streamed-chunked-with-trailer",
  2408. [&](const Request & /*req*/, Response &res) {
  2409. auto i = new int(0);
  2410. res.set_header("Trailer", "Dummy1, Dummy2");
  2411. res.set_chunked_content_provider(
  2412. "text/plain",
  2413. [i](size_t /*offset*/, DataSink &sink) {
  2414. switch (*i) {
  2415. case 0: sink.os << "123"; break;
  2416. case 1: sink.os << "456"; break;
  2417. case 2: sink.os << "789"; break;
  2418. case 3: {
  2419. sink.done_with_trailer(
  2420. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2421. } break;
  2422. }
  2423. (*i)++;
  2424. return true;
  2425. },
  2426. [i](bool success) {
  2427. EXPECT_TRUE(success);
  2428. delete i;
  2429. });
  2430. })
  2431. .Get("/streamed",
  2432. [&](const Request & /*req*/, Response &res) {
  2433. res.set_content_provider(
  2434. 6, "text/plain",
  2435. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2436. sink.os << (offset < 3 ? "a" : "b");
  2437. return true;
  2438. });
  2439. })
  2440. .Get("/streamed-with-range",
  2441. [&](const Request &req, Response &res) {
  2442. auto data = new std::string("abcdefg");
  2443. res.set_content_provider(
  2444. data->size(), "text/plain",
  2445. [data](size_t offset, size_t length, DataSink &sink) {
  2446. size_t DATA_CHUNK_SIZE = 4;
  2447. const auto &d = *data;
  2448. auto out_len =
  2449. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2450. auto ret =
  2451. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2452. EXPECT_TRUE(ret);
  2453. return true;
  2454. },
  2455. [data, &req](bool success) {
  2456. EXPECT_EQ(success, !req.has_param("error"));
  2457. delete data;
  2458. });
  2459. })
  2460. .Get("/streamed-cancel",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. size_t(-1), "text/plain",
  2464. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2465. sink.os << "data_chunk";
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/regex-with-delimiter",
  2470. [&](const Request &req, Response & /*res*/) {
  2471. ASSERT_TRUE(req.has_param("key"));
  2472. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2473. })
  2474. .Get("/with-range",
  2475. [&](const Request & /*req*/, Response &res) {
  2476. res.set_content("abcdefg", "text/plain");
  2477. })
  2478. .Get("/with-range-customized-response",
  2479. [&](const Request & /*req*/, Response &res) {
  2480. res.status = StatusCode::BadRequest_400;
  2481. res.set_content(JSON_DATA, "application/json");
  2482. })
  2483. .Post("/chunked",
  2484. [&](const Request &req, Response & /*res*/) {
  2485. EXPECT_EQ(req.body, "dechunked post body");
  2486. })
  2487. .Post("/large-chunked",
  2488. [&](const Request &req, Response & /*res*/) {
  2489. std::string expected(6 * 30 * 1024u, 'a');
  2490. EXPECT_EQ(req.body, expected);
  2491. })
  2492. .Post("/multipart",
  2493. [&](const Request &req, Response & /*res*/) {
  2494. EXPECT_EQ(6u, req.files.size());
  2495. ASSERT_TRUE(!req.has_file("???"));
  2496. ASSERT_TRUE(req.body.empty());
  2497. {
  2498. const auto &file = req.get_file_value("text1");
  2499. EXPECT_TRUE(file.filename.empty());
  2500. EXPECT_EQ("text default", file.content);
  2501. }
  2502. {
  2503. const auto &file = req.get_file_value("text2");
  2504. EXPECT_TRUE(file.filename.empty());
  2505. EXPECT_EQ("aωb", file.content);
  2506. }
  2507. {
  2508. const auto &file = req.get_file_value("file1");
  2509. EXPECT_EQ("hello.txt", file.filename);
  2510. EXPECT_EQ("text/plain", file.content_type);
  2511. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2512. }
  2513. {
  2514. const auto &file = req.get_file_value("file3");
  2515. EXPECT_TRUE(file.filename.empty());
  2516. EXPECT_EQ("application/octet-stream", file.content_type);
  2517. EXPECT_EQ(0u, file.content.size());
  2518. }
  2519. {
  2520. const auto &file = req.get_file_value("file4");
  2521. EXPECT_TRUE(file.filename.empty());
  2522. EXPECT_EQ(0u, file.content.size());
  2523. EXPECT_EQ("application/json tmp-string", file.content_type);
  2524. }
  2525. })
  2526. .Post("/multipart/multi_file_values",
  2527. [&](const Request &req, Response & /*res*/) {
  2528. EXPECT_EQ(5u, req.files.size());
  2529. ASSERT_TRUE(!req.has_file("???"));
  2530. ASSERT_TRUE(req.body.empty());
  2531. {
  2532. const auto &text_value = req.get_file_values("text");
  2533. EXPECT_EQ(1u, text_value.size());
  2534. auto &text = text_value[0];
  2535. EXPECT_TRUE(text.filename.empty());
  2536. EXPECT_EQ("default text", text.content);
  2537. }
  2538. {
  2539. const auto &text1_values = req.get_file_values("multi_text1");
  2540. EXPECT_EQ(2u, text1_values.size());
  2541. EXPECT_EQ("aaaaa", text1_values[0].content);
  2542. EXPECT_EQ("bbbbb", text1_values[1].content);
  2543. }
  2544. {
  2545. const auto &file1_values = req.get_file_values("multi_file1");
  2546. EXPECT_EQ(2u, file1_values.size());
  2547. auto file1 = file1_values[0];
  2548. EXPECT_EQ(file1.filename, "hello.txt");
  2549. EXPECT_EQ(file1.content_type, "text/plain");
  2550. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2551. auto file2 = file1_values[1];
  2552. EXPECT_EQ(file2.filename, "world.json");
  2553. EXPECT_EQ(file2.content_type, "application/json");
  2554. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2555. }
  2556. })
  2557. .Post("/empty",
  2558. [&](const Request &req, Response &res) {
  2559. EXPECT_EQ(req.body, "");
  2560. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2561. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2562. res.set_content("empty", "text/plain");
  2563. })
  2564. .Post("/empty-no-content-type",
  2565. [&](const Request &req, Response &res) {
  2566. EXPECT_EQ(req.body, "");
  2567. EXPECT_FALSE(req.has_header("Content-Type"));
  2568. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2569. res.set_content("empty-no-content-type", "text/plain");
  2570. })
  2571. .Post("/path-only",
  2572. [&](const Request &req, Response &res) {
  2573. EXPECT_EQ(req.body, "");
  2574. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2575. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2576. res.set_content("path-only", "text/plain");
  2577. })
  2578. .Post("/path-headers-only",
  2579. [&](const Request &req, Response &res) {
  2580. EXPECT_EQ(req.body, "");
  2581. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2582. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2583. EXPECT_EQ("world", req.get_header_value("hello"));
  2584. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2585. res.set_content("path-headers-only", "text/plain");
  2586. })
  2587. .Post("/post-large",
  2588. [&](const Request &req, Response &res) {
  2589. EXPECT_EQ(req.body, LARGE_DATA);
  2590. res.set_content(req.body, "text/plain");
  2591. })
  2592. .Put("/empty-no-content-type",
  2593. [&](const Request &req, Response &res) {
  2594. EXPECT_EQ(req.body, "");
  2595. EXPECT_FALSE(req.has_header("Content-Type"));
  2596. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2597. res.set_content("empty-no-content-type", "text/plain");
  2598. })
  2599. .Put("/put",
  2600. [&](const Request &req, Response &res) {
  2601. EXPECT_EQ(req.body, "PUT");
  2602. res.set_content(req.body, "text/plain");
  2603. })
  2604. .Put("/put-large",
  2605. [&](const Request &req, Response &res) {
  2606. EXPECT_EQ(req.body, LARGE_DATA);
  2607. res.set_content(req.body, "text/plain");
  2608. })
  2609. .Patch("/patch",
  2610. [&](const Request &req, Response &res) {
  2611. EXPECT_EQ(req.body, "PATCH");
  2612. res.set_content(req.body, "text/plain");
  2613. })
  2614. .Delete("/delete",
  2615. [&](const Request & /*req*/, Response &res) {
  2616. res.set_content("DELETE", "text/plain");
  2617. })
  2618. .Delete("/delete-body",
  2619. [&](const Request &req, Response &res) {
  2620. EXPECT_EQ(req.body, "content");
  2621. res.set_content(req.body, "text/plain");
  2622. })
  2623. .Options(R"(\*)",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2626. })
  2627. .Get("/request-target",
  2628. [&](const Request &req, Response & /*res*/) {
  2629. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2630. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2631. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2632. })
  2633. .Get("/long-query-value",
  2634. [&](const Request &req, Response & /*res*/) {
  2635. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2636. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2637. })
  2638. .Get("/too-long-query-value",
  2639. [&](const Request &req, Response & /*res*/) {
  2640. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2641. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2642. })
  2643. .Get("/array-param",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2646. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2647. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2648. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2649. })
  2650. .Post("/validate-no-multiple-headers",
  2651. [&](const Request &req, Response & /*res*/) {
  2652. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2653. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2654. })
  2655. .Post("/content_receiver",
  2656. [&](const Request &req, Response &res,
  2657. const ContentReader &content_reader) {
  2658. if (req.is_multipart_form_data()) {
  2659. MultipartFormDataItems files;
  2660. content_reader(
  2661. [&](const MultipartFormData &file) {
  2662. files.push_back(file);
  2663. return true;
  2664. },
  2665. [&](const char *data, size_t data_length) {
  2666. files.back().content.append(data, data_length);
  2667. return true;
  2668. });
  2669. EXPECT_EQ(5u, files.size());
  2670. {
  2671. const auto &file = get_file_value(files, "text1");
  2672. EXPECT_TRUE(file.filename.empty());
  2673. EXPECT_EQ("text default", file.content);
  2674. }
  2675. {
  2676. const auto &file = get_file_value(files, "text2");
  2677. EXPECT_TRUE(file.filename.empty());
  2678. EXPECT_EQ("aωb", file.content);
  2679. }
  2680. {
  2681. const auto &file = get_file_value(files, "file1");
  2682. EXPECT_EQ("hello.txt", file.filename);
  2683. EXPECT_EQ("text/plain", file.content_type);
  2684. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2685. }
  2686. {
  2687. const auto &file = get_file_value(files, "file3");
  2688. EXPECT_TRUE(file.filename.empty());
  2689. EXPECT_EQ("application/octet-stream", file.content_type);
  2690. EXPECT_EQ(0u, file.content.size());
  2691. }
  2692. } else {
  2693. std::string body;
  2694. content_reader([&](const char *data, size_t data_length) {
  2695. EXPECT_EQ(7U, data_length);
  2696. body.append(data, data_length);
  2697. return true;
  2698. });
  2699. EXPECT_EQ(body, "content");
  2700. res.set_content(body, "text/plain");
  2701. }
  2702. })
  2703. .Put("/content_receiver",
  2704. [&](const Request & /*req*/, Response &res,
  2705. const ContentReader &content_reader) {
  2706. std::string body;
  2707. content_reader([&](const char *data, size_t data_length) {
  2708. body.append(data, data_length);
  2709. return true;
  2710. });
  2711. EXPECT_EQ(body, "content");
  2712. res.set_content(body, "text/plain");
  2713. })
  2714. .Patch("/content_receiver",
  2715. [&](const Request & /*req*/, Response &res,
  2716. const ContentReader &content_reader) {
  2717. std::string body;
  2718. content_reader([&](const char *data, size_t data_length) {
  2719. body.append(data, data_length);
  2720. return true;
  2721. });
  2722. EXPECT_EQ(body, "content");
  2723. res.set_content(body, "text/plain");
  2724. })
  2725. .Post("/query-string-and-body",
  2726. [&](const Request &req, Response & /*res*/) {
  2727. ASSERT_TRUE(req.has_param("key"));
  2728. EXPECT_EQ(req.get_param_value("key"), "value");
  2729. EXPECT_EQ(req.body, "content");
  2730. })
  2731. .Get("/last-request",
  2732. [&](const Request &req, Response & /*res*/) {
  2733. EXPECT_EQ("close", req.get_header_value("Connection"));
  2734. })
  2735. .Get(R"(/redirect/(\d+))",
  2736. [&](const Request &req, Response &res) {
  2737. auto num = std::stoi(req.matches[1]) + 1;
  2738. std::string url = "/redirect/" + std::to_string(num);
  2739. res.set_redirect(url);
  2740. })
  2741. .Post("/binary",
  2742. [&](const Request &req, Response &res) {
  2743. EXPECT_EQ(4U, req.body.size());
  2744. EXPECT_EQ("application/octet-stream",
  2745. req.get_header_value("Content-Type"));
  2746. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2747. res.set_content(req.body, "application/octet-stream");
  2748. })
  2749. .Put("/binary",
  2750. [&](const Request &req, Response &res) {
  2751. EXPECT_EQ(4U, req.body.size());
  2752. EXPECT_EQ("application/octet-stream",
  2753. req.get_header_value("Content-Type"));
  2754. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2755. res.set_content(req.body, "application/octet-stream");
  2756. })
  2757. .Patch("/binary",
  2758. [&](const Request &req, Response &res) {
  2759. EXPECT_EQ(4U, req.body.size());
  2760. EXPECT_EQ("application/octet-stream",
  2761. req.get_header_value("Content-Type"));
  2762. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2763. res.set_content(req.body, "application/octet-stream");
  2764. })
  2765. .Delete("/binary",
  2766. [&](const Request &req, Response &res) {
  2767. EXPECT_EQ(4U, req.body.size());
  2768. EXPECT_EQ("application/octet-stream",
  2769. req.get_header_value("Content-Type"));
  2770. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2771. res.set_content(req.body, "application/octet-stream");
  2772. })
  2773. .Get("/issue1772",
  2774. [&](const Request & /*req*/, Response &res) {
  2775. res.status = 401;
  2776. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2777. })
  2778. .Delete("/issue609",
  2779. [](const httplib::Request &, httplib::Response &res,
  2780. const httplib::ContentReader &) {
  2781. res.set_content("ok", "text/plain");
  2782. })
  2783. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2784. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2785. .Get("/compress",
  2786. [&](const Request & /*req*/, Response &res) {
  2787. res.set_content(
  2788. "12345678901234567890123456789012345678901234567890123456789"
  2789. "01234567890123456789012345678901234567890",
  2790. "text/plain");
  2791. })
  2792. .Get("/nocompress",
  2793. [&](const Request & /*req*/, Response &res) {
  2794. res.set_content(
  2795. "12345678901234567890123456789012345678901234567890123456789"
  2796. "01234567890123456789012345678901234567890",
  2797. "application/octet-stream");
  2798. })
  2799. .Post("/compress-multipart",
  2800. [&](const Request &req, Response & /*res*/) {
  2801. EXPECT_EQ(2u, req.files.size());
  2802. ASSERT_TRUE(!req.has_file("???"));
  2803. {
  2804. const auto &file = req.get_file_value("key1");
  2805. EXPECT_TRUE(file.filename.empty());
  2806. EXPECT_EQ("test", file.content);
  2807. }
  2808. {
  2809. const auto &file = req.get_file_value("key2");
  2810. EXPECT_TRUE(file.filename.empty());
  2811. EXPECT_EQ("--abcdefg123", file.content);
  2812. }
  2813. })
  2814. #endif
  2815. ;
  2816. persons_["john"] = "programmer";
  2817. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2818. svr_.wait_until_ready();
  2819. }
  2820. virtual void TearDown() {
  2821. svr_.stop();
  2822. if (!request_threads_.empty()) {
  2823. std::this_thread::sleep_for(std::chrono::seconds(1));
  2824. for (auto &t : request_threads_) {
  2825. t.join();
  2826. }
  2827. }
  2828. t_.join();
  2829. }
  2830. map<string, string> persons_;
  2831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2832. SSLClient cli_;
  2833. SSLServer svr_;
  2834. #else
  2835. Client cli_;
  2836. Server svr_;
  2837. #endif
  2838. thread t_;
  2839. std::vector<thread> request_threads_;
  2840. };
  2841. TEST_F(ServerTest, GetMethod200) {
  2842. auto res = cli_.Get("/hi");
  2843. ASSERT_TRUE(res);
  2844. EXPECT_EQ("HTTP/1.1", res->version);
  2845. EXPECT_EQ(StatusCode::OK_200, res->status);
  2846. EXPECT_EQ("OK", res->reason);
  2847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2848. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2849. EXPECT_EQ("Hello World!", res->body);
  2850. }
  2851. void performance_test(const char *host) {
  2852. auto port = 1234;
  2853. Server svr;
  2854. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2855. res.set_content("Benchmark Response", "text/plain");
  2856. });
  2857. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  2858. auto se = detail::scope_exit([&] {
  2859. svr.stop();
  2860. listen_thread.join();
  2861. ASSERT_FALSE(svr.is_running());
  2862. });
  2863. svr.wait_until_ready();
  2864. Client cli(host, port);
  2865. auto start = std::chrono::high_resolution_clock::now();
  2866. auto res = cli.Get("/benchmark");
  2867. ASSERT_TRUE(res);
  2868. EXPECT_EQ(StatusCode::OK_200, res->status);
  2869. auto end = std::chrono::high_resolution_clock::now();
  2870. auto elapsed =
  2871. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2872. .count();
  2873. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  2874. << "ms (Issue #1777)";
  2875. }
  2876. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  2877. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  2878. TEST_F(ServerTest, GetEmptyFile) {
  2879. auto res = cli_.Get("/empty_file");
  2880. ASSERT_TRUE(res);
  2881. EXPECT_EQ(StatusCode::OK_200, res->status);
  2882. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2883. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2884. EXPECT_EQ("", res->body);
  2885. }
  2886. TEST_F(ServerTest, GetFileContent) {
  2887. auto res = cli_.Get("/file_content");
  2888. ASSERT_TRUE(res);
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2891. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2892. EXPECT_EQ("test.html", res->body);
  2893. }
  2894. TEST_F(ServerTest, GetFileContentWithRange) {
  2895. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2896. ASSERT_TRUE(res);
  2897. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2898. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2899. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2900. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2901. EXPECT_EQ("est", res->body);
  2902. }
  2903. TEST_F(ServerTest, GetFileContentWithContentType) {
  2904. auto res = cli_.Get("/file_content_with_content_type");
  2905. ASSERT_TRUE(res);
  2906. EXPECT_EQ(StatusCode::OK_200, res->status);
  2907. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2908. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2909. EXPECT_EQ("file\n", res->body);
  2910. }
  2911. TEST_F(ServerTest, GetInvalidFileContent) {
  2912. auto res = cli_.Get("/invalid_file_content");
  2913. ASSERT_TRUE(res);
  2914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2915. }
  2916. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2917. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2918. ASSERT_TRUE(res);
  2919. EXPECT_EQ("HTTP/1.1", res->version);
  2920. EXPECT_EQ(StatusCode::OK_200, res->status);
  2921. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2922. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2923. EXPECT_EQ("Hello World!", res->body);
  2924. }
  2925. TEST_F(ServerTest, GetMethod302) {
  2926. auto res = cli_.Get("/");
  2927. ASSERT_TRUE(res);
  2928. EXPECT_EQ(StatusCode::Found_302, res->status);
  2929. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2930. }
  2931. TEST_F(ServerTest, GetMethod302Redirect) {
  2932. cli_.set_follow_location(true);
  2933. auto res = cli_.Get("/");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("Hello World!", res->body);
  2937. EXPECT_EQ("/hi", res->location);
  2938. }
  2939. TEST_F(ServerTest, GetMethod404) {
  2940. auto res = cli_.Get("/invalid");
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2943. }
  2944. TEST_F(ServerTest, HeadMethod200) {
  2945. auto res = cli_.Head("/hi");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::OK_200, res->status);
  2948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2949. EXPECT_TRUE(res->body.empty());
  2950. }
  2951. TEST_F(ServerTest, HeadMethod200Static) {
  2952. auto res = cli_.Head("/mount/dir/index.html");
  2953. ASSERT_TRUE(res);
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2956. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2957. EXPECT_TRUE(res->body.empty());
  2958. }
  2959. TEST_F(ServerTest, HeadMethod404) {
  2960. auto res = cli_.Head("/invalid");
  2961. ASSERT_TRUE(res);
  2962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2963. EXPECT_TRUE(res->body.empty());
  2964. }
  2965. TEST_F(ServerTest, GetMethodPersonJohn) {
  2966. auto res = cli_.Get("/person/john");
  2967. ASSERT_TRUE(res);
  2968. EXPECT_EQ(StatusCode::OK_200, res->status);
  2969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2970. EXPECT_EQ("programmer", res->body);
  2971. }
  2972. TEST_F(ServerTest, PostMethod1) {
  2973. auto res = cli_.Get("/person/john1");
  2974. ASSERT_TRUE(res);
  2975. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2976. res = cli_.Post("/person", "name=john1&note=coder",
  2977. "application/x-www-form-urlencoded");
  2978. ASSERT_TRUE(res);
  2979. ASSERT_EQ(StatusCode::OK_200, res->status);
  2980. res = cli_.Get("/person/john1");
  2981. ASSERT_TRUE(res);
  2982. ASSERT_EQ(StatusCode::OK_200, res->status);
  2983. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2984. ASSERT_EQ("coder", res->body);
  2985. }
  2986. TEST_F(ServerTest, PostMethod2) {
  2987. auto res = cli_.Get("/person/john2");
  2988. ASSERT_TRUE(res);
  2989. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2990. Params params;
  2991. params.emplace("name", "john2");
  2992. params.emplace("note", "coder");
  2993. res = cli_.Post("/person", params);
  2994. ASSERT_TRUE(res);
  2995. ASSERT_EQ(StatusCode::OK_200, res->status);
  2996. res = cli_.Get("/person/john2");
  2997. ASSERT_TRUE(res);
  2998. ASSERT_EQ(StatusCode::OK_200, res->status);
  2999. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3000. ASSERT_EQ("coder", res->body);
  3001. }
  3002. TEST_F(ServerTest, PutMethod3) {
  3003. auto res = cli_.Get("/person/john3");
  3004. ASSERT_TRUE(res);
  3005. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3006. Params params;
  3007. params.emplace("name", "john3");
  3008. params.emplace("note", "coder");
  3009. res = cli_.Put("/person", params);
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(StatusCode::OK_200, res->status);
  3012. res = cli_.Get("/person/john3");
  3013. ASSERT_TRUE(res);
  3014. ASSERT_EQ(StatusCode::OK_200, res->status);
  3015. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3016. ASSERT_EQ("coder", res->body);
  3017. }
  3018. TEST_F(ServerTest, DeleteMethod1) {
  3019. auto res = cli_.Get("/person/john4");
  3020. ASSERT_TRUE(res);
  3021. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3022. Params params;
  3023. params.emplace("name", "john4");
  3024. params.emplace("note", "coder");
  3025. res = cli_.Post("/person", params);
  3026. ASSERT_TRUE(res);
  3027. ASSERT_EQ(StatusCode::OK_200, res->status);
  3028. res = cli_.Get("/person/john4");
  3029. ASSERT_TRUE(res);
  3030. ASSERT_EQ(StatusCode::OK_200, res->status);
  3031. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3032. ASSERT_EQ("coder", res->body);
  3033. Params delete_params;
  3034. delete_params.emplace("name", "john4");
  3035. res = cli_.Delete("/person", delete_params);
  3036. ASSERT_TRUE(res);
  3037. ASSERT_EQ(StatusCode::OK_200, res->status);
  3038. ASSERT_EQ("DELETED", res->body);
  3039. res = cli_.Get("/person/john4");
  3040. ASSERT_TRUE(res);
  3041. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3042. }
  3043. TEST_F(ServerTest, DeleteMethod2) {
  3044. auto res = cli_.Get("/person/john5");
  3045. ASSERT_TRUE(res);
  3046. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3047. Params params;
  3048. params.emplace("name", "john5");
  3049. params.emplace("note", "developer");
  3050. res = cli_.Post("/person", params);
  3051. ASSERT_TRUE(res);
  3052. ASSERT_EQ(StatusCode::OK_200, res->status);
  3053. res = cli_.Get("/person/john5");
  3054. ASSERT_TRUE(res);
  3055. ASSERT_EQ(StatusCode::OK_200, res->status);
  3056. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3057. ASSERT_EQ("developer", res->body);
  3058. Params delete_params;
  3059. delete_params.emplace("name", "john5");
  3060. Headers headers;
  3061. headers.emplace("Custom-Header", "test-value");
  3062. res = cli_.Delete("/person", headers, delete_params);
  3063. ASSERT_TRUE(res);
  3064. ASSERT_EQ(StatusCode::OK_200, res->status);
  3065. ASSERT_EQ("DELETED", res->body);
  3066. res = cli_.Get("/person/john5");
  3067. ASSERT_TRUE(res);
  3068. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3069. }
  3070. TEST_F(ServerTest, DeleteMethod3) {
  3071. auto res = cli_.Get("/person/john6");
  3072. ASSERT_TRUE(res);
  3073. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3074. Params params;
  3075. params.emplace("name", "john6");
  3076. params.emplace("note", "tester");
  3077. res = cli_.Post("/person", params);
  3078. ASSERT_TRUE(res);
  3079. ASSERT_EQ(StatusCode::OK_200, res->status);
  3080. res = cli_.Get("/person/john6");
  3081. ASSERT_TRUE(res);
  3082. ASSERT_EQ(StatusCode::OK_200, res->status);
  3083. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3084. ASSERT_EQ("tester", res->body);
  3085. Params delete_params;
  3086. delete_params.emplace("name", "john6");
  3087. Headers headers;
  3088. headers.emplace("Custom-Header", "test-value");
  3089. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3090. ASSERT_TRUE(res);
  3091. ASSERT_EQ(StatusCode::OK_200, res->status);
  3092. ASSERT_EQ("DELETED", res->body);
  3093. res = cli_.Get("/person/john6");
  3094. ASSERT_TRUE(res);
  3095. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3096. }
  3097. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3098. Params params;
  3099. params.emplace("json", JSON_DATA);
  3100. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3101. ASSERT_TRUE(res);
  3102. ASSERT_EQ(StatusCode::OK_200, res->status);
  3103. ASSERT_EQ(JSON_DATA, res->body);
  3104. }
  3105. TEST_F(ServerTest, PostEmptyContent) {
  3106. auto res = cli_.Post("/empty", "", "text/plain");
  3107. ASSERT_TRUE(res);
  3108. ASSERT_EQ(StatusCode::OK_200, res->status);
  3109. ASSERT_EQ("empty", res->body);
  3110. }
  3111. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3112. auto res = cli_.Post("/empty-no-content-type");
  3113. ASSERT_TRUE(res);
  3114. ASSERT_EQ(StatusCode::OK_200, res->status);
  3115. ASSERT_EQ("empty-no-content-type", res->body);
  3116. }
  3117. TEST_F(ServerTest, PostPathOnly) {
  3118. auto res = cli_.Post("/path-only");
  3119. ASSERT_TRUE(res);
  3120. ASSERT_EQ(StatusCode::OK_200, res->status);
  3121. ASSERT_EQ("path-only", res->body);
  3122. }
  3123. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3124. auto res = cli_.Post("/path-headers-only",
  3125. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3126. ASSERT_TRUE(res);
  3127. ASSERT_EQ(StatusCode::OK_200, res->status);
  3128. ASSERT_EQ("path-headers-only", res->body);
  3129. }
  3130. TEST_F(ServerTest, PostLarge) {
  3131. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3132. ASSERT_TRUE(res);
  3133. ASSERT_EQ(StatusCode::OK_200, res->status);
  3134. EXPECT_EQ(LARGE_DATA, res->body);
  3135. }
  3136. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3137. auto res = cli_.Put("/empty-no-content-type");
  3138. ASSERT_TRUE(res);
  3139. ASSERT_EQ(StatusCode::OK_200, res->status);
  3140. ASSERT_EQ("empty-no-content-type", res->body);
  3141. }
  3142. TEST_F(ServerTest, GetMethodDir) {
  3143. auto res = cli_.Get("/dir/");
  3144. ASSERT_TRUE(res);
  3145. EXPECT_EQ(StatusCode::OK_200, res->status);
  3146. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3147. auto body = R"(<html>
  3148. <head>
  3149. </head>
  3150. <body>
  3151. <a href="/dir/test.html">Test</a>
  3152. <a href="/hi">hi</a>
  3153. </body>
  3154. </html>
  3155. )";
  3156. EXPECT_EQ(body, res->body);
  3157. }
  3158. TEST_F(ServerTest, GetMethodDirTest) {
  3159. auto res = cli_.Get("/dir/test.html");
  3160. ASSERT_TRUE(res);
  3161. EXPECT_EQ(StatusCode::OK_200, res->status);
  3162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3163. EXPECT_EQ("test.html", res->body);
  3164. }
  3165. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3166. auto res = cli_.Get("/dir/../dir/test.html");
  3167. ASSERT_TRUE(res);
  3168. EXPECT_EQ(StatusCode::OK_200, res->status);
  3169. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3170. EXPECT_EQ("test.html", res->body);
  3171. }
  3172. TEST_F(ServerTest, GetMethodInvalidPath) {
  3173. auto res = cli_.Get("/dir/../test.html");
  3174. ASSERT_TRUE(res);
  3175. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3176. }
  3177. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3178. auto res = cli_.Get("/../www/dir/test.html");
  3179. ASSERT_TRUE(res);
  3180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3181. }
  3182. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3183. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3186. }
  3187. TEST_F(ServerTest, GetMethodDirMountTest) {
  3188. auto res = cli_.Get("/mount/dir/test.html");
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3192. EXPECT_EQ("test.html", res->body);
  3193. }
  3194. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3195. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3199. EXPECT_EQ("test.html", res->body);
  3200. }
  3201. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3202. auto res = cli_.Get("/mount/dir/../test.html");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3205. }
  3206. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3207. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3208. ASSERT_TRUE(res);
  3209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3210. }
  3211. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3212. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3215. }
  3216. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3217. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3220. }
  3221. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3222. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3223. ASSERT_TRUE(res);
  3224. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3225. }
  3226. TEST_F(ServerTest, PostMethod303) {
  3227. auto res = cli_.Post("/1", "body", "text/plain");
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3230. EXPECT_EQ("/2", res->get_header_value("Location"));
  3231. }
  3232. TEST_F(ServerTest, PostMethod303Redirect) {
  3233. cli_.set_follow_location(true);
  3234. auto res = cli_.Post("/1", "body", "text/plain");
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::OK_200, res->status);
  3237. EXPECT_EQ("redirected.", res->body);
  3238. EXPECT_EQ("/2", res->location);
  3239. }
  3240. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3241. auto res = cli_.Get("/dir/test.abcde");
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::OK_200, res->status);
  3244. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3245. EXPECT_EQ("abcde", res->body);
  3246. }
  3247. TEST_F(ServerTest, StaticFileRange) {
  3248. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3251. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3252. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3253. EXPECT_EQ(true, res->has_header("Content-Range"));
  3254. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3255. EXPECT_EQ(std::string("cd"), res->body);
  3256. }
  3257. TEST_F(ServerTest, StaticFileRanges) {
  3258. auto res =
  3259. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3262. EXPECT_TRUE(
  3263. res->get_header_value("Content-Type")
  3264. .find(
  3265. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3266. 0);
  3267. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3268. }
  3269. TEST_F(ServerTest, StaticFileRangeHead) {
  3270. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3273. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3274. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3275. EXPECT_EQ(true, res->has_header("Content-Range"));
  3276. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3277. }
  3278. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3279. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3280. ASSERT_TRUE(res);
  3281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3283. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3284. EXPECT_EQ(true, res->has_header("Content-Range"));
  3285. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3286. res->get_header_value("Content-Range"));
  3287. EXPECT_EQ("LAST\n", res->body);
  3288. }
  3289. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3290. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3291. ASSERT_TRUE(res);
  3292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3294. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3295. EXPECT_EQ(true, res->has_header("Content-Range"));
  3296. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3297. }
  3298. TEST_F(ServerTest, StaticFileBigFile) {
  3299. auto res = cli_.Get("/dir/1MB.txt");
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3304. }
  3305. TEST_F(ServerTest, InvalidBaseDirMount) {
  3306. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3307. }
  3308. TEST_F(ServerTest, Binary) {
  3309. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3310. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3311. "application/octet-stream");
  3312. ASSERT_TRUE(res);
  3313. ASSERT_EQ(StatusCode::OK_200, res->status);
  3314. ASSERT_EQ(4U, res->body.size());
  3315. res = cli_.Put("/binary", binary.data(), binary.size(),
  3316. "application/octet-stream");
  3317. ASSERT_TRUE(res);
  3318. ASSERT_EQ(StatusCode::OK_200, res->status);
  3319. ASSERT_EQ(4U, res->body.size());
  3320. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3321. "application/octet-stream");
  3322. ASSERT_TRUE(res);
  3323. ASSERT_EQ(StatusCode::OK_200, res->status);
  3324. ASSERT_EQ(4U, res->body.size());
  3325. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3326. "application/octet-stream");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ(4U, res->body.size());
  3330. }
  3331. TEST_F(ServerTest, BinaryString) {
  3332. auto binary = std::string("\x00\x01\x02\x03", 4);
  3333. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3334. ASSERT_TRUE(res);
  3335. ASSERT_EQ(StatusCode::OK_200, res->status);
  3336. ASSERT_EQ(4U, res->body.size());
  3337. res = cli_.Put("/binary", binary, "application/octet-stream");
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. ASSERT_EQ(4U, res->body.size());
  3341. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::OK_200, res->status);
  3344. ASSERT_EQ(4U, res->body.size());
  3345. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3346. ASSERT_TRUE(res);
  3347. ASSERT_EQ(StatusCode::OK_200, res->status);
  3348. ASSERT_EQ(4U, res->body.size());
  3349. }
  3350. TEST_F(ServerTest, EmptyRequest) {
  3351. auto res = cli_.Get("");
  3352. ASSERT_TRUE(!res);
  3353. EXPECT_EQ(Error::Connection, res.error());
  3354. }
  3355. TEST_F(ServerTest, LongRequest) {
  3356. std::string request;
  3357. for (size_t i = 0; i < 545; i++) {
  3358. request += "/TooLongRequest";
  3359. }
  3360. request += "OK";
  3361. auto res = cli_.Get(request.c_str());
  3362. ASSERT_TRUE(res);
  3363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3364. }
  3365. TEST_F(ServerTest, TooLongRequest) {
  3366. std::string request;
  3367. for (size_t i = 0; i < 546; i++) {
  3368. request += "/TooLongRequest";
  3369. }
  3370. request += "_NG";
  3371. auto res = cli_.Get(request.c_str());
  3372. ASSERT_TRUE(res);
  3373. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3374. }
  3375. TEST_F(ServerTest, AlmostTooLongRequest) {
  3376. // test for #2046 - URI length check shouldn't include other content on req
  3377. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3378. // leading /, space, HTTP/1.1)
  3379. std::string request =
  3380. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3381. auto res = cli_.Get(request.c_str());
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3384. }
  3385. TEST_F(ServerTest, LongHeader) {
  3386. Request req;
  3387. req.method = "GET";
  3388. req.path = "/hi";
  3389. std::string host_and_port;
  3390. host_and_port += HOST;
  3391. host_and_port += ":";
  3392. host_and_port += std::to_string(PORT);
  3393. req.headers.emplace("Host", host_and_port.c_str());
  3394. req.headers.emplace("Accept", "*/*");
  3395. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3396. req.headers.emplace(
  3397. "Header-Name",
  3398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3426. "@@@@@@@@@@@@@@@@");
  3427. auto res = std::make_shared<Response>();
  3428. auto error = Error::Success;
  3429. auto ret = cli_.send(req, *res, error);
  3430. ASSERT_TRUE(ret);
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. }
  3433. TEST_F(ServerTest, LongQueryValue) {
  3434. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3435. ASSERT_TRUE(res);
  3436. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3437. }
  3438. TEST_F(ServerTest, TooLongQueryValue) {
  3439. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3440. ASSERT_FALSE(res);
  3441. EXPECT_EQ(Error::Read, res.error());
  3442. }
  3443. TEST_F(ServerTest, TooLongHeader) {
  3444. Request req;
  3445. req.method = "GET";
  3446. req.path = "/hi";
  3447. std::string host_and_port;
  3448. host_and_port += HOST;
  3449. host_and_port += ":";
  3450. host_and_port += std::to_string(PORT);
  3451. req.headers.emplace("Host", host_and_port.c_str());
  3452. req.headers.emplace("Accept", "*/*");
  3453. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3454. req.headers.emplace(
  3455. "Header-Name",
  3456. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3457. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3458. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3459. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3460. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3461. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3462. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3463. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3464. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3465. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3466. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3467. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3468. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3469. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3470. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3471. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3472. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3473. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3474. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3475. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3476. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3477. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3478. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3479. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3480. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3481. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3482. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3483. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3484. "@@@@@@@@@@@@@@@@@");
  3485. auto res = std::make_shared<Response>();
  3486. auto error = Error::Success;
  3487. auto ret = cli_.send(req, *res, error);
  3488. ASSERT_TRUE(ret);
  3489. EXPECT_EQ(StatusCode::OK_200, res->status);
  3490. }
  3491. TEST_F(ServerTest, HeaderCountAtLimit) {
  3492. // Test with headers just under the 100 limit
  3493. httplib::Headers headers;
  3494. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3495. // This should keep us just under the 100 header limit
  3496. for (int i = 0; i < 95; i++) {
  3497. std::string name = "X-Test-Header-" + std::to_string(i);
  3498. std::string value = "value" + std::to_string(i);
  3499. headers.emplace(name, value);
  3500. }
  3501. // This should work fine as we're under the limit
  3502. auto res = cli_.Get("/hi", headers);
  3503. EXPECT_TRUE(res);
  3504. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3505. }
  3506. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3507. // Test with many headers to exceed the 100 limit
  3508. httplib::Headers headers;
  3509. // Add 150 headers to definitely exceed the 100 limit
  3510. for (int i = 0; i < 150; i++) {
  3511. std::string name = "X-Test-Header-" + std::to_string(i);
  3512. std::string value = "value" + std::to_string(i);
  3513. headers.emplace(name, value);
  3514. }
  3515. // This should fail due to exceeding header count limit
  3516. auto res = cli_.Get("/hi", headers);
  3517. // The request should either fail or return 400 Bad Request
  3518. if (res) {
  3519. // If we get a response, it should be 400 Bad Request
  3520. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3521. } else {
  3522. // Or the request should fail entirely
  3523. EXPECT_FALSE(res);
  3524. }
  3525. }
  3526. TEST_F(ServerTest, PercentEncoding) {
  3527. auto res = cli_.Get("/e%6edwith%");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. }
  3531. TEST_F(ServerTest, PercentEncodingUnicode) {
  3532. auto res = cli_.Get("/e%u006edwith%");
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::OK_200, res->status);
  3535. }
  3536. TEST_F(ServerTest, InvalidPercentEncoding) {
  3537. auto res = cli_.Get("/%endwith%");
  3538. ASSERT_TRUE(res);
  3539. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3540. }
  3541. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3542. auto res = cli_.Get("/%uendwith%");
  3543. ASSERT_TRUE(res);
  3544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3545. }
  3546. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3547. auto res = cli_.Get("/hello?aaa=bbb%");
  3548. ASSERT_TRUE(res);
  3549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3550. }
  3551. TEST_F(ServerTest, PlusSignEncoding) {
  3552. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. EXPECT_EQ("a +b", res->body);
  3556. }
  3557. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3558. // This test simulates a potential DoS attack using many headers
  3559. // to verify our security fix prevents memory exhaustion
  3560. httplib::Headers attack_headers;
  3561. // Attempt to add many headers like an attacker would (200 headers to far
  3562. // exceed limit)
  3563. for (int i = 0; i < 200; i++) {
  3564. std::string name = "X-Attack-Header-" + std::to_string(i);
  3565. std::string value = "attack_payload_" + std::to_string(i);
  3566. attack_headers.emplace(name, value);
  3567. }
  3568. // Try to POST with excessive headers
  3569. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3570. // Should either fail or return 400 Bad Request due to security limit
  3571. if (res) {
  3572. // If we get a response, it should be 400 Bad Request
  3573. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3574. } else {
  3575. // Request failed, which is the expected behavior for DoS protection
  3576. EXPECT_FALSE(res);
  3577. }
  3578. }
  3579. TEST_F(ServerTest, MultipartFormData) {
  3580. MultipartFormDataItemsForClientInput items = {
  3581. {"text1", "text default", "", ""},
  3582. {"text2", "aωb", "", ""},
  3583. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3584. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3585. {"file3", "", "", "application/octet-stream"},
  3586. {"file4", "", "", " application/json tmp-string "}};
  3587. auto res = cli_.Post("/multipart", items);
  3588. ASSERT_TRUE(res);
  3589. EXPECT_EQ(StatusCode::OK_200, res->status);
  3590. }
  3591. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3592. MultipartFormDataItemsForClientInput items = {
  3593. {"text", "default text", "", ""},
  3594. {"multi_text1", "aaaaa", "", ""},
  3595. {"multi_text1", "bbbbb", "", ""},
  3596. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3597. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3598. "application/json"},
  3599. };
  3600. auto res = cli_.Post("/multipart/multi_file_values", items);
  3601. ASSERT_TRUE(res);
  3602. EXPECT_EQ(StatusCode::OK_200, res->status);
  3603. }
  3604. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3605. auto res = cli_.Get("/hi");
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3609. EXPECT_EQ("Hello World!", res->body);
  3610. }
  3611. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3612. Request req;
  3613. req.method = "POST";
  3614. req.path = "/chunked";
  3615. std::string host_and_port;
  3616. host_and_port += HOST;
  3617. host_and_port += ":";
  3618. host_and_port += std::to_string(PORT);
  3619. req.headers.emplace("Host", host_and_port.c_str());
  3620. req.headers.emplace("Accept", "*/*");
  3621. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3622. req.headers.emplace("Content-Type", "text/plain");
  3623. req.headers.emplace("Content-Length", "0");
  3624. req.headers.emplace(
  3625. "Transfer-Encoding",
  3626. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3627. // Client does not chunk, so make a chunked body manually.
  3628. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3629. auto res = std::make_shared<Response>();
  3630. auto error = Error::Success;
  3631. auto ret = cli_.send(req, *res, error);
  3632. ASSERT_TRUE(ret);
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. }
  3635. TEST_F(ServerTest, GetStreamed2) {
  3636. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3637. ASSERT_TRUE(res);
  3638. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3639. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3640. EXPECT_EQ(true, res->has_header("Content-Range"));
  3641. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3642. EXPECT_EQ(std::string("ab"), res->body);
  3643. }
  3644. TEST_F(ServerTest, GetStreamed) {
  3645. auto res = cli_.Get("/streamed");
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::OK_200, res->status);
  3648. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3649. EXPECT_EQ(std::string("aaabbb"), res->body);
  3650. }
  3651. TEST_F(ServerTest, GetStreamedWithRange1) {
  3652. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3653. ASSERT_TRUE(res);
  3654. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3655. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3656. EXPECT_EQ(true, res->has_header("Content-Range"));
  3657. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3658. EXPECT_EQ(std::string("def"), res->body);
  3659. }
  3660. TEST_F(ServerTest, GetStreamedWithRange2) {
  3661. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3662. ASSERT_TRUE(res);
  3663. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3664. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3665. EXPECT_EQ(true, res->has_header("Content-Range"));
  3666. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3667. EXPECT_EQ(std::string("bcdefg"), res->body);
  3668. }
  3669. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3670. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3671. ASSERT_TRUE(res);
  3672. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3673. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3674. EXPECT_EQ(true, res->has_header("Content-Range"));
  3675. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3676. EXPECT_EQ(std::string("efg"), res->body);
  3677. }
  3678. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3679. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3682. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3683. EXPECT_EQ(false, res->has_header("Content-Range"));
  3684. EXPECT_EQ(0U, res->body.size());
  3685. }
  3686. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3687. auto res = cli_.Get("/streamed-with-range",
  3688. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3689. "92233720368547758079223372036854775807"}});
  3690. ASSERT_TRUE(res);
  3691. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3692. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3693. EXPECT_EQ(false, res->has_header("Content-Range"));
  3694. EXPECT_EQ(0U, res->body.size());
  3695. }
  3696. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3697. auto res = cli_.Get(
  3698. "/with-range",
  3699. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3700. {"Accept-Encoding", ""}});
  3701. ASSERT_TRUE(res);
  3702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3703. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3704. EXPECT_EQ(true, res->has_header("Content-Range"));
  3705. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3706. EXPECT_EQ(std::string("abcdefg"), res->body);
  3707. }
  3708. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3709. auto res = cli_.Get("/with-range", {
  3710. {"Range", "bytes=0-"},
  3711. {"Accept-Encoding", ""},
  3712. });
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3715. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3716. EXPECT_EQ(true, res->has_header("Content-Range"));
  3717. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3718. EXPECT_EQ(std::string("abcdefg"), res->body);
  3719. }
  3720. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3721. auto res =
  3722. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3723. ASSERT_TRUE(res);
  3724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3725. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3726. EXPECT_EQ(false, res->has_header("Content-Range"));
  3727. EXPECT_EQ(267U, res->body.size());
  3728. // Check that both range contents are present
  3729. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3730. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3731. // Check that Content-Range headers are present for both ranges
  3732. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3733. std::string::npos);
  3734. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3735. std::string::npos);
  3736. }
  3737. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3738. Ranges ranges;
  3739. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3740. ranges.emplace_back(0, -1);
  3741. }
  3742. auto res =
  3743. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3744. ASSERT_TRUE(res);
  3745. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3746. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3747. EXPECT_EQ(false, res->has_header("Content-Range"));
  3748. EXPECT_EQ(0U, res->body.size());
  3749. }
  3750. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3751. auto res =
  3752. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3753. ASSERT_TRUE(res);
  3754. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3755. EXPECT_EQ(5U, res->body.size());
  3756. // Check that overlapping ranges are coalesced into a single range
  3757. EXPECT_EQ("bcdef", res->body);
  3758. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3759. // Should be single range, not multipart
  3760. EXPECT_TRUE(res->has_header("Content-Range"));
  3761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3762. }
  3763. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3764. auto res =
  3765. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3768. EXPECT_EQ(268U, res->body.size());
  3769. // Check that both range contents are present
  3770. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3771. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3772. // Check that Content-Range headers are present for both ranges
  3773. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3774. std::string::npos);
  3775. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3776. std::string::npos);
  3777. }
  3778. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3779. auto res =
  3780. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3781. ASSERT_TRUE(res);
  3782. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3783. EXPECT_EQ(269U, res->body.size());
  3784. // Check that both duplicate range contents are present
  3785. size_t first_abc = res->body.find("abc\r\n");
  3786. EXPECT_TRUE(first_abc != std::string::npos);
  3787. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3788. EXPECT_TRUE(second_abc != std::string::npos);
  3789. // Check that Content-Range headers are present for both ranges
  3790. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3791. EXPECT_TRUE(first_range != std::string::npos);
  3792. size_t second_range =
  3793. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3794. EXPECT_TRUE(second_range != std::string::npos);
  3795. }
  3796. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3797. auto res = cli_.Get("/streamed-with-range?error",
  3798. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3799. ASSERT_TRUE(res);
  3800. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3801. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3802. EXPECT_EQ(false, res->has_header("Content-Range"));
  3803. EXPECT_EQ(0U, res->body.size());
  3804. }
  3805. TEST_F(ServerTest, GetStreamedEndless) {
  3806. uint64_t offset = 0;
  3807. auto res = cli_.Get("/streamed-cancel",
  3808. [&](const char * /*data*/, uint64_t data_length) {
  3809. if (offset < 100) {
  3810. offset += data_length;
  3811. return true;
  3812. }
  3813. return false;
  3814. });
  3815. ASSERT_TRUE(!res);
  3816. EXPECT_EQ(Error::Canceled, res.error());
  3817. }
  3818. TEST_F(ServerTest, ClientStop) {
  3819. std::atomic_size_t count{4};
  3820. std::vector<std::thread> threads;
  3821. for (auto i = count.load(); i != 0; --i) {
  3822. threads.emplace_back([&]() {
  3823. auto res = cli_.Get("/streamed-cancel",
  3824. [&](const char *, uint64_t) { return true; });
  3825. --count;
  3826. ASSERT_TRUE(!res);
  3827. EXPECT_TRUE(res.error() == Error::Canceled ||
  3828. res.error() == Error::Read || res.error() == Error::Write);
  3829. });
  3830. }
  3831. std::this_thread::sleep_for(std::chrono::seconds(2));
  3832. while (count != 0) {
  3833. cli_.stop();
  3834. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3835. }
  3836. for (auto &t : threads) {
  3837. t.join();
  3838. }
  3839. }
  3840. TEST_F(ServerTest, GetWithRange1) {
  3841. auto res = cli_.Get("/with-range", {
  3842. make_range_header({{3, 5}}),
  3843. {"Accept-Encoding", ""},
  3844. });
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3847. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3848. EXPECT_EQ(true, res->has_header("Content-Range"));
  3849. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3850. EXPECT_EQ(std::string("def"), res->body);
  3851. }
  3852. TEST_F(ServerTest, GetWithRange2) {
  3853. auto res = cli_.Get("/with-range", {
  3854. make_range_header({{1, -1}}),
  3855. {"Accept-Encoding", ""},
  3856. });
  3857. ASSERT_TRUE(res);
  3858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3859. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3860. EXPECT_EQ(true, res->has_header("Content-Range"));
  3861. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3862. EXPECT_EQ(std::string("bcdefg"), res->body);
  3863. }
  3864. TEST_F(ServerTest, GetWithRange3) {
  3865. auto res = cli_.Get("/with-range", {
  3866. make_range_header({{0, 0}}),
  3867. {"Accept-Encoding", ""},
  3868. });
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3871. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3872. EXPECT_EQ(true, res->has_header("Content-Range"));
  3873. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3874. EXPECT_EQ(std::string("a"), res->body);
  3875. }
  3876. TEST_F(ServerTest, GetWithRange4) {
  3877. auto res = cli_.Get("/with-range", {
  3878. make_range_header({{-1, 2}}),
  3879. {"Accept-Encoding", ""},
  3880. });
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3883. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3884. EXPECT_EQ(true, res->has_header("Content-Range"));
  3885. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3886. EXPECT_EQ(std::string("fg"), res->body);
  3887. }
  3888. TEST_F(ServerTest, GetWithRange5) {
  3889. auto res = cli_.Get("/with-range", {
  3890. make_range_header({{0, 5}}),
  3891. {"Accept-Encoding", ""},
  3892. });
  3893. ASSERT_TRUE(res);
  3894. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3895. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3896. EXPECT_EQ(true, res->has_header("Content-Range"));
  3897. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3898. EXPECT_EQ(std::string("abcdef"), res->body);
  3899. }
  3900. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3901. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3902. ASSERT_TRUE(res);
  3903. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3904. }
  3905. TEST_F(ServerTest, GetWithRangeMultipart) {
  3906. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(false, res->has_header("Content-Range"));
  3911. EXPECT_EQ(267U, res->body.size());
  3912. }
  3913. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3914. auto res =
  3915. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3918. }
  3919. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3920. auto res = cli_.Get("/with-range-customized-response",
  3921. {{make_range_header({{1, 2}})}});
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3924. EXPECT_EQ(true, res->has_header("Content-Length"));
  3925. EXPECT_EQ(false, res->has_header("Content-Range"));
  3926. EXPECT_EQ(JSON_DATA, res->body);
  3927. }
  3928. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3929. auto res = cli_.Get("/with-range-customized-response",
  3930. {{make_range_header({{1, 2}, {4, 5}})}});
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3933. EXPECT_EQ(true, res->has_header("Content-Length"));
  3934. EXPECT_EQ(false, res->has_header("Content-Range"));
  3935. EXPECT_EQ(JSON_DATA, res->body);
  3936. }
  3937. TEST_F(ServerTest, Issue1772) {
  3938. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3941. }
  3942. TEST_F(ServerTest, Issue609) {
  3943. auto res = cli_.Delete("/issue609");
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ(std::string("ok"), res->body);
  3947. }
  3948. TEST_F(ServerTest, GetStreamedChunked) {
  3949. auto res = cli_.Get("/streamed-chunked");
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::OK_200, res->status);
  3952. EXPECT_EQ(std::string("123456789"), res->body);
  3953. }
  3954. TEST_F(ServerTest, GetStreamedChunked2) {
  3955. auto res = cli_.Get("/streamed-chunked2");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. EXPECT_EQ(std::string("123456789"), res->body);
  3959. }
  3960. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3961. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3962. ASSERT_TRUE(res);
  3963. EXPECT_EQ(StatusCode::OK_200, res->status);
  3964. EXPECT_EQ(std::string("123456789"), res->body);
  3965. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3966. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3967. }
  3968. TEST_F(ServerTest, LargeChunkedPost) {
  3969. Request req;
  3970. req.method = "POST";
  3971. req.path = "/large-chunked";
  3972. std::string host_and_port;
  3973. host_and_port += HOST;
  3974. host_and_port += ":";
  3975. host_and_port += std::to_string(PORT);
  3976. req.headers.emplace("Host", host_and_port.c_str());
  3977. req.headers.emplace("Accept", "*/*");
  3978. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3979. req.headers.emplace("Content-Type", "text/plain");
  3980. req.headers.emplace("Content-Length", "0");
  3981. req.headers.emplace("Transfer-Encoding", "chunked");
  3982. std::string long_string(30 * 1024u, 'a');
  3983. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3984. // Attempt to make a large enough post to exceed OS buffers, to test that
  3985. // the server handles short reads if the full chunk data isn't available.
  3986. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3987. auto res = std::make_shared<Response>();
  3988. auto error = Error::Success;
  3989. auto ret = cli_.send(req, *res, error);
  3990. ASSERT_TRUE(ret);
  3991. EXPECT_EQ(StatusCode::OK_200, res->status);
  3992. }
  3993. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3994. auto res = cli_.Get("/remote_addr");
  3995. ASSERT_TRUE(res);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3998. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3999. }
  4000. TEST_F(ServerTest, GetMethodLocalAddr) {
  4001. auto res = cli_.Get("/local_addr");
  4002. ASSERT_TRUE(res);
  4003. EXPECT_EQ(StatusCode::OK_200, res->status);
  4004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4005. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4006. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4007. }
  4008. TEST_F(ServerTest, HTTPResponseSplitting) {
  4009. auto res = cli_.Get("/http_response_splitting");
  4010. ASSERT_TRUE(res);
  4011. EXPECT_EQ(StatusCode::OK_200, res->status);
  4012. }
  4013. TEST_F(ServerTest, SlowRequest) {
  4014. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4015. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4016. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4017. }
  4018. #if 0
  4019. TEST_F(ServerTest, SlowPost) {
  4020. char buffer[64 * 1024];
  4021. memset(buffer, 0x42, sizeof(buffer));
  4022. auto res = cli_.Post(
  4023. "/slowpost", 64 * 1024 * 1024,
  4024. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4025. auto ret = sink.write(buffer, sizeof(buffer));
  4026. EXPECT_TRUE(ret);
  4027. return true;
  4028. },
  4029. "text/plain");
  4030. ASSERT_TRUE(res);
  4031. EXPECT_EQ(StatusCode::OK_200, res->status);
  4032. }
  4033. TEST_F(ServerTest, SlowPostFail) {
  4034. char buffer[64 * 1024];
  4035. memset(buffer, 0x42, sizeof(buffer));
  4036. cli_.set_write_timeout(std::chrono::seconds(0));
  4037. auto res = cli_.Post(
  4038. "/slowpost", 64 * 1024 * 1024,
  4039. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4040. sink.write(buffer, sizeof(buffer));
  4041. return true;
  4042. },
  4043. "text/plain");
  4044. ASSERT_TRUE(!res);
  4045. EXPECT_EQ(Error::Write, res.error());
  4046. }
  4047. #endif
  4048. TEST_F(ServerTest, Put) {
  4049. auto res = cli_.Put("/put", "PUT", "text/plain");
  4050. ASSERT_TRUE(res);
  4051. EXPECT_EQ(StatusCode::OK_200, res->status);
  4052. EXPECT_EQ("PUT", res->body);
  4053. }
  4054. TEST_F(ServerTest, PutWithContentProvider) {
  4055. auto res = cli_.Put(
  4056. "/put", 3,
  4057. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4058. sink.os << "PUT";
  4059. return true;
  4060. },
  4061. "text/plain");
  4062. ASSERT_TRUE(res);
  4063. EXPECT_EQ(StatusCode::OK_200, res->status);
  4064. EXPECT_EQ("PUT", res->body);
  4065. }
  4066. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4067. auto res = cli_.Post(
  4068. "/post", 42,
  4069. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4070. return false;
  4071. },
  4072. "text/plain");
  4073. ASSERT_TRUE(!res);
  4074. EXPECT_EQ(Error::Canceled, res.error());
  4075. }
  4076. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4077. auto res = cli_.Put(
  4078. "/put",
  4079. [](size_t /*offset*/, DataSink &sink) {
  4080. sink.os << "PUT";
  4081. sink.done();
  4082. return true;
  4083. },
  4084. "text/plain");
  4085. ASSERT_TRUE(res);
  4086. EXPECT_EQ(StatusCode::OK_200, res->status);
  4087. EXPECT_EQ("PUT", res->body);
  4088. }
  4089. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4090. auto res = cli_.Post(
  4091. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4092. "text/plain");
  4093. ASSERT_TRUE(!res);
  4094. EXPECT_EQ(Error::Canceled, res.error());
  4095. }
  4096. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4097. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4098. cli_.set_compress(true);
  4099. auto res = cli_.Put(
  4100. "/put", 3,
  4101. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4102. sink.os << "PUT";
  4103. return true;
  4104. },
  4105. "text/plain");
  4106. ASSERT_TRUE(res);
  4107. EXPECT_EQ(StatusCode::OK_200, res->status);
  4108. EXPECT_EQ("PUT", res->body);
  4109. }
  4110. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4111. cli_.set_compress(true);
  4112. auto res = cli_.Post(
  4113. "/post", 42,
  4114. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4115. return false;
  4116. },
  4117. "text/plain");
  4118. ASSERT_TRUE(!res);
  4119. EXPECT_EQ(Error::Canceled, res.error());
  4120. }
  4121. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4122. cli_.set_compress(true);
  4123. auto res = cli_.Put(
  4124. "/put",
  4125. [](size_t /*offset*/, DataSink &sink) {
  4126. sink.os << "PUT";
  4127. sink.done();
  4128. return true;
  4129. },
  4130. "text/plain");
  4131. ASSERT_TRUE(res);
  4132. EXPECT_EQ(StatusCode::OK_200, res->status);
  4133. EXPECT_EQ("PUT", res->body);
  4134. }
  4135. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4136. cli_.set_compress(true);
  4137. auto res = cli_.Post(
  4138. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4139. "text/plain");
  4140. ASSERT_TRUE(!res);
  4141. EXPECT_EQ(Error::Canceled, res.error());
  4142. }
  4143. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4144. cli_.set_compress(true);
  4145. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. EXPECT_EQ(LARGE_DATA, res->body);
  4149. }
  4150. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4151. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4152. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4153. Client cli(s.c_str());
  4154. cli.enable_server_certificate_verification(false);
  4155. #else
  4156. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4157. Client cli(s.c_str());
  4158. #endif
  4159. cli.set_compress(true);
  4160. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. EXPECT_EQ(LARGE_DATA, res->body);
  4164. // The compressed size should be less than a 10th of the original. May vary
  4165. // depending on the zlib library.
  4166. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4167. static_cast<uint64_t>(10 * 1024 * 1024));
  4168. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4169. }
  4170. TEST_F(ServerTest, PutContentWithDeflate) {
  4171. cli_.set_compress(false);
  4172. Headers headers;
  4173. headers.emplace("Content-Encoding", "deflate");
  4174. // PUT in deflate format:
  4175. auto res = cli_.Put("/put", headers,
  4176. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ(StatusCode::OK_200, res->status);
  4179. EXPECT_EQ("PUT", res->body);
  4180. }
  4181. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4182. Headers headers;
  4183. headers.emplace("Accept-Encoding", "gzip, deflate");
  4184. auto res = cli_.Get("/streamed-chunked", headers);
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. EXPECT_EQ(std::string("123456789"), res->body);
  4188. }
  4189. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4190. Headers headers;
  4191. headers.emplace("Accept-Encoding", "gzip, deflate");
  4192. auto res = cli_.Get("/streamed-chunked2", headers);
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::OK_200, res->status);
  4195. EXPECT_EQ(std::string("123456789"), res->body);
  4196. }
  4197. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4198. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4199. ASSERT_TRUE(res);
  4200. EXPECT_EQ(StatusCode::OK_200, res->status);
  4201. }
  4202. TEST(GzipDecompressor, ChunkedDecompression) {
  4203. std::string data;
  4204. for (size_t i = 0; i < 32 * 1024; ++i) {
  4205. data.push_back(static_cast<char>('a' + i % 26));
  4206. }
  4207. std::string compressed_data;
  4208. {
  4209. httplib::detail::gzip_compressor compressor;
  4210. bool result = compressor.compress(
  4211. data.data(), data.size(),
  4212. /*last=*/true,
  4213. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4214. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4215. compressed_data_size);
  4216. return true;
  4217. });
  4218. ASSERT_TRUE(result);
  4219. }
  4220. std::string decompressed_data;
  4221. {
  4222. httplib::detail::gzip_decompressor decompressor;
  4223. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4224. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4225. size_t chunk_size = 130;
  4226. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4227. chunk_begin += chunk_size) {
  4228. size_t current_chunk_size =
  4229. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4230. bool result = decompressor.decompress(
  4231. compressed_data.data() + chunk_begin, current_chunk_size,
  4232. [&](const char *decompressed_data_chunk,
  4233. size_t decompressed_data_chunk_size) {
  4234. decompressed_data.insert(decompressed_data.size(),
  4235. decompressed_data_chunk,
  4236. decompressed_data_chunk_size);
  4237. return true;
  4238. });
  4239. ASSERT_TRUE(result);
  4240. }
  4241. }
  4242. ASSERT_EQ(data, decompressed_data);
  4243. }
  4244. TEST(GzipDecompressor, DeflateDecompression) {
  4245. std::string original_text = "Raw deflate without gzip";
  4246. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4247. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4248. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4249. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4250. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4251. std::string decompressed_data;
  4252. {
  4253. httplib::detail::gzip_decompressor decompressor;
  4254. bool result = decompressor.decompress(
  4255. compressed_data.data(), compressed_data.size(),
  4256. [&](const char *decompressed_data_chunk,
  4257. size_t decompressed_data_chunk_size) {
  4258. decompressed_data.insert(decompressed_data.size(),
  4259. decompressed_data_chunk,
  4260. decompressed_data_chunk_size);
  4261. return true;
  4262. });
  4263. ASSERT_TRUE(result);
  4264. }
  4265. ASSERT_EQ(original_text, decompressed_data);
  4266. }
  4267. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4268. std::string original_text = "Raw deflate without gzip";
  4269. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4270. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4271. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4272. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4273. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4274. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4275. std::string decompressed_data;
  4276. {
  4277. httplib::detail::gzip_decompressor decompressor;
  4278. bool result = decompressor.decompress(
  4279. compressed_data.data(), compressed_data.size(),
  4280. [&](const char *decompressed_data_chunk,
  4281. size_t decompressed_data_chunk_size) {
  4282. decompressed_data.insert(decompressed_data.size(),
  4283. decompressed_data_chunk,
  4284. decompressed_data_chunk_size);
  4285. return true;
  4286. });
  4287. ASSERT_TRUE(result);
  4288. }
  4289. ASSERT_EQ(original_text, decompressed_data);
  4290. }
  4291. #ifdef _WIN32
  4292. TEST(GzipDecompressor, LargeRandomData) {
  4293. // prepare large random data that is difficult to be compressed and is
  4294. // expected to have large size even when compressed
  4295. std::random_device seed_gen;
  4296. std::mt19937 random(seed_gen());
  4297. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4298. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4299. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4300. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4301. // compress data over 4GiB
  4302. std::string compressed_data;
  4303. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4304. httplib::detail::gzip_compressor compressor;
  4305. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4306. data.size() * sizeof(std::uint32_t), true,
  4307. [&](const char *data, size_t size) {
  4308. compressed_data.insert(
  4309. compressed_data.size(), data, size);
  4310. return true;
  4311. });
  4312. ASSERT_TRUE(result);
  4313. // FIXME: compressed data size is expected to be greater than 4GiB,
  4314. // but there is no guarantee
  4315. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4316. // decompress data over 4GiB
  4317. std::string decompressed_data;
  4318. decompressed_data.reserve(data_size);
  4319. httplib::detail::gzip_decompressor decompressor;
  4320. result = decompressor.decompress(
  4321. compressed_data.data(), compressed_data.size(),
  4322. [&](const char *data, size_t size) {
  4323. decompressed_data.insert(decompressed_data.size(), data, size);
  4324. return true;
  4325. });
  4326. ASSERT_TRUE(result);
  4327. // compare
  4328. ASSERT_EQ(data_size, decompressed_data.size());
  4329. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4330. 0);
  4331. }
  4332. #endif
  4333. #endif
  4334. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4335. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4336. Headers headers;
  4337. headers.emplace("Accept-Encoding", "br");
  4338. auto res = cli_.Get("/streamed-chunked", headers);
  4339. ASSERT_TRUE(res);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. EXPECT_EQ(std::string("123456789"), res->body);
  4342. }
  4343. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4344. Headers headers;
  4345. headers.emplace("Accept-Encoding", "br");
  4346. auto res = cli_.Get("/streamed-chunked2", headers);
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. EXPECT_EQ(std::string("123456789"), res->body);
  4350. }
  4351. #endif
  4352. TEST_F(ServerTest, Patch) {
  4353. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::OK_200, res->status);
  4356. EXPECT_EQ("PATCH", res->body);
  4357. }
  4358. TEST_F(ServerTest, Delete) {
  4359. auto res = cli_.Delete("/delete");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. EXPECT_EQ("DELETE", res->body);
  4363. }
  4364. TEST_F(ServerTest, DeleteContentReceiver) {
  4365. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. EXPECT_EQ("content", res->body);
  4369. }
  4370. TEST_F(ServerTest, Options) {
  4371. auto res = cli_.Options("*");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4375. EXPECT_TRUE(res->body.empty());
  4376. }
  4377. TEST_F(ServerTest, URL) {
  4378. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. TEST_F(ServerTest, ArrayParam) {
  4383. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::OK_200, res->status);
  4386. }
  4387. TEST_F(ServerTest, NoMultipleHeaders) {
  4388. Headers headers = {{"Content-Length", "5"}};
  4389. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4390. "text/plain");
  4391. ASSERT_TRUE(res);
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. }
  4394. TEST_F(ServerTest, PostContentReceiver) {
  4395. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4396. ASSERT_TRUE(res);
  4397. ASSERT_EQ(StatusCode::OK_200, res->status);
  4398. ASSERT_EQ("content", res->body);
  4399. }
  4400. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4401. MultipartFormDataItemsForClientInput items = {
  4402. {"text1", "text default", "", ""},
  4403. {"text2", "aωb", "", ""},
  4404. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4405. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4406. {"file3", "", "", "application/octet-stream"},
  4407. };
  4408. auto res = cli_.Post("/content_receiver", items);
  4409. ASSERT_TRUE(res);
  4410. EXPECT_EQ(StatusCode::OK_200, res->status);
  4411. }
  4412. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4413. MultipartFormDataItemsForClientInput items = {
  4414. {"text1", "text default", "", ""},
  4415. {"text2", "aωb", "", ""},
  4416. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4417. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4418. {"file3", "", "", "application/octet-stream"},
  4419. };
  4420. auto boundary = std::string("+++++");
  4421. std::string body;
  4422. for (const auto &item : items) {
  4423. body += "--" + boundary + "\r\n";
  4424. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4425. if (!item.filename.empty()) {
  4426. body += "; filename=\"" + item.filename + "\"";
  4427. }
  4428. body += "\r\n";
  4429. if (!item.content_type.empty()) {
  4430. body += "Content-Type: " + item.content_type + "\r\n";
  4431. }
  4432. body += "\r\n";
  4433. body += item.content + "\r\n";
  4434. }
  4435. body += "--" + boundary + "--\r\n";
  4436. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4437. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4438. ASSERT_TRUE(res);
  4439. EXPECT_EQ(StatusCode::OK_200, res->status);
  4440. }
  4441. TEST_F(ServerTest, PostContentReceiverGzip) {
  4442. cli_.set_compress(true);
  4443. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4444. ASSERT_TRUE(res);
  4445. ASSERT_EQ(StatusCode::OK_200, res->status);
  4446. ASSERT_EQ("content", res->body);
  4447. }
  4448. TEST_F(ServerTest, PutContentReceiver) {
  4449. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4450. ASSERT_TRUE(res);
  4451. ASSERT_EQ(StatusCode::OK_200, res->status);
  4452. ASSERT_EQ("content", res->body);
  4453. }
  4454. TEST_F(ServerTest, PatchContentReceiver) {
  4455. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4456. ASSERT_TRUE(res);
  4457. ASSERT_EQ(StatusCode::OK_200, res->status);
  4458. ASSERT_EQ("content", res->body);
  4459. }
  4460. TEST_F(ServerTest, PostQueryStringAndBody) {
  4461. auto res =
  4462. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4463. ASSERT_TRUE(res);
  4464. ASSERT_EQ(StatusCode::OK_200, res->status);
  4465. }
  4466. TEST_F(ServerTest, HTTP2Magic) {
  4467. Request req;
  4468. req.method = "PRI";
  4469. req.path = "*";
  4470. req.body = "SM";
  4471. auto res = std::make_shared<Response>();
  4472. auto error = Error::Success;
  4473. auto ret = cli_.send(req, *res, error);
  4474. ASSERT_TRUE(ret);
  4475. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4476. }
  4477. TEST_F(ServerTest, KeepAlive) {
  4478. auto res = cli_.Get("/hi");
  4479. ASSERT_TRUE(res);
  4480. EXPECT_EQ(StatusCode::OK_200, res->status);
  4481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4482. EXPECT_EQ("Hello World!", res->body);
  4483. res = cli_.Get("/hi");
  4484. ASSERT_TRUE(res);
  4485. EXPECT_EQ(StatusCode::OK_200, res->status);
  4486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4487. EXPECT_EQ("Hello World!", res->body);
  4488. res = cli_.Get("/hi");
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4492. EXPECT_EQ("Hello World!", res->body);
  4493. res = cli_.Get("/not-exist");
  4494. ASSERT_TRUE(res);
  4495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4496. res = cli_.Post("/empty", "", "text/plain");
  4497. ASSERT_TRUE(res);
  4498. EXPECT_EQ(StatusCode::OK_200, res->status);
  4499. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4500. EXPECT_EQ("empty", res->body);
  4501. EXPECT_EQ("close", res->get_header_value("Connection"));
  4502. res = cli_.Post(
  4503. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4504. "text/plain");
  4505. ASSERT_TRUE(res);
  4506. EXPECT_EQ(StatusCode::OK_200, res->status);
  4507. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4508. EXPECT_EQ("empty", res->body);
  4509. cli_.set_keep_alive(false);
  4510. res = cli_.Get("/last-request");
  4511. ASSERT_TRUE(res);
  4512. EXPECT_EQ(StatusCode::OK_200, res->status);
  4513. EXPECT_EQ("close", res->get_header_value("Connection"));
  4514. }
  4515. TEST_F(ServerTest, TooManyRedirect) {
  4516. cli_.set_follow_location(true);
  4517. auto res = cli_.Get("/redirect/0");
  4518. ASSERT_TRUE(!res);
  4519. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4520. }
  4521. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4522. TEST_F(ServerTest, Gzip) {
  4523. Headers headers;
  4524. headers.emplace("Accept-Encoding", "gzip, deflate");
  4525. auto res = cli_.Get("/compress", headers);
  4526. ASSERT_TRUE(res);
  4527. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4529. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4530. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4531. "7890123456789012345678901234567890",
  4532. res->body);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. }
  4535. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4536. Headers headers;
  4537. headers.emplace("Accept-Encoding", "");
  4538. auto res = cli_.Get("/compress", headers);
  4539. ASSERT_TRUE(res);
  4540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4544. "7890123456789012345678901234567890",
  4545. res->body);
  4546. EXPECT_EQ(StatusCode::OK_200, res->status);
  4547. }
  4548. TEST_F(ServerTest, GzipWithContentReceiver) {
  4549. Headers headers;
  4550. headers.emplace("Accept-Encoding", "gzip, deflate");
  4551. std::string body;
  4552. auto res = cli_.Get("/compress", headers,
  4553. [&](const char *data, uint64_t data_length) {
  4554. EXPECT_EQ(100U, data_length);
  4555. body.append(data, data_length);
  4556. return true;
  4557. });
  4558. ASSERT_TRUE(res);
  4559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4561. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4562. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4563. "7890123456789012345678901234567890",
  4564. body);
  4565. EXPECT_EQ(StatusCode::OK_200, res->status);
  4566. }
  4567. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4568. Headers headers;
  4569. headers.emplace("Accept-Encoding", "gzip, deflate");
  4570. cli_.set_decompress(false);
  4571. auto res = cli_.Get("/compress", headers);
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4576. EXPECT_EQ(33U, res->body.size());
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. }
  4579. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4580. Headers headers;
  4581. headers.emplace("Accept-Encoding", "");
  4582. std::string body;
  4583. auto res = cli_.Get("/compress", headers,
  4584. [&](const char *data, uint64_t data_length) {
  4585. EXPECT_EQ(100U, data_length);
  4586. body.append(data, data_length);
  4587. return true;
  4588. });
  4589. ASSERT_TRUE(res);
  4590. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4591. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4592. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4593. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4594. "7890123456789012345678901234567890",
  4595. body);
  4596. EXPECT_EQ(StatusCode::OK_200, res->status);
  4597. }
  4598. TEST_F(ServerTest, NoGzip) {
  4599. Headers headers;
  4600. headers.emplace("Accept-Encoding", "gzip, deflate");
  4601. auto res = cli_.Get("/nocompress", headers);
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4604. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4605. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4607. "7890123456789012345678901234567890",
  4608. res->body);
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. }
  4611. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4612. Headers headers;
  4613. headers.emplace("Accept-Encoding", "gzip, deflate");
  4614. std::string body;
  4615. auto res = cli_.Get("/nocompress", headers,
  4616. [&](const char *data, uint64_t data_length) {
  4617. EXPECT_EQ(100U, data_length);
  4618. body.append(data, data_length);
  4619. return true;
  4620. });
  4621. ASSERT_TRUE(res);
  4622. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4623. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4626. "7890123456789012345678901234567890",
  4627. body);
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. }
  4630. TEST_F(ServerTest, MultipartFormDataGzip) {
  4631. MultipartFormDataItemsForClientInput items = {
  4632. {"key1", "test", "", ""},
  4633. {"key2", "--abcdefg123", "", ""},
  4634. };
  4635. cli_.set_compress(true);
  4636. auto res = cli_.Post("/compress-multipart", items);
  4637. ASSERT_TRUE(res);
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. }
  4640. #endif
  4641. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4642. TEST_F(ServerTest, Brotli) {
  4643. Headers headers;
  4644. headers.emplace("Accept-Encoding", "br");
  4645. auto res = cli_.Get("/compress", headers);
  4646. ASSERT_TRUE(res);
  4647. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4648. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4649. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4650. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4651. "7890123456789012345678901234567890",
  4652. res->body);
  4653. EXPECT_EQ(StatusCode::OK_200, res->status);
  4654. }
  4655. #endif
  4656. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4657. TEST_F(ServerTest, Zstd) {
  4658. Headers headers;
  4659. headers.emplace("Accept-Encoding", "zstd");
  4660. auto res = cli_.Get("/compress", headers);
  4661. ASSERT_TRUE(res);
  4662. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4663. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4664. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4666. "7890123456789012345678901234567890",
  4667. res->body);
  4668. EXPECT_EQ(StatusCode::OK_200, res->status);
  4669. }
  4670. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4671. Headers headers;
  4672. headers.emplace("Accept-Encoding", "");
  4673. auto res = cli_.Get("/compress", headers);
  4674. ASSERT_TRUE(res);
  4675. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4676. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4677. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4678. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4679. "7890123456789012345678901234567890",
  4680. res->body);
  4681. EXPECT_EQ(StatusCode::OK_200, res->status);
  4682. }
  4683. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4684. Headers headers;
  4685. headers.emplace("Accept-Encoding", "zstd");
  4686. std::string body;
  4687. auto res = cli_.Get("/compress", headers,
  4688. [&](const char *data, uint64_t data_length) {
  4689. EXPECT_EQ(100U, data_length);
  4690. body.append(data, data_length);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(res);
  4694. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4696. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4697. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4698. "7890123456789012345678901234567890",
  4699. body);
  4700. EXPECT_EQ(StatusCode::OK_200, res->status);
  4701. }
  4702. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4703. Headers headers;
  4704. headers.emplace("Accept-Encoding", "zstd");
  4705. cli_.set_decompress(false);
  4706. auto res = cli_.Get("/compress", headers);
  4707. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4708. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4709. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4710. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4711. ASSERT_TRUE(res);
  4712. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4714. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. ASSERT_EQ(26U, res->body.size());
  4717. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4718. 0);
  4719. }
  4720. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4721. Headers headers;
  4722. headers.emplace("Accept-Encoding", "");
  4723. std::string body;
  4724. auto res = cli_.Get("/compress", headers,
  4725. [&](const char *data, uint64_t data_length) {
  4726. EXPECT_EQ(100U, data_length);
  4727. body.append(data, data_length);
  4728. return true;
  4729. });
  4730. ASSERT_TRUE(res);
  4731. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4732. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4733. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4734. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4735. "7890123456789012345678901234567890",
  4736. body);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. }
  4739. TEST_F(ServerTest, NoZstd) {
  4740. Headers headers;
  4741. headers.emplace("Accept-Encoding", "zstd");
  4742. auto res = cli_.Get("/nocompress", headers);
  4743. ASSERT_TRUE(res);
  4744. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4745. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4746. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4747. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4748. "7890123456789012345678901234567890",
  4749. res->body);
  4750. EXPECT_EQ(StatusCode::OK_200, res->status);
  4751. }
  4752. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4753. Headers headers;
  4754. headers.emplace("Accept-Encoding", "zstd");
  4755. std::string body;
  4756. auto res = cli_.Get("/nocompress", headers,
  4757. [&](const char *data, uint64_t data_length) {
  4758. EXPECT_EQ(100U, data_length);
  4759. body.append(data, data_length);
  4760. return true;
  4761. });
  4762. ASSERT_TRUE(res);
  4763. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4764. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4765. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4766. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4767. "7890123456789012345678901234567890",
  4768. body);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. }
  4771. // TODO: How to enable zstd ??
  4772. TEST_F(ServerTest, MultipartFormDataZstd) {
  4773. MultipartFormDataItemsForClientInput items = {
  4774. {"key1", "test", "", ""},
  4775. {"key2", "--abcdefg123", "", ""},
  4776. };
  4777. Headers headers;
  4778. headers.emplace("Accept-Encoding", "zstd");
  4779. cli_.set_compress(true);
  4780. auto res = cli_.Post("/compress-multipart", headers, items);
  4781. ASSERT_TRUE(res);
  4782. EXPECT_EQ(StatusCode::OK_200, res->status);
  4783. }
  4784. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4785. Headers headers;
  4786. headers.emplace("Accept-Encoding", "zstd");
  4787. cli_.set_compress(true);
  4788. auto res = cli_.Put(
  4789. "/put", headers, 3,
  4790. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4791. sink.os << "PUT";
  4792. return true;
  4793. },
  4794. "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("PUT", res->body);
  4798. }
  4799. TEST(ZstdDecompressor, ChunkedDecompression) {
  4800. std::string data;
  4801. for (size_t i = 0; i < 32 * 1024; ++i) {
  4802. data.push_back(static_cast<char>('a' + i % 26));
  4803. }
  4804. std::string compressed_data;
  4805. {
  4806. httplib::detail::zstd_compressor compressor;
  4807. bool result = compressor.compress(
  4808. data.data(), data.size(),
  4809. /*last=*/true,
  4810. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4811. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4812. compressed_data_size);
  4813. return true;
  4814. });
  4815. ASSERT_TRUE(result);
  4816. }
  4817. std::string decompressed_data;
  4818. {
  4819. httplib::detail::zstd_decompressor decompressor;
  4820. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4821. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4822. size_t chunk_size = 130;
  4823. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4824. chunk_begin += chunk_size) {
  4825. size_t current_chunk_size =
  4826. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4827. bool result = decompressor.decompress(
  4828. compressed_data.data() + chunk_begin, current_chunk_size,
  4829. [&](const char *decompressed_data_chunk,
  4830. size_t decompressed_data_chunk_size) {
  4831. decompressed_data.insert(decompressed_data.size(),
  4832. decompressed_data_chunk,
  4833. decompressed_data_chunk_size);
  4834. return true;
  4835. });
  4836. ASSERT_TRUE(result);
  4837. }
  4838. }
  4839. ASSERT_EQ(data, decompressed_data);
  4840. }
  4841. TEST(ZstdDecompressor, Decompress) {
  4842. std::string original_text = "Compressed with ZSTD";
  4843. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  4844. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  4845. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  4846. 0x20, 0x5a, 0x53, 0x54, 0x44};
  4847. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4848. std::string decompressed_data;
  4849. {
  4850. httplib::detail::zstd_decompressor decompressor;
  4851. bool result = decompressor.decompress(
  4852. compressed_data.data(), compressed_data.size(),
  4853. [&](const char *decompressed_data_chunk,
  4854. size_t decompressed_data_chunk_size) {
  4855. decompressed_data.insert(decompressed_data.size(),
  4856. decompressed_data_chunk,
  4857. decompressed_data_chunk_size);
  4858. return true;
  4859. });
  4860. ASSERT_TRUE(result);
  4861. }
  4862. ASSERT_EQ(original_text, decompressed_data);
  4863. }
  4864. #endif
  4865. // Sends a raw request to a server listening at HOST:PORT.
  4866. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4867. std::string *resp = nullptr) {
  4868. auto error = Error::Success;
  4869. auto client_sock = detail::create_client_socket(
  4870. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4871. /*connection_timeout_sec=*/5, 0,
  4872. /*read_timeout_sec=*/5, 0,
  4873. /*write_timeout_sec=*/5, 0, std::string(), error);
  4874. if (client_sock == INVALID_SOCKET) { return false; }
  4875. auto ret = detail::process_client_socket(
  4876. client_sock, read_timeout_sec, 0, 0, 0, 0,
  4877. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  4878. if (req.size() !=
  4879. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4880. return false;
  4881. }
  4882. char buf[512];
  4883. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4884. while (line_reader.getline()) {
  4885. if (resp) { *resp += line_reader.ptr(); }
  4886. }
  4887. return true;
  4888. });
  4889. detail::close_socket(client_sock);
  4890. return ret;
  4891. }
  4892. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4893. Server svr;
  4894. std::string header_value;
  4895. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4896. header_value = req.get_header_value("foo");
  4897. res.set_content("ok", "text/plain");
  4898. });
  4899. thread t = thread([&] { svr.listen(HOST, PORT); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. t.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4907. // like characters are not treated the same - use vertical tab and escape.
  4908. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4909. "foo: \t \v bar \x1B\t \r\n"
  4910. "Connection: close\r\n"
  4911. "\r\n";
  4912. std::string res;
  4913. ASSERT_TRUE(send_request(5, req, &res));
  4914. EXPECT_EQ(header_value, "");
  4915. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  4916. }
  4917. // Sends a raw request and verifies that there isn't a crash or exception.
  4918. static void test_raw_request(const std::string &req,
  4919. std::string *out = nullptr) {
  4920. Server svr;
  4921. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4922. res.set_content("ok", "text/plain");
  4923. });
  4924. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4925. res.set_content("ok", "text/plain");
  4926. });
  4927. svr.Get("/header_field_value_check",
  4928. [&](const Request & /*req*/, Response &res) {
  4929. res.set_content("ok", "text/plain");
  4930. });
  4931. // Server read timeout must be longer than the client read timeout for the
  4932. // bug to reproduce, probably to force the server to process a request
  4933. // without a trailing blank line.
  4934. const time_t client_read_timeout_sec = 1;
  4935. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4936. bool listen_thread_ok = false;
  4937. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4938. auto se = detail::scope_exit([&] {
  4939. svr.stop();
  4940. t.join();
  4941. ASSERT_FALSE(svr.is_running());
  4942. EXPECT_TRUE(listen_thread_ok);
  4943. });
  4944. svr.wait_until_ready();
  4945. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4946. }
  4947. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4948. // A certain header line causes an exception if the header property is parsed
  4949. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4950. test_raw_request(
  4951. "GET /hi HTTP/1.1\r\n"
  4952. " : "
  4953. " "
  4954. " ");
  4955. }
  4956. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4957. // A certain header line causes an exception if the header property *name* is
  4958. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4959. // greedy matcher and requires backtracking when there are a lot of ":"
  4960. // characters.
  4961. // This occurs with libc++ but not libstdc++.
  4962. test_raw_request(
  4963. "GET /hi HTTP/1.1\r\n"
  4964. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4965. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4966. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4967. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4968. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4969. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4970. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4971. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4972. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4973. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4974. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4975. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4976. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4977. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4978. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4979. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4980. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4981. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4982. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4983. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4984. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4985. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4986. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4987. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4988. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4989. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4990. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4991. "&&&%%%");
  4992. }
  4993. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4994. // Make sure this doesn't crash the server.
  4995. // In a previous version of the header line regex, the "\r" rendered the line
  4996. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4997. // a new position where the leading white space ended and the field value
  4998. // began.
  4999. // The crash occurs with libc++ but not libstdc++.
  5000. test_raw_request("GET /hi HTTP/1.1\r\n"
  5001. "a:" +
  5002. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5003. "\r\n"
  5004. "\r\n");
  5005. }
  5006. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5007. std::string out;
  5008. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5009. "Content-Type: text/plain\r\n"
  5010. "Transfer-Encoding: chunked\r\n"
  5011. "\r\n"
  5012. "nothex\r\n",
  5013. &out);
  5014. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5015. }
  5016. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5017. std::string out;
  5018. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5019. "Content-Type: text/plain\r\n"
  5020. "Transfer-Encoding: chunked\r\n"
  5021. "\r\n"
  5022. "3\r\n"
  5023. "xyz\r\n"
  5024. "NaN\r\n",
  5025. &out);
  5026. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5027. }
  5028. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5029. std::string out;
  5030. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5031. "Content-Type: text/plain\r\n"
  5032. "Transfer-Encoding: chunked\r\n"
  5033. "\r\n"
  5034. // Length is too large for 64 bits.
  5035. "1ffffffffffffffff\r\n"
  5036. "xyz\r\n",
  5037. &out);
  5038. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5039. }
  5040. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5041. test_raw_request("GET /hi HTTP/1.1\r\n"
  5042. "Content-Type: text/plain\r\n\r");
  5043. }
  5044. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5045. std::string out;
  5046. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5047. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5048. }
  5049. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5050. std::string out;
  5051. std::string request(
  5052. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5053. test_raw_request(request, &out);
  5054. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5055. }
  5056. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5057. std::string out;
  5058. std::string request(
  5059. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5060. test_raw_request(request, &out);
  5061. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5062. }
  5063. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5064. std::string out;
  5065. std::string request(
  5066. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5067. test_raw_request(request, &out);
  5068. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5069. }
  5070. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5071. std::string out;
  5072. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5073. "Test: \r\n\r\n",
  5074. &out);
  5075. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5076. }
  5077. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5078. Server svr;
  5079. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5080. res.set_header("Cache-Control", "no-cache");
  5081. res.set_chunked_content_provider(
  5082. "text/event-stream", [](size_t offset, DataSink &sink) {
  5083. std::string s = "data:";
  5084. s += std::to_string(offset);
  5085. s += "\n\n";
  5086. auto ret = sink.write(s.data(), s.size());
  5087. EXPECT_TRUE(ret);
  5088. std::this_thread::sleep_for(std::chrono::seconds(1));
  5089. return true;
  5090. });
  5091. });
  5092. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5093. svr.wait_until_ready();
  5094. Client client(HOST, PORT);
  5095. const Headers headers = {{"Accept", "text/event-stream"}};
  5096. auto get_thread = std::thread([&client, &headers]() {
  5097. auto res = client.Get(
  5098. "/events", headers,
  5099. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5100. });
  5101. auto se = detail::scope_exit([&] {
  5102. svr.stop();
  5103. get_thread.join();
  5104. listen_thread.join();
  5105. ASSERT_FALSE(svr.is_running());
  5106. });
  5107. // Give GET time to get a few messages.
  5108. std::this_thread::sleep_for(std::chrono::seconds(2));
  5109. }
  5110. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5111. httplib::Server svr;
  5112. svr.Post("/hi",
  5113. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5114. res.status = StatusCode::OK_200;
  5115. });
  5116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5117. svr.wait_until_ready();
  5118. Client cli(HOST, PORT);
  5119. auto res = cli.Post("/hi", "data", "text/plain");
  5120. ASSERT_TRUE(res);
  5121. EXPECT_EQ(StatusCode::OK_200, res->status);
  5122. svr.stop();
  5123. thread.join();
  5124. ASSERT_FALSE(svr.is_running());
  5125. res = cli.Post("/hi", "data", "text/plain");
  5126. ASSERT_FALSE(res);
  5127. }
  5128. TEST(ServerStopTest, ListenFailure) {
  5129. Server svr;
  5130. auto t = thread([&]() {
  5131. auto ret = svr.listen("????", PORT);
  5132. EXPECT_FALSE(ret);
  5133. });
  5134. svr.wait_until_ready();
  5135. svr.stop();
  5136. t.join();
  5137. }
  5138. TEST(ServerStopTest, Decommision) {
  5139. Server svr;
  5140. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5141. for (int i = 0; i < 4; i++) {
  5142. auto is_even = !(i % 2);
  5143. std::thread t{[&] {
  5144. try {
  5145. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5146. if (is_even) {
  5147. throw std::runtime_error("Some thing that happens to go wrong.");
  5148. }
  5149. svr.listen(HOST, PORT);
  5150. } catch (...) { svr.decommission(); }
  5151. }};
  5152. svr.wait_until_ready();
  5153. // Server is up
  5154. {
  5155. Client cli(HOST, PORT);
  5156. auto res = cli.Get("/hi");
  5157. if (is_even) {
  5158. EXPECT_FALSE(res);
  5159. } else {
  5160. EXPECT_TRUE(res);
  5161. EXPECT_EQ("hi...", res->body);
  5162. }
  5163. }
  5164. svr.stop();
  5165. t.join();
  5166. // Server is down...
  5167. {
  5168. Client cli(HOST, PORT);
  5169. auto res = cli.Get("/hi");
  5170. EXPECT_FALSE(res);
  5171. }
  5172. }
  5173. }
  5174. // Helper function for string body upload progress tests
  5175. template <typename SetupHandler, typename ClientCall>
  5176. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5177. ClientCall &&client_call,
  5178. const string &body) {
  5179. Server svr;
  5180. setup_handler(svr);
  5181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5182. auto se = detail::scope_exit([&] {
  5183. svr.stop();
  5184. t.join();
  5185. });
  5186. svr.wait_until_ready();
  5187. Client cli(HOST, PORT);
  5188. vector<uint64_t> progress_values;
  5189. bool progress_called = false;
  5190. auto res =
  5191. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5192. progress_values.push_back(current);
  5193. progress_called = true;
  5194. return true;
  5195. });
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(200, res->status);
  5198. EXPECT_TRUE(progress_called);
  5199. }
  5200. TEST(UploadProgressTest, PostStringBodyBasic) {
  5201. TestStringBodyUploadProgress(
  5202. [](Server &svr) {
  5203. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5204. res.set_content("received", "text/plain");
  5205. });
  5206. },
  5207. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5208. return cli.Post("/test", body, "text/plain", progress_callback);
  5209. },
  5210. "test data for upload progress");
  5211. }
  5212. TEST(UploadProgressTest, PutStringBodyBasic) {
  5213. TestStringBodyUploadProgress(
  5214. [](Server &svr) {
  5215. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5216. res.set_content("put received", "text/plain");
  5217. });
  5218. },
  5219. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5220. return cli.Put("/test", body, "text/plain", progress_callback);
  5221. },
  5222. "put test data for upload progress");
  5223. }
  5224. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5225. TestStringBodyUploadProgress(
  5226. [](Server &svr) {
  5227. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5228. res.set_content("patch received", "text/plain");
  5229. });
  5230. },
  5231. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5232. return cli.Patch("/test", body, "text/plain", progress_callback);
  5233. },
  5234. "patch test data for upload progress");
  5235. }
  5236. // Helper function for content provider upload progress tests
  5237. template <typename SetupHandler, typename ClientCall>
  5238. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5239. ClientCall &&client_call) {
  5240. Server svr;
  5241. setup_handler(svr);
  5242. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5243. auto se = detail::scope_exit([&] {
  5244. svr.stop();
  5245. t.join();
  5246. });
  5247. svr.wait_until_ready();
  5248. Client cli(HOST, PORT);
  5249. vector<uint64_t> progress_values;
  5250. auto res =
  5251. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5252. progress_values.push_back(current);
  5253. return true;
  5254. });
  5255. ASSERT_TRUE(res);
  5256. EXPECT_EQ(200, res->status);
  5257. EXPECT_FALSE(progress_values.empty());
  5258. }
  5259. TEST(UploadProgressTest, PostContentProviderProgress) {
  5260. TestContentProviderUploadProgress(
  5261. [](Server &svr) {
  5262. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5263. res.set_content("provider received", "text/plain");
  5264. });
  5265. },
  5266. [](Client &cli, UploadProgress progress_callback) {
  5267. return cli.Post(
  5268. "/test", 10,
  5269. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5270. sink.os << "test data";
  5271. return true;
  5272. },
  5273. "text/plain", progress_callback);
  5274. });
  5275. }
  5276. // Helper function for multipart upload progress tests
  5277. template <typename SetupHandler, typename ClientCall>
  5278. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5279. ClientCall &&client_call,
  5280. const string &endpoint) {
  5281. Server svr;
  5282. setup_handler(svr);
  5283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5284. auto se = detail::scope_exit([&] {
  5285. svr.stop();
  5286. t.join();
  5287. });
  5288. svr.wait_until_ready();
  5289. Client cli(HOST, PORT);
  5290. vector<uint64_t> progress_values;
  5291. MultipartFormDataItemsForClientInput items = {
  5292. {"field1", "value1", "", ""},
  5293. {"field2", "longer value for progress tracking test", "", ""},
  5294. {"file1", "file content data for upload progress", "test.txt",
  5295. "text/plain"}};
  5296. auto res = client_call(cli, endpoint, items,
  5297. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5298. progress_values.push_back(current);
  5299. return true;
  5300. });
  5301. ASSERT_TRUE(res);
  5302. EXPECT_EQ(200, res->status);
  5303. EXPECT_FALSE(progress_values.empty());
  5304. }
  5305. TEST(UploadProgressTest, PostMultipartProgress) {
  5306. TestMultipartUploadProgress(
  5307. [](Server &svr) {
  5308. svr.Post("/multipart", [](const Request &req, Response &res) {
  5309. EXPECT_FALSE(req.files.empty());
  5310. res.set_content("multipart received", "text/plain");
  5311. });
  5312. },
  5313. [](Client &cli, const string &endpoint,
  5314. const MultipartFormDataItemsForClientInput &items,
  5315. UploadProgress progress_callback) {
  5316. return cli.Post(endpoint, items, progress_callback);
  5317. },
  5318. "/multipart");
  5319. }
  5320. // Helper function for basic download progress tests
  5321. template <typename SetupHandler, typename ClientCall>
  5322. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5323. ClientCall &&client_call, const string &endpoint,
  5324. size_t expected_content_size) {
  5325. Server svr;
  5326. setup_handler(svr);
  5327. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5328. auto se = detail::scope_exit([&] {
  5329. svr.stop();
  5330. t.join();
  5331. });
  5332. svr.wait_until_ready();
  5333. Client cli(HOST, PORT);
  5334. vector<uint64_t> progress_values;
  5335. auto res = client_call(cli, endpoint,
  5336. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5337. progress_values.push_back(current);
  5338. return true;
  5339. });
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(200, res->status);
  5342. EXPECT_FALSE(progress_values.empty());
  5343. EXPECT_EQ(expected_content_size, res->body.size());
  5344. }
  5345. TEST(DownloadProgressTest, GetBasic) {
  5346. TestBasicDownloadProgress(
  5347. [](Server &svr) {
  5348. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5349. string content(1000, 'D');
  5350. res.set_content(content, "text/plain");
  5351. });
  5352. },
  5353. [](Client &cli, const string &endpoint,
  5354. DownloadProgress progress_callback) {
  5355. return cli.Get(endpoint, progress_callback);
  5356. },
  5357. "/download", 1000u);
  5358. }
  5359. // Helper function for content receiver download progress tests
  5360. template <typename SetupHandler, typename ClientCall>
  5361. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5362. ClientCall &&client_call,
  5363. const string &endpoint,
  5364. size_t expected_content_size) {
  5365. Server svr;
  5366. setup_handler(svr);
  5367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5368. auto se = detail::scope_exit([&] {
  5369. svr.stop();
  5370. t.join();
  5371. });
  5372. svr.wait_until_ready();
  5373. Client cli(HOST, PORT);
  5374. vector<uint64_t> progress_values;
  5375. string received_body;
  5376. auto res = client_call(
  5377. cli, endpoint,
  5378. [&](const char *data, size_t data_length) -> bool {
  5379. received_body.append(data, data_length);
  5380. return true;
  5381. },
  5382. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5383. progress_values.push_back(current);
  5384. return true;
  5385. });
  5386. ASSERT_TRUE(res);
  5387. EXPECT_EQ(200, res->status);
  5388. EXPECT_FALSE(progress_values.empty());
  5389. EXPECT_EQ(expected_content_size, received_body.size());
  5390. EXPECT_TRUE(res->body.empty());
  5391. }
  5392. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5393. TestContentReceiverDownloadProgress(
  5394. [](Server &svr) {
  5395. svr.Get("/download-receiver",
  5396. [](const Request & /*req*/, Response &res) {
  5397. string content(2000, 'R');
  5398. res.set_content(content, "text/plain");
  5399. });
  5400. },
  5401. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5402. DownloadProgress progress_callback) {
  5403. return cli.Get(endpoint, content_receiver, progress_callback);
  5404. },
  5405. "/download-receiver", 2000u);
  5406. }
  5407. TEST(StreamingTest, NoContentLengthStreaming) {
  5408. Server svr;
  5409. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5410. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5411. if (offset < 6) {
  5412. sink.os << (offset < 3 ? "a" : "b");
  5413. } else {
  5414. sink.done();
  5415. }
  5416. return true;
  5417. });
  5418. });
  5419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5420. auto listen_se = detail::scope_exit([&] {
  5421. svr.stop();
  5422. listen_thread.join();
  5423. ASSERT_FALSE(svr.is_running());
  5424. });
  5425. svr.wait_until_ready();
  5426. Client client(HOST, PORT);
  5427. auto get_thread = std::thread([&client]() {
  5428. std::string s;
  5429. auto res =
  5430. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5431. s += std::string(data, len);
  5432. return true;
  5433. });
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("aaabbb", s);
  5437. });
  5438. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5439. // Give GET time to get a few messages.
  5440. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5441. }
  5442. TEST(MountTest, Unmount) {
  5443. Server svr;
  5444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5445. auto se = detail::scope_exit([&] {
  5446. svr.stop();
  5447. listen_thread.join();
  5448. ASSERT_FALSE(svr.is_running());
  5449. });
  5450. svr.wait_until_ready();
  5451. Client cli("localhost", PORT);
  5452. svr.set_mount_point("/mount2", "./www2");
  5453. auto res = cli.Get("/");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5456. res = cli.Get("/mount2/dir/test.html");
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ(StatusCode::OK_200, res->status);
  5459. svr.set_mount_point("/", "./www");
  5460. res = cli.Get("/dir/");
  5461. ASSERT_TRUE(res);
  5462. EXPECT_EQ(StatusCode::OK_200, res->status);
  5463. svr.remove_mount_point("/");
  5464. res = cli.Get("/dir/");
  5465. ASSERT_TRUE(res);
  5466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5467. svr.remove_mount_point("/mount2");
  5468. res = cli.Get("/mount2/dir/test.html");
  5469. ASSERT_TRUE(res);
  5470. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5471. }
  5472. TEST(MountTest, Redicect) {
  5473. Server svr;
  5474. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5475. auto se = detail::scope_exit([&] {
  5476. svr.stop();
  5477. listen_thread.join();
  5478. ASSERT_FALSE(svr.is_running());
  5479. });
  5480. svr.set_mount_point("/", "./www");
  5481. svr.wait_until_ready();
  5482. Client cli("localhost", PORT);
  5483. auto res = cli.Get("/dir/");
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. res = cli.Get("/dir");
  5487. ASSERT_TRUE(res);
  5488. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5489. res = cli.Get("/file");
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(StatusCode::OK_200, res->status);
  5492. res = cli.Get("/file/");
  5493. ASSERT_TRUE(res);
  5494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5495. cli.set_follow_location(true);
  5496. res = cli.Get("/dir");
  5497. ASSERT_TRUE(res);
  5498. EXPECT_EQ(StatusCode::OK_200, res->status);
  5499. }
  5500. TEST(MountTest, MultibytesPathName) {
  5501. Server svr;
  5502. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5503. auto se = detail::scope_exit([&] {
  5504. svr.stop();
  5505. listen_thread.join();
  5506. ASSERT_FALSE(svr.is_running());
  5507. });
  5508. svr.set_mount_point("/", "./www");
  5509. svr.wait_until_ready();
  5510. Client cli("localhost", PORT);
  5511. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5512. ASSERT_TRUE(res);
  5513. EXPECT_EQ(StatusCode::OK_200, res->status);
  5514. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5515. }
  5516. TEST(KeepAliveTest, ReadTimeout) {
  5517. Server svr;
  5518. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5519. std::this_thread::sleep_for(std::chrono::seconds(2));
  5520. res.set_content("a", "text/plain");
  5521. });
  5522. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5523. res.set_content("b", "text/plain");
  5524. });
  5525. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5526. auto se = detail::scope_exit([&] {
  5527. svr.stop();
  5528. listen_thread.join();
  5529. ASSERT_FALSE(svr.is_running());
  5530. });
  5531. svr.wait_until_ready();
  5532. Client cli("localhost", PORT);
  5533. cli.set_keep_alive(true);
  5534. cli.set_read_timeout(std::chrono::seconds(1));
  5535. auto resa = cli.Get("/a");
  5536. ASSERT_FALSE(resa);
  5537. EXPECT_EQ(Error::Read, resa.error());
  5538. auto resb = cli.Get("/b");
  5539. ASSERT_TRUE(resb);
  5540. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5541. EXPECT_EQ("b", resb->body);
  5542. }
  5543. TEST(KeepAliveTest, MaxCount) {
  5544. size_t keep_alive_max_count = 3;
  5545. Server svr;
  5546. svr.set_keep_alive_max_count(keep_alive_max_count);
  5547. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5548. res.set_content("Hello World!", "text/plain");
  5549. });
  5550. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5551. auto se = detail::scope_exit([&] {
  5552. svr.stop();
  5553. listen_thread.join();
  5554. ASSERT_FALSE(svr.is_running());
  5555. });
  5556. svr.wait_until_ready();
  5557. Client cli(HOST, PORT);
  5558. cli.set_keep_alive(true);
  5559. for (size_t i = 0; i < 5; i++) {
  5560. auto result = cli.Get("/hi");
  5561. ASSERT_TRUE(result);
  5562. EXPECT_EQ(StatusCode::OK_200, result->status);
  5563. if (i == keep_alive_max_count - 1) {
  5564. EXPECT_EQ("close", result->get_header_value("Connection"));
  5565. } else {
  5566. EXPECT_FALSE(result->has_header("Connection"));
  5567. }
  5568. }
  5569. }
  5570. TEST(KeepAliveTest, Issue1041) {
  5571. Server svr;
  5572. svr.set_keep_alive_timeout(3);
  5573. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5574. res.set_content("Hello World!", "text/plain");
  5575. });
  5576. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5577. auto se = detail::scope_exit([&] {
  5578. svr.stop();
  5579. listen_thread.join();
  5580. ASSERT_FALSE(svr.is_running());
  5581. });
  5582. svr.wait_until_ready();
  5583. Client cli(HOST, PORT);
  5584. cli.set_keep_alive(true);
  5585. auto result = cli.Get("/hi");
  5586. ASSERT_TRUE(result);
  5587. EXPECT_EQ(StatusCode::OK_200, result->status);
  5588. std::this_thread::sleep_for(std::chrono::seconds(5));
  5589. result = cli.Get("/hi");
  5590. ASSERT_TRUE(result);
  5591. EXPECT_EQ(StatusCode::OK_200, result->status);
  5592. }
  5593. TEST(KeepAliveTest, Issue1959) {
  5594. Server svr;
  5595. svr.set_keep_alive_timeout(5);
  5596. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5597. res.set_content("a", "text/plain");
  5598. });
  5599. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5600. auto se = detail::scope_exit([&] {
  5601. if (!svr.is_running()) return;
  5602. svr.stop();
  5603. listen_thread.join();
  5604. ASSERT_FALSE(svr.is_running());
  5605. });
  5606. svr.wait_until_ready();
  5607. Client cli("localhost", PORT);
  5608. cli.set_keep_alive(true);
  5609. using namespace std::chrono;
  5610. auto start = steady_clock::now();
  5611. cli.Get("/a");
  5612. svr.stop();
  5613. listen_thread.join();
  5614. auto end = steady_clock::now();
  5615. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5616. EXPECT_LT(elapsed, 5000);
  5617. }
  5618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5619. TEST(KeepAliveTest, SSLClientReconnection) {
  5620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5621. ASSERT_TRUE(svr.is_valid());
  5622. svr.set_keep_alive_timeout(1);
  5623. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5624. res.set_content("Hello World!", "text/plain");
  5625. });
  5626. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5627. auto se = detail::scope_exit([&] {
  5628. svr.stop();
  5629. listen_thread.join();
  5630. ASSERT_FALSE(svr.is_running());
  5631. });
  5632. svr.wait_until_ready();
  5633. SSLClient cli(HOST, PORT);
  5634. cli.enable_server_certificate_verification(false);
  5635. cli.set_keep_alive(true);
  5636. auto result = cli.Get("/hi");
  5637. ASSERT_TRUE(result);
  5638. EXPECT_EQ(StatusCode::OK_200, result->status);
  5639. result = cli.Get("/hi");
  5640. ASSERT_TRUE(result);
  5641. EXPECT_EQ(StatusCode::OK_200, result->status);
  5642. std::this_thread::sleep_for(std::chrono::seconds(2));
  5643. // Recoonect
  5644. result = cli.Get("/hi");
  5645. ASSERT_TRUE(result);
  5646. EXPECT_EQ(StatusCode::OK_200, result->status);
  5647. result = cli.Get("/hi");
  5648. ASSERT_TRUE(result);
  5649. EXPECT_EQ(StatusCode::OK_200, result->status);
  5650. }
  5651. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5653. ASSERT_TRUE(svr.is_valid());
  5654. svr.set_keep_alive_timeout(1);
  5655. std::string content = "reconnect";
  5656. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5657. res.set_content("Hello World!", "text/plain");
  5658. });
  5659. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5660. auto se = detail::scope_exit([&] {
  5661. svr.stop();
  5662. listen_thread.join();
  5663. ASSERT_FALSE(svr.is_running());
  5664. });
  5665. svr.wait_until_ready();
  5666. SSLClient cli(HOST, PORT);
  5667. cli.enable_server_certificate_verification(false);
  5668. cli.set_keep_alive(true);
  5669. auto result = cli.Post(
  5670. "/hi", content.size(),
  5671. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5672. sink.write(content.c_str(), content.size());
  5673. return true;
  5674. },
  5675. "text/plain");
  5676. ASSERT_TRUE(result);
  5677. EXPECT_EQ(200, result->status);
  5678. std::this_thread::sleep_for(std::chrono::seconds(2));
  5679. // Recoonect
  5680. result = cli.Post(
  5681. "/hi", content.size(),
  5682. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5683. sink.write(content.c_str(), content.size());
  5684. return true;
  5685. },
  5686. "text/plain");
  5687. ASSERT_TRUE(result);
  5688. EXPECT_EQ(200, result->status);
  5689. result = cli.Post(
  5690. "/hi", content.size(),
  5691. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5692. sink.write(content.c_str(), content.size());
  5693. return true;
  5694. },
  5695. "text/plain");
  5696. ASSERT_TRUE(result);
  5697. EXPECT_EQ(200, result->status);
  5698. }
  5699. #endif
  5700. TEST(ClientProblemDetectionTest, ContentProvider) {
  5701. Server svr;
  5702. size_t content_length = 1024 * 1024;
  5703. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5704. res.set_content_provider(
  5705. content_length, "text/plain",
  5706. [&](size_t offset, size_t length, DataSink &sink) {
  5707. auto out_len = std::min(length, static_cast<size_t>(1024));
  5708. std::string out(out_len, '@');
  5709. sink.write(out.data(), out_len);
  5710. return offset < 4096;
  5711. },
  5712. [](bool success) { ASSERT_FALSE(success); });
  5713. });
  5714. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5715. res.set_content_provider(
  5716. 0, "text/plain",
  5717. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5718. EXPECT_TRUE(false);
  5719. return true;
  5720. },
  5721. [](bool success) { ASSERT_FALSE(success); });
  5722. });
  5723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5724. auto se = detail::scope_exit([&] {
  5725. svr.stop();
  5726. listen_thread.join();
  5727. ASSERT_FALSE(svr.is_running());
  5728. });
  5729. svr.wait_until_ready();
  5730. Client cli("localhost", PORT);
  5731. {
  5732. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5733. size_t /*data_length*/) { return false; });
  5734. ASSERT_FALSE(res);
  5735. }
  5736. {
  5737. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5738. size_t /*data_length*/) { return false; });
  5739. ASSERT_TRUE(res);
  5740. }
  5741. }
  5742. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5743. Server svr;
  5744. svr.set_error_handler([](Request const &, Response &res) -> void {
  5745. res.set_chunked_content_provider(
  5746. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5747. sink.os << "hello";
  5748. sink.os << "world";
  5749. sink.done();
  5750. return true;
  5751. });
  5752. });
  5753. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5754. auto se = detail::scope_exit([&] {
  5755. svr.stop();
  5756. listen_thread.join();
  5757. ASSERT_FALSE(svr.is_running());
  5758. });
  5759. svr.wait_until_ready();
  5760. Client cli("localhost", PORT);
  5761. auto res = cli.Get("/");
  5762. ASSERT_TRUE(res);
  5763. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5764. EXPECT_EQ("helloworld", res->body);
  5765. }
  5766. TEST(LongPollingTest, ClientCloseDetection) {
  5767. Server svr;
  5768. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5769. res.set_chunked_content_provider(
  5770. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5771. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5772. sink.os << "hello";
  5773. auto count = 10;
  5774. while (count > 0 && sink.is_writable()) {
  5775. this_thread::sleep_for(chrono::milliseconds(10));
  5776. count--;
  5777. }
  5778. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5779. return true;
  5780. });
  5781. });
  5782. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5783. auto se = detail::scope_exit([&] {
  5784. svr.stop();
  5785. listen_thread.join();
  5786. ASSERT_FALSE(svr.is_running());
  5787. });
  5788. svr.wait_until_ready();
  5789. Client cli("localhost", PORT);
  5790. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  5791. EXPECT_EQ("hello", string(data, data_length));
  5792. return false; // close the socket immediately.
  5793. });
  5794. ASSERT_FALSE(res);
  5795. }
  5796. TEST(GetWithParametersTest, GetWithParameters) {
  5797. Server svr;
  5798. svr.Get("/", [&](const Request &req, Response &) {
  5799. EXPECT_EQ("world", req.get_param_value("hello"));
  5800. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5801. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5802. });
  5803. svr.Get("/params", [&](const Request &req, Response &) {
  5804. EXPECT_EQ("world", req.get_param_value("hello"));
  5805. EXPECT_EQ("world2", req.get_param_value("hello2"));
  5806. EXPECT_EQ("world3", req.get_param_value("hello3"));
  5807. });
  5808. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  5809. EXPECT_EQ("resource-id", req.matches[1]);
  5810. EXPECT_EQ("foo", req.get_param_value("param1"));
  5811. EXPECT_EQ("bar", req.get_param_value("param2"));
  5812. });
  5813. svr.Get("/users/:id", [&](const Request &req, Response &) {
  5814. EXPECT_EQ("user-id", req.path_params.at("id"));
  5815. EXPECT_EQ("foo", req.get_param_value("param1"));
  5816. EXPECT_EQ("bar", req.get_param_value("param2"));
  5817. });
  5818. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5819. auto se = detail::scope_exit([&] {
  5820. svr.stop();
  5821. listen_thread.join();
  5822. ASSERT_FALSE(svr.is_running());
  5823. });
  5824. svr.wait_until_ready();
  5825. {
  5826. Client cli(HOST, PORT);
  5827. Params params;
  5828. params.emplace("hello", "world");
  5829. params.emplace("hello2", "world2");
  5830. params.emplace("hello3", "world3");
  5831. auto res = cli.Get("/", params, Headers{});
  5832. ASSERT_TRUE(res);
  5833. EXPECT_EQ(StatusCode::OK_200, res->status);
  5834. }
  5835. {
  5836. Client cli(HOST, PORT);
  5837. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  5838. ASSERT_TRUE(res);
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. }
  5841. {
  5842. Client cli(HOST, PORT);
  5843. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  5844. ASSERT_TRUE(res);
  5845. EXPECT_EQ(StatusCode::OK_200, res->status);
  5846. }
  5847. {
  5848. Client cli(HOST, PORT);
  5849. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  5850. ASSERT_TRUE(res);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. }
  5853. }
  5854. TEST(GetWithParametersTest, GetWithParameters2) {
  5855. Server svr;
  5856. svr.Get("/", [&](const Request &req, Response &res) {
  5857. auto text = req.get_param_value("hello");
  5858. res.set_content(text, "text/plain");
  5859. });
  5860. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5861. auto se = detail::scope_exit([&] {
  5862. svr.stop();
  5863. listen_thread.join();
  5864. ASSERT_FALSE(svr.is_running());
  5865. });
  5866. svr.wait_until_ready();
  5867. Client cli("localhost", PORT);
  5868. Params params;
  5869. params.emplace("hello", "world");
  5870. std::string body;
  5871. auto res = cli.Get("/", params, Headers{},
  5872. [&](const char *data, size_t data_length) {
  5873. body.append(data, data_length);
  5874. return true;
  5875. });
  5876. ASSERT_TRUE(res);
  5877. EXPECT_EQ(StatusCode::OK_200, res->status);
  5878. EXPECT_EQ("world", body);
  5879. }
  5880. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  5881. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  5882. auto host = "httpbin.org";
  5883. auto path = std::string{"/range/32"};
  5884. #else
  5885. auto host = "nghttp2.org";
  5886. auto path = std::string{"/httpbin/range/32"};
  5887. #endif
  5888. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5889. SSLClient cli(host);
  5890. #else
  5891. Client cli(host);
  5892. #endif
  5893. cli.set_default_headers({make_range_header({{1, 10}})});
  5894. cli.set_connection_timeout(5);
  5895. {
  5896. auto res = cli.Get(path);
  5897. ASSERT_TRUE(res);
  5898. EXPECT_EQ("bcdefghijk", res->body);
  5899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5900. }
  5901. {
  5902. auto res = cli.Get(path);
  5903. ASSERT_TRUE(res);
  5904. EXPECT_EQ("bcdefghijk", res->body);
  5905. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5906. }
  5907. }
  5908. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  5909. Server svr;
  5910. svr.set_default_headers({{"Hello", "World"}});
  5911. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  5912. res.set_content("ok", "text/plain");
  5913. });
  5914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5915. auto se = detail::scope_exit([&] {
  5916. svr.stop();
  5917. listen_thread.join();
  5918. ASSERT_FALSE(svr.is_running());
  5919. });
  5920. svr.wait_until_ready();
  5921. Client cli("localhost", PORT);
  5922. auto res = cli.Get("/");
  5923. ASSERT_TRUE(res);
  5924. EXPECT_EQ(StatusCode::OK_200, res->status);
  5925. EXPECT_EQ("ok", res->body);
  5926. EXPECT_EQ("World", res->get_header_value("Hello"));
  5927. }
  5928. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5929. TEST(KeepAliveTest, ReadTimeoutSSL) {
  5930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5931. ASSERT_TRUE(svr.is_valid());
  5932. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5933. std::this_thread::sleep_for(std::chrono::seconds(2));
  5934. res.set_content("a", "text/plain");
  5935. });
  5936. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5937. res.set_content("b", "text/plain");
  5938. });
  5939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5940. auto se = detail::scope_exit([&] {
  5941. svr.stop();
  5942. listen_thread.join();
  5943. ASSERT_FALSE(svr.is_running());
  5944. });
  5945. svr.wait_until_ready();
  5946. SSLClient cli("localhost", PORT);
  5947. cli.enable_server_certificate_verification(false);
  5948. cli.set_keep_alive(true);
  5949. cli.set_read_timeout(std::chrono::seconds(1));
  5950. auto resa = cli.Get("/a");
  5951. ASSERT_TRUE(!resa);
  5952. EXPECT_EQ(Error::Read, resa.error());
  5953. auto resb = cli.Get("/b");
  5954. ASSERT_TRUE(resb);
  5955. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5956. EXPECT_EQ("b", resb->body);
  5957. }
  5958. #endif
  5959. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  5960. protected:
  5961. ServerTestWithAI_PASSIVE()
  5962. : cli_(HOST, PORT)
  5963. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5964. ,
  5965. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5966. #endif
  5967. {
  5968. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5969. cli_.enable_server_certificate_verification(false);
  5970. #endif
  5971. }
  5972. virtual void SetUp() {
  5973. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5974. res.set_content("Hello World!", "text/plain");
  5975. });
  5976. t_ = thread(
  5977. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  5978. svr_.wait_until_ready();
  5979. }
  5980. virtual void TearDown() {
  5981. svr_.stop();
  5982. t_.join();
  5983. }
  5984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5985. SSLClient cli_;
  5986. SSLServer svr_;
  5987. #else
  5988. Client cli_;
  5989. Server svr_;
  5990. #endif
  5991. thread t_;
  5992. };
  5993. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  5994. auto res = cli_.Get("/hi");
  5995. ASSERT_TRUE(res);
  5996. EXPECT_EQ(StatusCode::OK_200, res->status);
  5997. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5998. EXPECT_EQ("Hello World!", res->body);
  5999. }
  6000. class ServerUpDownTest : public ::testing::Test {
  6001. protected:
  6002. ServerUpDownTest() : cli_(HOST, PORT) {}
  6003. virtual void SetUp() {
  6004. t_ = thread([&]() {
  6005. svr_.bind_to_any_port(HOST);
  6006. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6007. ASSERT_TRUE(svr_.listen_after_bind());
  6008. });
  6009. svr_.wait_until_ready();
  6010. }
  6011. virtual void TearDown() {
  6012. svr_.stop();
  6013. t_.join();
  6014. }
  6015. Client cli_;
  6016. Server svr_;
  6017. thread t_;
  6018. };
  6019. TEST_F(ServerUpDownTest, QuickStartStop) {
  6020. // Should not crash, especially when run with
  6021. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6022. }
  6023. class PayloadMaxLengthTest : public ::testing::Test {
  6024. protected:
  6025. PayloadMaxLengthTest()
  6026. : cli_(HOST, PORT)
  6027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6028. ,
  6029. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6030. #endif
  6031. {
  6032. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6033. cli_.enable_server_certificate_verification(false);
  6034. #endif
  6035. }
  6036. virtual void SetUp() {
  6037. svr_.set_payload_max_length(8);
  6038. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6039. res.set_content("test", "text/plain");
  6040. });
  6041. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6042. svr_.wait_until_ready();
  6043. }
  6044. virtual void TearDown() {
  6045. svr_.stop();
  6046. t_.join();
  6047. }
  6048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6049. SSLClient cli_;
  6050. SSLServer svr_;
  6051. #else
  6052. Client cli_;
  6053. Server svr_;
  6054. #endif
  6055. thread t_;
  6056. };
  6057. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6058. auto res = cli_.Post("/test", "123456789", "text/plain");
  6059. ASSERT_TRUE(res);
  6060. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6061. res = cli_.Post("/test", "12345678", "text/plain");
  6062. ASSERT_TRUE(res);
  6063. EXPECT_EQ(StatusCode::OK_200, res->status);
  6064. }
  6065. TEST(HostAndPortPropertiesTest, NoSSL) {
  6066. httplib::Client cli("www.google.com", 1234);
  6067. ASSERT_EQ("www.google.com", cli.host());
  6068. ASSERT_EQ(1234, cli.port());
  6069. }
  6070. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6071. httplib::Client cli("www.google.com:1234");
  6072. ASSERT_EQ("www.google.com", cli.host());
  6073. ASSERT_EQ(1234, cli.port());
  6074. }
  6075. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6076. TEST(HostAndPortPropertiesTest, SSL) {
  6077. httplib::SSLClient cli("www.google.com");
  6078. ASSERT_EQ("www.google.com", cli.host());
  6079. ASSERT_EQ(443, cli.port());
  6080. }
  6081. #endif
  6082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6083. TEST(SSLClientTest, UpdateCAStore) {
  6084. httplib::SSLClient httplib_client("www.google.com");
  6085. auto ca_store_1 = X509_STORE_new();
  6086. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6087. nullptr);
  6088. httplib_client.set_ca_cert_store(ca_store_1);
  6089. auto ca_store_2 = X509_STORE_new();
  6090. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6091. nullptr);
  6092. httplib_client.set_ca_cert_store(ca_store_2);
  6093. }
  6094. TEST(SSLClientTest, ServerNameIndication_Online) {
  6095. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6096. auto host = "httpbin.org";
  6097. auto path = std::string{"/get"};
  6098. #else
  6099. auto host = "nghttp2.org";
  6100. auto path = std::string{"/httpbin/get"};
  6101. #endif
  6102. SSLClient cli(host, 443);
  6103. auto res = cli.Get(path);
  6104. ASSERT_TRUE(res);
  6105. ASSERT_EQ(StatusCode::OK_200, res->status);
  6106. }
  6107. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6108. Client cli("https://google.com");
  6109. auto res = cli.Get("/");
  6110. ASSERT_TRUE(res);
  6111. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6112. }
  6113. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6114. SSLClient cli("google.com");
  6115. cli.enable_server_certificate_verification(true);
  6116. cli.set_ca_cert_path("hello");
  6117. auto res = cli.Get("/");
  6118. ASSERT_TRUE(!res);
  6119. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6120. }
  6121. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6122. SSLClient cli("google.com");
  6123. cli.set_ca_cert_path(CA_CERT_FILE);
  6124. auto res = cli.Get("/");
  6125. ASSERT_TRUE(res);
  6126. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6127. }
  6128. TEST(SSLClientTest, ServerCertificateVerification4) {
  6129. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6130. ASSERT_TRUE(svr.is_valid());
  6131. svr.Get("/test", [&](const Request &, Response &res) {
  6132. res.set_content("test", "text/plain");
  6133. svr.stop();
  6134. ASSERT_TRUE(true);
  6135. });
  6136. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6137. auto se = detail::scope_exit([&] {
  6138. t.join();
  6139. ASSERT_FALSE(svr.is_running());
  6140. });
  6141. svr.wait_until_ready();
  6142. SSLClient cli("127.0.0.1", PORT);
  6143. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6144. cli.enable_server_certificate_verification(true);
  6145. cli.set_connection_timeout(30);
  6146. auto res = cli.Get("/test");
  6147. ASSERT_TRUE(res);
  6148. ASSERT_EQ(StatusCode::OK_200, res->status);
  6149. }
  6150. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6151. std::string cert;
  6152. read_file(CA_CERT_FILE, cert);
  6153. SSLClient cli("google.com");
  6154. cli.load_ca_cert_store(cert.data(), cert.size());
  6155. const auto res = cli.Get("/");
  6156. ASSERT_TRUE(res);
  6157. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6158. }
  6159. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6160. // clang-format off
  6161. static constexpr char cert[] =
  6162. "GlobalSign Root CA\n"
  6163. "==================\n"
  6164. "-----BEGIN CERTIFICATE-----\n"
  6165. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6166. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6167. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6168. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6169. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6170. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6171. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6172. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6173. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6174. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6175. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6176. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6177. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6178. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6179. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6180. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6181. "-----END CERTIFICATE-----\n";
  6182. // clang-format on
  6183. SSLClient cli("google.com");
  6184. cli.load_ca_cert_store(cert, sizeof(cert));
  6185. const auto res = cli.Get("/");
  6186. ASSERT_TRUE(res);
  6187. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6188. }
  6189. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6190. SSLClient cli("www.youtube.com");
  6191. cli.set_ca_cert_path(CA_CERT_FILE);
  6192. cli.enable_server_certificate_verification(true);
  6193. cli.set_follow_location(true);
  6194. auto res = cli.Get("/");
  6195. ASSERT_TRUE(res);
  6196. ASSERT_EQ(StatusCode::OK_200, res->status);
  6197. }
  6198. TEST(SSLClientTest, Issue2004_Online) {
  6199. Client client("https://google.com");
  6200. client.set_follow_location(true);
  6201. auto res = client.Get("/");
  6202. ASSERT_TRUE(res);
  6203. ASSERT_EQ(StatusCode::OK_200, res->status);
  6204. auto body = res->body;
  6205. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6206. }
  6207. #if 0
  6208. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6209. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6210. ASSERT_TRUE(cli != nullptr);
  6211. cli->set_address_family(AF_INET6);
  6212. cli->set_interface("en0");
  6213. auto res = cli->Get("/get");
  6214. ASSERT_TRUE(res);
  6215. ASSERT_EQ(StatusCode::OK_200, res->status);
  6216. }
  6217. #endif
  6218. void ClientCertPresent(
  6219. const std::string &client_cert_file,
  6220. const std::string &client_private_key_file,
  6221. const std::string &client_encrypted_private_key_pass = std::string()) {
  6222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6223. CLIENT_CA_CERT_DIR);
  6224. ASSERT_TRUE(svr.is_valid());
  6225. svr.Get("/test", [&](const Request &req, Response &res) {
  6226. res.set_content("test", "text/plain");
  6227. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6228. ASSERT_TRUE(peer_cert != nullptr);
  6229. auto subject_name = X509_get_subject_name(peer_cert);
  6230. ASSERT_TRUE(subject_name != nullptr);
  6231. std::string common_name;
  6232. {
  6233. char name[BUFSIZ];
  6234. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6235. name, sizeof(name));
  6236. common_name.assign(name, static_cast<size_t>(name_len));
  6237. }
  6238. EXPECT_EQ("Common Name", common_name);
  6239. X509_free(peer_cert);
  6240. });
  6241. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6242. auto se = detail::scope_exit([&] {
  6243. svr.stop();
  6244. t.join();
  6245. ASSERT_FALSE(svr.is_running());
  6246. });
  6247. svr.wait_until_ready();
  6248. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6249. client_encrypted_private_key_pass);
  6250. cli.enable_server_certificate_verification(false);
  6251. cli.set_connection_timeout(30);
  6252. auto res = cli.Get("/test");
  6253. ASSERT_TRUE(res);
  6254. ASSERT_EQ(StatusCode::OK_200, res->status);
  6255. }
  6256. TEST(SSLClientServerTest, ClientCertPresent) {
  6257. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6258. }
  6259. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6260. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6261. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6262. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6263. }
  6264. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6265. void MemoryClientCertPresent(
  6266. const std::string &client_cert_file,
  6267. const std::string &client_private_key_file,
  6268. const std::string &client_encrypted_private_key_pass = std::string()) {
  6269. auto f = fopen(SERVER_CERT_FILE, "r+");
  6270. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6271. fclose(f);
  6272. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6273. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6274. fclose(f);
  6275. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6276. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6277. auto client_ca_cert_store = X509_STORE_new();
  6278. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6279. X509_free(client_cert);
  6280. fclose(f);
  6281. f = fopen(client_cert_file.c_str(), "r+");
  6282. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6283. fclose(f);
  6284. f = fopen(client_private_key_file.c_str(), "r+");
  6285. auto client_private_key = PEM_read_PrivateKey(
  6286. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6287. fclose(f);
  6288. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6289. ASSERT_TRUE(svr.is_valid());
  6290. svr.Get("/test", [&](const Request &req, Response &res) {
  6291. res.set_content("test", "text/plain");
  6292. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6293. ASSERT_TRUE(peer_cert != nullptr);
  6294. auto subject_name = X509_get_subject_name(peer_cert);
  6295. ASSERT_TRUE(subject_name != nullptr);
  6296. std::string common_name;
  6297. {
  6298. char name[BUFSIZ];
  6299. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6300. name, sizeof(name));
  6301. common_name.assign(name, static_cast<size_t>(name_len));
  6302. }
  6303. EXPECT_EQ("Common Name", common_name);
  6304. X509_free(peer_cert);
  6305. });
  6306. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6307. auto se = detail::scope_exit([&] {
  6308. svr.stop();
  6309. t.join();
  6310. ASSERT_FALSE(svr.is_running());
  6311. });
  6312. svr.wait_until_ready();
  6313. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6314. client_encrypted_private_key_pass);
  6315. cli.enable_server_certificate_verification(false);
  6316. cli.set_connection_timeout(30);
  6317. auto res = cli.Get("/test");
  6318. ASSERT_TRUE(res);
  6319. ASSERT_EQ(StatusCode::OK_200, res->status);
  6320. X509_free(server_cert);
  6321. EVP_PKEY_free(server_private_key);
  6322. X509_free(client_cert);
  6323. EVP_PKEY_free(client_private_key);
  6324. }
  6325. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6326. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6327. }
  6328. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6329. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6330. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6331. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6332. }
  6333. #endif
  6334. TEST(SSLClientServerTest, ClientCertMissing) {
  6335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6336. CLIENT_CA_CERT_DIR);
  6337. ASSERT_TRUE(svr.is_valid());
  6338. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6339. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6340. auto se = detail::scope_exit([&] {
  6341. svr.stop();
  6342. t.join();
  6343. ASSERT_FALSE(svr.is_running());
  6344. });
  6345. svr.wait_until_ready();
  6346. SSLClient cli(HOST, PORT);
  6347. auto res = cli.Get("/test");
  6348. cli.set_connection_timeout(30);
  6349. ASSERT_TRUE(!res);
  6350. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6351. }
  6352. TEST(SSLClientServerTest, TrustDirOptional) {
  6353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6354. ASSERT_TRUE(svr.is_valid());
  6355. svr.Get("/test", [&](const Request &, Response &res) {
  6356. res.set_content("test", "text/plain");
  6357. });
  6358. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6359. auto se = detail::scope_exit([&] {
  6360. svr.stop();
  6361. t.join();
  6362. ASSERT_FALSE(svr.is_running());
  6363. });
  6364. svr.wait_until_ready();
  6365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6366. cli.enable_server_certificate_verification(false);
  6367. cli.set_connection_timeout(30);
  6368. auto res = cli.Get("/test");
  6369. ASSERT_TRUE(res);
  6370. ASSERT_EQ(StatusCode::OK_200, res->status);
  6371. }
  6372. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6373. class NoListenSSLServer : public SSLServer {
  6374. public:
  6375. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6376. const char *client_ca_cert_file_path,
  6377. const char *client_ca_cert_dir_path = nullptr)
  6378. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6379. client_ca_cert_dir_path),
  6380. stop_(false) {}
  6381. std::atomic_bool stop_;
  6382. private:
  6383. bool process_and_close_socket(socket_t /*sock*/) override {
  6384. // Don't create SSL context
  6385. while (!stop_.load()) {
  6386. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6387. }
  6388. return true;
  6389. }
  6390. };
  6391. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6392. CLIENT_CA_CERT_FILE);
  6393. ASSERT_TRUE(svr.is_valid());
  6394. svr.Get("/test", [&](const Request &, Response &res) {
  6395. res.set_content("test", "text/plain");
  6396. });
  6397. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6398. auto se = detail::scope_exit([&] {
  6399. svr.stop_ = true;
  6400. svr.stop();
  6401. t.join();
  6402. ASSERT_FALSE(svr.is_running());
  6403. });
  6404. svr.wait_until_ready();
  6405. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6406. cli.enable_server_certificate_verification(false);
  6407. cli.set_connection_timeout(1);
  6408. auto res = cli.Get("/test");
  6409. ASSERT_TRUE(!res);
  6410. EXPECT_EQ(Error::SSLConnection, res.error());
  6411. }
  6412. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6413. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6414. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6415. SSL_CTX_set_options(&ssl_ctx,
  6416. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6417. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6418. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6419. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6420. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6421. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6422. "ECDHE-DSS-AES128-SHA256:"
  6423. "ECDHE-RSA-AES256-SHA256:"
  6424. "ECDHE-DSS-AES256-SHA256:";
  6425. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6426. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6427. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6428. SSL_FILETYPE_PEM) != 1) {
  6429. return false;
  6430. }
  6431. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6432. CLIENT_CA_CERT_DIR);
  6433. SSL_CTX_set_verify(
  6434. &ssl_ctx,
  6435. SSL_VERIFY_PEER |
  6436. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6437. nullptr);
  6438. return true;
  6439. };
  6440. SSLServer svr(setup_ssl_ctx_callback);
  6441. ASSERT_TRUE(svr.is_valid());
  6442. svr.Get("/test", [&](const Request &req, Response &res) {
  6443. res.set_content("test", "text/plain");
  6444. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6445. ASSERT_TRUE(peer_cert != nullptr);
  6446. auto subject_name = X509_get_subject_name(peer_cert);
  6447. ASSERT_TRUE(subject_name != nullptr);
  6448. std::string common_name;
  6449. {
  6450. char name[BUFSIZ];
  6451. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6452. name, sizeof(name));
  6453. common_name.assign(name, static_cast<size_t>(name_len));
  6454. }
  6455. EXPECT_EQ("Common Name", common_name);
  6456. X509_free(peer_cert);
  6457. });
  6458. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6459. auto se = detail::scope_exit([&] {
  6460. svr.stop();
  6461. t.join();
  6462. ASSERT_FALSE(svr.is_running());
  6463. });
  6464. svr.wait_until_ready();
  6465. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6466. cli.enable_server_certificate_verification(false);
  6467. cli.set_connection_timeout(30);
  6468. auto res = cli.Get("/test");
  6469. ASSERT_TRUE(res);
  6470. ASSERT_EQ(StatusCode::OK_200, res->status);
  6471. }
  6472. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6473. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6474. // prepare large data
  6475. std::random_device seed_gen;
  6476. std::mt19937 random(seed_gen());
  6477. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6478. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6479. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6480. // server
  6481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6482. ASSERT_TRUE(svr.is_valid());
  6483. svr.Post("/binary", [&](const Request &req, Response &res) {
  6484. EXPECT_EQ(large_size_byte, req.body.size());
  6485. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6486. res.set_content(req.body, "application/octet-stream");
  6487. });
  6488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6489. auto se = detail::scope_exit([&] {
  6490. svr.stop();
  6491. listen_thread.join();
  6492. ASSERT_FALSE(svr.is_running());
  6493. });
  6494. svr.wait_until_ready();
  6495. // client POST
  6496. SSLClient cli("localhost", PORT);
  6497. cli.enable_server_certificate_verification(false);
  6498. cli.set_read_timeout(std::chrono::seconds(100));
  6499. cli.set_write_timeout(std::chrono::seconds(100));
  6500. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6501. large_size_byte, "application/octet-stream");
  6502. // compare
  6503. EXPECT_EQ(StatusCode::OK_200, res->status);
  6504. EXPECT_EQ(large_size_byte, res->body.size());
  6505. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6506. }
  6507. #endif
  6508. #ifdef _WIN32
  6509. TEST(CleanupTest, WSACleanup) {
  6510. int ret = WSACleanup();
  6511. ASSERT_EQ(0, ret);
  6512. }
  6513. #endif
  6514. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6515. TEST(NoSSLSupport, SimpleInterface) {
  6516. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6517. }
  6518. #endif
  6519. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6520. TEST(InvalidScheme, SimpleInterface) {
  6521. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6522. }
  6523. #endif
  6524. TEST(NoScheme, SimpleInterface) {
  6525. Client cli("yahoo.com:80");
  6526. ASSERT_TRUE(cli.is_valid());
  6527. }
  6528. TEST(SendAPI, SimpleInterface_Online) {
  6529. Client cli("http://yahoo.com");
  6530. Request req;
  6531. req.method = "GET";
  6532. req.path = "/";
  6533. auto res = cli.send(req);
  6534. ASSERT_TRUE(res);
  6535. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6536. }
  6537. TEST(SendAPI, WithParamsInRequest) {
  6538. Server svr;
  6539. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6540. EXPECT_TRUE(req.has_param("test"));
  6541. EXPECT_EQ("test_value", req.get_param_value("test"));
  6542. });
  6543. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6544. auto se = detail::scope_exit([&] {
  6545. svr.stop();
  6546. t.join();
  6547. ASSERT_FALSE(svr.is_running());
  6548. });
  6549. svr.wait_until_ready();
  6550. Client cli(HOST, PORT);
  6551. {
  6552. Request req;
  6553. req.method = "GET";
  6554. req.path = "/";
  6555. req.params.emplace("test", "test_value");
  6556. auto res = cli.send(req);
  6557. ASSERT_TRUE(res);
  6558. }
  6559. {
  6560. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6561. ASSERT_TRUE(res);
  6562. }
  6563. }
  6564. TEST(ClientImplMethods, GetSocketTest) {
  6565. httplib::Server svr;
  6566. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6567. res.status = StatusCode::OK_200;
  6568. });
  6569. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6570. auto se = detail::scope_exit([&] {
  6571. svr.stop();
  6572. thread.join();
  6573. ASSERT_FALSE(svr.is_running());
  6574. });
  6575. svr.wait_until_ready();
  6576. {
  6577. httplib::Client cli("http://127.0.0.1:3333");
  6578. cli.set_keep_alive(true);
  6579. // Use the behavior of cpp-httplib of opening the connection
  6580. // only when the first request happens. If that changes,
  6581. // this test would be obsolete.
  6582. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6583. // This also implicitly tests the server. But other tests would fail much
  6584. // earlier than this one to be considered.
  6585. auto res = cli.Get("/");
  6586. ASSERT_TRUE(res);
  6587. EXPECT_EQ(StatusCode::OK_200, res->status);
  6588. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6589. }
  6590. }
  6591. // Disabled due to out-of-memory problem on GitHub Actions
  6592. #ifdef _WIN64
  6593. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6594. // allocate content size larger than 2GB in memory
  6595. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6596. char *content = (char *)malloc(content_size);
  6597. ASSERT_TRUE(content);
  6598. Server svr;
  6599. svr.Get("/foo",
  6600. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6601. res.set_content(content, content_size, "application/octet-stream");
  6602. });
  6603. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6604. auto se = detail::scope_exit([&] {
  6605. svr.stop();
  6606. listen_thread.join();
  6607. if (content) free(content);
  6608. ASSERT_FALSE(svr.is_running());
  6609. });
  6610. svr.wait_until_ready();
  6611. Client cli(HOST, PORT);
  6612. auto res = cli.Get("/foo");
  6613. ASSERT_TRUE(res);
  6614. EXPECT_EQ(StatusCode::OK_200, res->status);
  6615. EXPECT_EQ(content_size, res->body.length());
  6616. }
  6617. #endif
  6618. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6619. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6620. Client cli("http://yahoo.com");
  6621. auto res = cli.Get("/");
  6622. ASSERT_TRUE(res);
  6623. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6624. cli.set_follow_location(true);
  6625. res = cli.Get("/");
  6626. ASSERT_TRUE(res);
  6627. EXPECT_EQ(StatusCode::OK_200, res->status);
  6628. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6629. }
  6630. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6631. Client cli("https://yahoo.com");
  6632. auto res = cli.Get("/");
  6633. ASSERT_TRUE(res);
  6634. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6635. cli.set_follow_location(true);
  6636. res = cli.Get("/");
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6640. }
  6641. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6642. Client cli("https://yahoo.com");
  6643. auto res = cli.Get("/");
  6644. ASSERT_TRUE(res);
  6645. ASSERT_FALSE(!res);
  6646. ASSERT_TRUE(res);
  6647. ASSERT_FALSE(res == nullptr);
  6648. ASSERT_TRUE(res != nullptr);
  6649. EXPECT_EQ(Error::Success, res.error());
  6650. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6651. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6653. cli.set_follow_location(true);
  6654. res = cli.Get("/");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(Error::Success, res.error());
  6657. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6658. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6659. EXPECT_EQ(StatusCode::OK_200, res->status);
  6660. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6661. }
  6662. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6663. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6664. Client cli("https://cdnjs.cloudflare.com");
  6665. auto res =
  6666. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6667. ASSERT_TRUE(res);
  6668. EXPECT_EQ(StatusCode::OK_200, res->status);
  6669. EXPECT_EQ(287630U, res->body.size());
  6670. EXPECT_EQ("application/javascript; charset=utf-8",
  6671. res->get_header_value("Content-Type"));
  6672. }
  6673. #endif
  6674. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6675. #undef REDIR_HOST // Silence compiler warning
  6676. #define REDIR_HOST "https://httpbingo.org"
  6677. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6678. Client cli(REDIR_HOST);
  6679. cli.set_follow_location(true);
  6680. auto res =
  6681. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. }
  6685. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6686. Client cli(REDIR_HOST);
  6687. cli.set_follow_location(true);
  6688. Params params;
  6689. params.emplace("url", "http://example.com");
  6690. params.emplace("status_code", "302");
  6691. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6692. ASSERT_TRUE(res);
  6693. EXPECT_EQ(StatusCode::OK_200, res->status);
  6694. }
  6695. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6696. Client cli(REDIR_HOST);
  6697. cli.set_follow_location(true);
  6698. Params params;
  6699. params.emplace("url", "http://example.com");
  6700. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6701. ASSERT_TRUE(res);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. }
  6704. TEST(HttpToHttpsRedirectTest, CertFile) {
  6705. Server svr;
  6706. ASSERT_TRUE(svr.is_valid());
  6707. svr.Get("/index", [&](const Request &, Response &res) {
  6708. res.set_redirect("https://127.0.0.1:1235/index");
  6709. svr.stop();
  6710. });
  6711. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6712. ASSERT_TRUE(ssl_svr.is_valid());
  6713. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6714. res.set_content("test", "text/plain");
  6715. ssl_svr.stop();
  6716. });
  6717. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6718. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6719. auto se = detail::scope_exit([&] {
  6720. t2.join();
  6721. t.join();
  6722. ASSERT_FALSE(svr.is_running());
  6723. });
  6724. svr.wait_until_ready();
  6725. ssl_svr.wait_until_ready();
  6726. Client cli("127.0.0.1", PORT);
  6727. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6728. cli.enable_server_certificate_verification(true);
  6729. cli.set_follow_location(true);
  6730. cli.set_connection_timeout(30);
  6731. auto res = cli.Get("/index");
  6732. ASSERT_TRUE(res);
  6733. ASSERT_EQ(StatusCode::OK_200, res->status);
  6734. }
  6735. TEST(MultipartFormDataTest, LargeData) {
  6736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6737. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6738. const ContentReader &content_reader) {
  6739. if (req.is_multipart_form_data()) {
  6740. MultipartFormDataItems files;
  6741. content_reader(
  6742. [&](const MultipartFormData &file) {
  6743. files.push_back(file);
  6744. return true;
  6745. },
  6746. [&](const char *data, size_t data_length) {
  6747. files.back().content.append(data, data_length);
  6748. return true;
  6749. });
  6750. EXPECT_TRUE(std::string(files[0].name) == "document");
  6751. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  6752. EXPECT_TRUE(files[0].filename == "2MB_data");
  6753. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6754. EXPECT_TRUE(files[1].name == "hello");
  6755. EXPECT_TRUE(files[1].content == "world");
  6756. EXPECT_TRUE(files[1].filename == "");
  6757. EXPECT_TRUE(files[1].content_type == "");
  6758. } else {
  6759. std::string body;
  6760. content_reader([&](const char *data, size_t data_length) {
  6761. body.append(data, data_length);
  6762. return true;
  6763. });
  6764. }
  6765. });
  6766. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6767. auto se = detail::scope_exit([&] {
  6768. svr.stop();
  6769. t.join();
  6770. ASSERT_FALSE(svr.is_running());
  6771. });
  6772. svr.wait_until_ready();
  6773. {
  6774. std::string data(1024 * 1024 * 2, '.');
  6775. std::stringstream buffer;
  6776. buffer << data;
  6777. Client cli("https://localhost:8080");
  6778. cli.enable_server_certificate_verification(false);
  6779. MultipartFormDataItemsForClientInput items{
  6780. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6781. {"hello", "world", "", ""},
  6782. };
  6783. auto res = cli.Post("/post", items);
  6784. ASSERT_TRUE(res);
  6785. ASSERT_EQ(StatusCode::OK_200, res->status);
  6786. }
  6787. }
  6788. TEST(MultipartFormDataTest, DataProviderItems) {
  6789. std::random_device seed_gen;
  6790. std::mt19937 random(seed_gen());
  6791. std::string rand1;
  6792. rand1.resize(1000);
  6793. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  6794. std::string rand2;
  6795. rand2.resize(3000);
  6796. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  6797. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6798. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  6799. const ContentReader &content_reader) {
  6800. ASSERT_FALSE(req.is_multipart_form_data());
  6801. std::string body;
  6802. content_reader([&](const char *data, size_t data_length) {
  6803. body.append(data, data_length);
  6804. return true;
  6805. });
  6806. EXPECT_EQ(body, "");
  6807. });
  6808. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  6809. const ContentReader &content_reader) {
  6810. ASSERT_TRUE(req.is_multipart_form_data());
  6811. MultipartFormDataItems files;
  6812. content_reader(
  6813. [&](const MultipartFormData &file) {
  6814. files.push_back(file);
  6815. return true;
  6816. },
  6817. [&](const char *data, size_t data_length) {
  6818. files.back().content.append(data, data_length);
  6819. return true;
  6820. });
  6821. ASSERT_TRUE(files.size() == 2);
  6822. EXPECT_EQ(std::string(files[0].name), "name1");
  6823. EXPECT_EQ(files[0].content, "Testing123");
  6824. EXPECT_EQ(files[0].filename, "filename1");
  6825. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6826. EXPECT_EQ(files[1].name, "name2");
  6827. EXPECT_EQ(files[1].content, "Testing456");
  6828. EXPECT_EQ(files[1].filename, "");
  6829. EXPECT_EQ(files[1].content_type, "");
  6830. });
  6831. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  6832. const ContentReader &content_reader) {
  6833. ASSERT_TRUE(req.is_multipart_form_data());
  6834. MultipartFormDataItems files;
  6835. content_reader(
  6836. [&](const MultipartFormData &file) {
  6837. files.push_back(file);
  6838. return true;
  6839. },
  6840. [&](const char *data, size_t data_length) {
  6841. files.back().content.append(data, data_length);
  6842. return true;
  6843. });
  6844. ASSERT_TRUE(files.size() == 2);
  6845. EXPECT_EQ(files[0].name, "name3");
  6846. EXPECT_EQ(files[0].content, rand1);
  6847. EXPECT_EQ(files[0].filename, "filename3");
  6848. EXPECT_EQ(files[0].content_type, "");
  6849. EXPECT_EQ(files[1].name, "name4");
  6850. EXPECT_EQ(files[1].content, rand2);
  6851. EXPECT_EQ(files[1].filename, "filename4");
  6852. EXPECT_EQ(files[1].content_type, "");
  6853. });
  6854. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  6855. const ContentReader &content_reader) {
  6856. ASSERT_TRUE(req.is_multipart_form_data());
  6857. MultipartFormDataItems files;
  6858. content_reader(
  6859. [&](const MultipartFormData &file) {
  6860. files.push_back(file);
  6861. return true;
  6862. },
  6863. [&](const char *data, size_t data_length) {
  6864. files.back().content.append(data, data_length);
  6865. return true;
  6866. });
  6867. ASSERT_TRUE(files.size() == 4);
  6868. EXPECT_EQ(std::string(files[0].name), "name1");
  6869. EXPECT_EQ(files[0].content, "Testing123");
  6870. EXPECT_EQ(files[0].filename, "filename1");
  6871. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  6872. EXPECT_EQ(files[1].name, "name2");
  6873. EXPECT_EQ(files[1].content, "Testing456");
  6874. EXPECT_EQ(files[1].filename, "");
  6875. EXPECT_EQ(files[1].content_type, "");
  6876. EXPECT_EQ(files[2].name, "name3");
  6877. EXPECT_EQ(files[2].content, rand1);
  6878. EXPECT_EQ(files[2].filename, "filename3");
  6879. EXPECT_EQ(files[2].content_type, "");
  6880. EXPECT_EQ(files[3].name, "name4");
  6881. EXPECT_EQ(files[3].content, rand2);
  6882. EXPECT_EQ(files[3].filename, "filename4");
  6883. EXPECT_EQ(files[3].content_type, "");
  6884. });
  6885. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6886. auto se = detail::scope_exit([&] {
  6887. svr.stop();
  6888. t.join();
  6889. ASSERT_FALSE(svr.is_running());
  6890. });
  6891. svr.wait_until_ready();
  6892. {
  6893. Client cli("https://localhost:8080");
  6894. cli.enable_server_certificate_verification(false);
  6895. MultipartFormDataItemsForClientInput items{
  6896. {"name1", "Testing123", "filename1", "application/octet-stream"},
  6897. {"name2", "Testing456", "", ""}, // not a file
  6898. };
  6899. {
  6900. auto res = cli.Post("/post-none", {}, {}, {});
  6901. ASSERT_TRUE(res);
  6902. ASSERT_EQ(StatusCode::OK_200, res->status);
  6903. }
  6904. MultipartFormDataProviderItems providers;
  6905. {
  6906. auto res =
  6907. cli.Post("/post-items", {}, items, providers); // empty providers
  6908. ASSERT_TRUE(res);
  6909. ASSERT_EQ(StatusCode::OK_200, res->status);
  6910. }
  6911. providers.push_back({"name3",
  6912. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6913. // test the offset is given correctly at each step
  6914. if (!offset)
  6915. sink.os.write(rand1.data(), 30);
  6916. else if (offset == 30)
  6917. sink.os.write(rand1.data() + 30, 300);
  6918. else if (offset == 330)
  6919. sink.os.write(rand1.data() + 330, 670);
  6920. else if (offset == rand1.size())
  6921. sink.done();
  6922. return true;
  6923. },
  6924. "filename3",
  6925. {}});
  6926. providers.push_back({"name4",
  6927. [&](size_t offset, httplib::DataSink &sink) -> bool {
  6928. // test the offset is given correctly at each step
  6929. if (!offset)
  6930. sink.os.write(rand2.data(), 2000);
  6931. else if (offset == 2000)
  6932. sink.os.write(rand2.data() + 2000, 1);
  6933. else if (offset == 2001)
  6934. sink.os.write(rand2.data() + 2001, 999);
  6935. else if (offset == rand2.size())
  6936. sink.done();
  6937. return true;
  6938. },
  6939. "filename4",
  6940. {}});
  6941. {
  6942. auto res = cli.Post("/post-providers", {}, {}, providers);
  6943. ASSERT_TRUE(res);
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. {
  6947. auto res = cli.Post("/post-both", {}, items, providers);
  6948. ASSERT_TRUE(res);
  6949. ASSERT_EQ(StatusCode::OK_200, res->status);
  6950. }
  6951. }
  6952. }
  6953. TEST(MultipartFormDataTest, BadHeader) {
  6954. Server svr;
  6955. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6956. res.set_content("ok", "text/plain");
  6957. });
  6958. thread t = thread([&] { svr.listen(HOST, PORT); });
  6959. auto se = detail::scope_exit([&] {
  6960. svr.stop();
  6961. t.join();
  6962. ASSERT_FALSE(svr.is_running());
  6963. });
  6964. svr.wait_until_ready();
  6965. const std::string body =
  6966. "This is the preamble. It is to be ignored, though it\r\n"
  6967. "is a handy place for composition agents to include an\r\n"
  6968. "explanatory note to non-MIME conformant readers.\r\n"
  6969. "\r\n"
  6970. "\r\n"
  6971. "--simple boundary\r\n"
  6972. "Content-Disposition: form-data; name=\"field1\"\r\n"
  6973. ": BAD...\r\n"
  6974. "\r\n"
  6975. "value1\r\n"
  6976. "--simple boundary\r\n"
  6977. "Content-Disposition: form-data; name=\"field2\"; "
  6978. "filename=\"example.txt\"\r\n"
  6979. "\r\n"
  6980. "value2\r\n"
  6981. "--simple boundary--\r\n"
  6982. "This is the epilogue. It is also to be ignored.\r\n";
  6983. std::string content_type =
  6984. R"(multipart/form-data; boundary="simple boundary")";
  6985. Client cli(HOST, PORT);
  6986. auto res = cli.Post("/post", body, content_type.c_str());
  6987. ASSERT_TRUE(res);
  6988. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6989. }
  6990. TEST(MultipartFormDataTest, WithPreamble) {
  6991. Server svr;
  6992. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  6993. res.set_content("ok", "text/plain");
  6994. });
  6995. thread t = thread([&] { svr.listen(HOST, PORT); });
  6996. auto se = detail::scope_exit([&] {
  6997. svr.stop();
  6998. t.join();
  6999. ASSERT_FALSE(svr.is_running());
  7000. });
  7001. svr.wait_until_ready();
  7002. const std::string body =
  7003. "This is the preamble. It is to be ignored, though it\r\n"
  7004. "is a handy place for composition agents to include an\r\n"
  7005. "explanatory note to non-MIME conformant readers.\r\n"
  7006. "\r\n"
  7007. "\r\n"
  7008. "--simple boundary\r\n"
  7009. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7010. "\r\n"
  7011. "value1\r\n"
  7012. "--simple boundary\r\n"
  7013. "Content-Disposition: form-data; name=\"field2\"; "
  7014. "filename=\"example.txt\"\r\n"
  7015. "\r\n"
  7016. "value2\r\n"
  7017. "--simple boundary--\r\n"
  7018. "This is the epilogue. It is also to be ignored.\r\n";
  7019. std::string content_type =
  7020. R"(multipart/form-data; boundary="simple boundary")";
  7021. Client cli(HOST, PORT);
  7022. auto res = cli.Post("/post", body, content_type.c_str());
  7023. ASSERT_TRUE(res);
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. }
  7026. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7028. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7029. const ContentReader &content_reader) {
  7030. if (req.is_multipart_form_data()) {
  7031. MultipartFormDataItems files;
  7032. content_reader(
  7033. [&](const MultipartFormData &file) {
  7034. files.push_back(file);
  7035. return true;
  7036. },
  7037. [&](const char *data, size_t data_length) {
  7038. files.back().content.append(data, data_length);
  7039. return true;
  7040. });
  7041. EXPECT_TRUE(std::string(files[0].name) == "document");
  7042. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7043. EXPECT_TRUE(files[0].filename == "2MB_data");
  7044. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7045. EXPECT_TRUE(files[1].name == "hello");
  7046. EXPECT_TRUE(files[1].content == "world");
  7047. EXPECT_TRUE(files[1].filename == "");
  7048. EXPECT_TRUE(files[1].content_type == "");
  7049. } else {
  7050. std::string body;
  7051. content_reader([&](const char *data, size_t data_length) {
  7052. body.append(data, data_length);
  7053. return true;
  7054. });
  7055. }
  7056. });
  7057. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7058. auto se = detail::scope_exit([&] {
  7059. svr.stop();
  7060. t.join();
  7061. ASSERT_FALSE(svr.is_running());
  7062. });
  7063. svr.wait_until_ready();
  7064. {
  7065. std::string data(1024 * 1024 * 2, '.');
  7066. std::stringstream buffer;
  7067. buffer << data;
  7068. Client cli("https://localhost:8080");
  7069. cli.enable_server_certificate_verification(false);
  7070. MultipartFormDataItemsForClientInput items{
  7071. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7072. {"hello", "world", "", ""},
  7073. };
  7074. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7075. ASSERT_TRUE(res);
  7076. ASSERT_EQ(StatusCode::OK_200, res->status);
  7077. }
  7078. }
  7079. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7080. std::string data(1024 * 1024 * 2, '&');
  7081. std::stringstream buffer;
  7082. buffer << data;
  7083. Client cli("https://localhost:8080");
  7084. MultipartFormDataItemsForClientInput items{
  7085. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7086. {"hello", "world", "", ""},
  7087. };
  7088. for (const char &c : " \t\r\n") {
  7089. auto res =
  7090. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7091. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7092. ASSERT_FALSE(res);
  7093. }
  7094. }
  7095. TEST(MultipartFormDataTest, PutFormData) {
  7096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7097. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7098. const ContentReader &content_reader) {
  7099. if (req.is_multipart_form_data()) {
  7100. MultipartFormDataItems files;
  7101. content_reader(
  7102. [&](const MultipartFormData &file) {
  7103. files.push_back(file);
  7104. return true;
  7105. },
  7106. [&](const char *data, size_t data_length) {
  7107. files.back().content.append(data, data_length);
  7108. return true;
  7109. });
  7110. EXPECT_TRUE(std::string(files[0].name) == "document");
  7111. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7112. EXPECT_TRUE(files[0].filename == "2MB_data");
  7113. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7114. EXPECT_TRUE(files[1].name == "hello");
  7115. EXPECT_TRUE(files[1].content == "world");
  7116. EXPECT_TRUE(files[1].filename == "");
  7117. EXPECT_TRUE(files[1].content_type == "");
  7118. } else {
  7119. std::string body;
  7120. content_reader([&](const char *data, size_t data_length) {
  7121. body.append(data, data_length);
  7122. return true;
  7123. });
  7124. }
  7125. });
  7126. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7127. auto se = detail::scope_exit([&] {
  7128. svr.stop();
  7129. t.join();
  7130. ASSERT_FALSE(svr.is_running());
  7131. });
  7132. svr.wait_until_ready();
  7133. {
  7134. std::string data(1024 * 1024 * 2, '&');
  7135. std::stringstream buffer;
  7136. buffer << data;
  7137. Client cli("https://localhost:8080");
  7138. cli.enable_server_certificate_verification(false);
  7139. MultipartFormDataItemsForClientInput items{
  7140. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7141. {"hello", "world", "", ""},
  7142. };
  7143. auto res = cli.Put("/put", items);
  7144. ASSERT_TRUE(res);
  7145. ASSERT_EQ(StatusCode::OK_200, res->status);
  7146. }
  7147. }
  7148. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7150. svr.Put("/put_customboundary",
  7151. [&](const Request &req, const Response & /*res*/,
  7152. const ContentReader &content_reader) {
  7153. if (req.is_multipart_form_data()) {
  7154. MultipartFormDataItems files;
  7155. content_reader(
  7156. [&](const MultipartFormData &file) {
  7157. files.push_back(file);
  7158. return true;
  7159. },
  7160. [&](const char *data, size_t data_length) {
  7161. files.back().content.append(data, data_length);
  7162. return true;
  7163. });
  7164. EXPECT_TRUE(std::string(files[0].name) == "document");
  7165. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7166. EXPECT_TRUE(files[0].filename == "2MB_data");
  7167. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7168. EXPECT_TRUE(files[1].name == "hello");
  7169. EXPECT_TRUE(files[1].content == "world");
  7170. EXPECT_TRUE(files[1].filename == "");
  7171. EXPECT_TRUE(files[1].content_type == "");
  7172. } else {
  7173. std::string body;
  7174. content_reader([&](const char *data, size_t data_length) {
  7175. body.append(data, data_length);
  7176. return true;
  7177. });
  7178. }
  7179. });
  7180. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7181. auto se = detail::scope_exit([&] {
  7182. svr.stop();
  7183. t.join();
  7184. ASSERT_FALSE(svr.is_running());
  7185. });
  7186. svr.wait_until_ready();
  7187. {
  7188. std::string data(1024 * 1024 * 2, '&');
  7189. std::stringstream buffer;
  7190. buffer << data;
  7191. Client cli("https://localhost:8080");
  7192. cli.enable_server_certificate_verification(false);
  7193. MultipartFormDataItemsForClientInput items{
  7194. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7195. {"hello", "world", "", ""},
  7196. };
  7197. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7198. ASSERT_TRUE(res);
  7199. ASSERT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. }
  7202. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7203. std::string data(1024 * 1024 * 2, '&');
  7204. std::stringstream buffer;
  7205. buffer << data;
  7206. Client cli("https://localhost:8080");
  7207. cli.enable_server_certificate_verification(false);
  7208. MultipartFormDataItemsForClientInput items{
  7209. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7210. {"hello", "world", "", ""},
  7211. };
  7212. for (const char &c : " \t\r\n") {
  7213. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7214. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7215. ASSERT_FALSE(res);
  7216. }
  7217. }
  7218. TEST(MultipartFormDataTest, AlternateFilename) {
  7219. auto handled = false;
  7220. Server svr;
  7221. svr.Post("/test", [&](const Request &req, Response &res) {
  7222. ASSERT_EQ(3u, req.files.size());
  7223. auto it = req.files.begin();
  7224. ASSERT_EQ("file1", it->second.name);
  7225. ASSERT_EQ("A.txt", it->second.filename);
  7226. ASSERT_EQ("text/plain", it->second.content_type);
  7227. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7228. ++it;
  7229. ASSERT_EQ("file2", it->second.name);
  7230. ASSERT_EQ("a.html", it->second.filename);
  7231. ASSERT_EQ("text/html", it->second.content_type);
  7232. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7233. it->second.content);
  7234. ++it;
  7235. ASSERT_EQ("text", it->second.name);
  7236. ASSERT_EQ("", it->second.filename);
  7237. ASSERT_EQ("", it->second.content_type);
  7238. ASSERT_EQ("text default", it->second.content);
  7239. res.set_content("ok", "text/plain");
  7240. handled = true;
  7241. });
  7242. thread t = thread([&] { svr.listen(HOST, PORT); });
  7243. auto se = detail::scope_exit([&] {
  7244. svr.stop();
  7245. t.join();
  7246. ASSERT_FALSE(svr.is_running());
  7247. ASSERT_TRUE(handled);
  7248. });
  7249. svr.wait_until_ready();
  7250. auto req = "POST /test HTTP/1.1\r\n"
  7251. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7252. "Content-Length: 399\r\n"
  7253. "\r\n"
  7254. "----------\r\n"
  7255. "Content-Disposition: form-data; name=\"text\"\r\n"
  7256. "\r\n"
  7257. "text default\r\n"
  7258. "----------\r\n"
  7259. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7260. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7261. "Content-Type: text/plain\r\n"
  7262. "\r\n"
  7263. "Content of a.txt.\r\n"
  7264. "\r\n"
  7265. "----------\r\n"
  7266. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7267. "\"a.html\"\r\n"
  7268. "Content-Type: text/html\r\n"
  7269. "\r\n"
  7270. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7271. "\r\n"
  7272. "------------\r\n";
  7273. ASSERT_TRUE(send_request(1, req));
  7274. }
  7275. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7276. auto handled = false;
  7277. Server svr;
  7278. svr.Post("/test", [&](const Request &req, Response &) {
  7279. ASSERT_EQ(2u, req.files.size());
  7280. auto it = req.files.begin();
  7281. ASSERT_EQ("text1", it->second.name);
  7282. ASSERT_EQ("text1", it->second.content);
  7283. ++it;
  7284. ASSERT_EQ("text2", it->second.name);
  7285. ASSERT_EQ("text2", it->second.content);
  7286. handled = true;
  7287. });
  7288. thread t = thread([&] { svr.listen(HOST, PORT); });
  7289. auto se = detail::scope_exit([&] {
  7290. svr.stop();
  7291. t.join();
  7292. ASSERT_FALSE(svr.is_running());
  7293. ASSERT_TRUE(handled);
  7294. });
  7295. svr.wait_until_ready();
  7296. auto req = "POST /test HTTP/1.1\r\n"
  7297. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7298. "Content-Length: 146\r\n"
  7299. "\r\n----------\r\n"
  7300. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7301. "\r\n"
  7302. "text1"
  7303. "\r\n----------\r\n"
  7304. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7305. "\r\n"
  7306. "text2"
  7307. "\r\n------------";
  7308. std::string response;
  7309. ASSERT_TRUE(send_request(1, req, &response));
  7310. ASSERT_EQ("200", response.substr(9, 3));
  7311. }
  7312. TEST(MultipartFormDataTest, ContentLength) {
  7313. auto handled = false;
  7314. Server svr;
  7315. svr.Post("/test", [&](const Request &req, Response &) {
  7316. ASSERT_EQ(2u, req.files.size());
  7317. auto it = req.files.begin();
  7318. ASSERT_EQ("text1", it->second.name);
  7319. ASSERT_EQ("text1", it->second.content);
  7320. ++it;
  7321. ASSERT_EQ("text2", it->second.name);
  7322. ASSERT_EQ("text2", it->second.content);
  7323. handled = true;
  7324. });
  7325. thread t = thread([&] { svr.listen(HOST, PORT); });
  7326. auto se = detail::scope_exit([&] {
  7327. svr.stop();
  7328. t.join();
  7329. ASSERT_FALSE(svr.is_running());
  7330. ASSERT_TRUE(handled);
  7331. });
  7332. svr.wait_until_ready();
  7333. auto req = "POST /test HTTP/1.1\r\n"
  7334. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7335. "Content-Length: 167\r\n"
  7336. "\r\n----------\r\n"
  7337. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7338. "Content-Length: 5\r\n"
  7339. "\r\n"
  7340. "text1"
  7341. "\r\n----------\r\n"
  7342. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7343. "\r\n"
  7344. "text2"
  7345. "\r\n------------\r\n";
  7346. std::string response;
  7347. ASSERT_TRUE(send_request(1, req, &response));
  7348. ASSERT_EQ("200", response.substr(9, 3));
  7349. }
  7350. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7351. auto handled = false;
  7352. Server svr;
  7353. svr.Post("/test", [&](const Request &req, Response &) {
  7354. ASSERT_EQ(2u, req.files.size());
  7355. auto it = req.files.begin();
  7356. ASSERT_EQ("text1", it->second.name);
  7357. ASSERT_EQ("text1", it->second.content);
  7358. ASSERT_EQ(1, it->second.headers.count("Content-Length"));
  7359. auto content_length = it->second.headers.find("CONTENT-length");
  7360. ASSERT_EQ("5", content_length->second);
  7361. ASSERT_EQ(3, it->second.headers.size());
  7362. ++it;
  7363. ASSERT_EQ("text2", it->second.name);
  7364. ASSERT_EQ("text2", it->second.content);
  7365. auto &headers = it->second.headers;
  7366. ASSERT_EQ(3, headers.size());
  7367. auto custom_header = headers.find("x-whatever");
  7368. ASSERT_TRUE(custom_header != headers.end());
  7369. ASSERT_NE("customvalue", custom_header->second);
  7370. ASSERT_EQ("CustomValue", custom_header->second);
  7371. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7372. handled = true;
  7373. });
  7374. thread t = thread([&] { svr.listen(HOST, PORT); });
  7375. auto se = detail::scope_exit([&] {
  7376. svr.stop();
  7377. t.join();
  7378. ASSERT_FALSE(svr.is_running());
  7379. ASSERT_TRUE(handled);
  7380. });
  7381. svr.wait_until_ready();
  7382. auto req = "POST /test HTTP/1.1\r\n"
  7383. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7384. "Content-Length: 232\r\n"
  7385. "\r\n----------\r\n"
  7386. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7387. "Content-Length: 5\r\n"
  7388. "X-Test: 1\r\n"
  7389. "\r\n"
  7390. "text1"
  7391. "\r\n----------\r\n"
  7392. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7393. "Content-Type: text/plain\r\n"
  7394. "X-Whatever: CustomValue\r\n"
  7395. "\r\n"
  7396. "text2"
  7397. "\r\n------------\r\n"
  7398. "That should be disregarded. Not even read";
  7399. std::string response;
  7400. ASSERT_TRUE(send_request(1, req, &response));
  7401. ASSERT_EQ("200", response.substr(9, 3));
  7402. }
  7403. #endif
  7404. TEST(MultipartFormDataTest, LargeHeader) {
  7405. auto handled = false;
  7406. Server svr;
  7407. svr.Post("/test", [&](const Request &req, Response &) {
  7408. ASSERT_EQ(1u, req.files.size());
  7409. auto it = req.files.begin();
  7410. ASSERT_EQ("name1", it->second.name);
  7411. ASSERT_EQ("text1", it->second.content);
  7412. handled = true;
  7413. });
  7414. thread t = thread([&] { svr.listen(HOST, PORT); });
  7415. auto se = detail::scope_exit([&] {
  7416. svr.stop();
  7417. t.join();
  7418. ASSERT_FALSE(svr.is_running());
  7419. ASSERT_TRUE(handled);
  7420. });
  7421. svr.wait_until_ready();
  7422. auto boundary = std::string("cpp-httplib-multipart-data");
  7423. std::string content = "--" + boundary +
  7424. "\r\n"
  7425. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7426. "\r\n"
  7427. "text1\r\n"
  7428. "--" +
  7429. boundary + "--\r\n";
  7430. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7431. "Content-Type: multipart/form-data;boundary=" +
  7432. boundary +
  7433. "\r\n"
  7434. "Content-Length: " +
  7435. std::to_string(content.size()) +
  7436. "\r\n"
  7437. "Dummy-Header: ";
  7438. std::string header_suffix = "\r\n"
  7439. "\r\n";
  7440. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7441. size_t header_dummy_size =
  7442. read_buff_size -
  7443. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7444. auto header_dummy = std::string(header_dummy_size, '@');
  7445. auto req = header_prefix + header_dummy + header_suffix + content;
  7446. std::string response;
  7447. ASSERT_TRUE(send_request(1, req, &response));
  7448. ASSERT_EQ("200", response.substr(9, 3));
  7449. }
  7450. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7451. static constexpr unsigned int number_of_tasks{1000000};
  7452. std::atomic_uint count{0};
  7453. std::unique_ptr<TaskQueue> task_queue{
  7454. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7455. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7456. auto queued = task_queue->enqueue(
  7457. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7458. EXPECT_TRUE(queued);
  7459. }
  7460. EXPECT_NO_THROW(task_queue->shutdown());
  7461. EXPECT_EQ(number_of_tasks, count.load());
  7462. }
  7463. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7464. static constexpr unsigned int number_of_tasks{1000000};
  7465. static constexpr unsigned int qlimit{2};
  7466. unsigned int queued_count{0};
  7467. std::atomic_uint count{0};
  7468. std::unique_ptr<TaskQueue> task_queue{
  7469. new ThreadPool{/*num_threads=*/1, qlimit}};
  7470. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7471. if (task_queue->enqueue(
  7472. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7473. queued_count++;
  7474. }
  7475. }
  7476. EXPECT_NO_THROW(task_queue->shutdown());
  7477. EXPECT_EQ(queued_count, count.load());
  7478. EXPECT_TRUE(queued_count <= number_of_tasks);
  7479. EXPECT_TRUE(queued_count >= qlimit);
  7480. }
  7481. TEST(TaskQueueTest, MaxQueuedRequests) {
  7482. static constexpr unsigned int qlimit{3};
  7483. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7484. std::condition_variable sem_cv;
  7485. std::mutex sem_mtx;
  7486. int credits = 0;
  7487. bool queued;
  7488. /* Fill up the queue with tasks that will block until we give them credits to
  7489. * complete. */
  7490. for (unsigned int n = 0; n <= qlimit;) {
  7491. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7492. std::unique_lock<std::mutex> lock(sem_mtx);
  7493. while (credits <= 0) {
  7494. sem_cv.wait(lock);
  7495. }
  7496. /* Consume the credit and signal the test code if they are all gone. */
  7497. if (--credits == 0) { sem_cv.notify_one(); }
  7498. });
  7499. if (n < qlimit) {
  7500. /* The first qlimit enqueues must succeed. */
  7501. EXPECT_TRUE(queued);
  7502. } else {
  7503. /* The last one will succeed only when the worker thread
  7504. * starts and dequeues the first blocking task. Although
  7505. * not necessary for the correctness of this test, we sleep for
  7506. * a short while to avoid busy waiting. */
  7507. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7508. }
  7509. if (queued) { n++; }
  7510. }
  7511. /* Further enqueues must fail since the queue is full. */
  7512. for (auto i = 0; i < 4; i++) {
  7513. queued = task_queue->enqueue([] {});
  7514. EXPECT_FALSE(queued);
  7515. }
  7516. /* Give the credits to allow the previous tasks to complete. */
  7517. {
  7518. std::unique_lock<std::mutex> lock(sem_mtx);
  7519. credits += qlimit + 1;
  7520. }
  7521. sem_cv.notify_all();
  7522. /* Wait for all the credits to be consumed. */
  7523. {
  7524. std::unique_lock<std::mutex> lock(sem_mtx);
  7525. while (credits > 0) {
  7526. sem_cv.wait(lock);
  7527. }
  7528. }
  7529. /* Check that we are able again to enqueue at least qlimit tasks. */
  7530. for (unsigned int i = 0; i < qlimit; i++) {
  7531. queued = task_queue->enqueue([] {});
  7532. EXPECT_TRUE(queued);
  7533. }
  7534. EXPECT_NO_THROW(task_queue->shutdown());
  7535. }
  7536. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7537. Server svr;
  7538. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7539. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7540. });
  7541. svr.Get("/hello", [](const Request &req, Response &res) {
  7542. res.set_content(req.get_param_value("key"), "text/plain");
  7543. });
  7544. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7545. auto se = detail::scope_exit([&] {
  7546. svr.stop();
  7547. thread.join();
  7548. ASSERT_FALSE(svr.is_running());
  7549. });
  7550. svr.wait_until_ready();
  7551. {
  7552. Client cli(HOST, PORT);
  7553. cli.set_follow_location(true);
  7554. auto res = cli.Get("/");
  7555. ASSERT_TRUE(res);
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("val&key2=val2", res->body);
  7558. }
  7559. }
  7560. TEST(VulnerabilityTest, CRLFInjection) {
  7561. Server svr;
  7562. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7563. res.set_content("Hello 1", "text/plain");
  7564. });
  7565. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7566. res.set_content("Hello 2", "text/plain");
  7567. });
  7568. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7569. res.set_content("Hello 3", "text/plain");
  7570. });
  7571. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7572. res.set_content("Hello 4", "text/plain");
  7573. });
  7574. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7575. for (const auto &x : req.headers) {
  7576. auto key = x.first;
  7577. EXPECT_STRNE("evil", key.c_str());
  7578. }
  7579. });
  7580. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7581. auto se = detail::scope_exit([&] {
  7582. svr.stop();
  7583. thread.join();
  7584. ASSERT_FALSE(svr.is_running());
  7585. });
  7586. svr.wait_until_ready();
  7587. {
  7588. Client cli(HOST, PORT);
  7589. cli.Post("/test1", "A=B",
  7590. "application/x-www-form-urlencoded\r\nevil: hello1");
  7591. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7592. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7593. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7594. }
  7595. }
  7596. TEST(PathParamsTest, StaticMatch) {
  7597. const auto pattern = "/users/all";
  7598. detail::PathParamsMatcher matcher(pattern);
  7599. Request request;
  7600. request.path = "/users/all";
  7601. ASSERT_TRUE(matcher.match(request));
  7602. std::unordered_map<std::string, std::string> expected_params = {};
  7603. EXPECT_EQ(request.path_params, expected_params);
  7604. }
  7605. TEST(PathParamsTest, StaticMismatch) {
  7606. const auto pattern = "/users/all";
  7607. detail::PathParamsMatcher matcher(pattern);
  7608. Request request;
  7609. request.path = "/users/1";
  7610. ASSERT_FALSE(matcher.match(request));
  7611. }
  7612. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7613. const auto pattern = "/users/:id/subscriptions";
  7614. detail::PathParamsMatcher matcher(pattern);
  7615. Request request;
  7616. request.path = "/users/42/subscriptions";
  7617. ASSERT_TRUE(matcher.match(request));
  7618. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7619. EXPECT_EQ(request.path_params, expected_params);
  7620. }
  7621. TEST(PathParamsTest, SingleParamInTheEnd) {
  7622. const auto pattern = "/users/:id";
  7623. detail::PathParamsMatcher matcher(pattern);
  7624. Request request;
  7625. request.path = "/users/24";
  7626. ASSERT_TRUE(matcher.match(request));
  7627. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7628. EXPECT_EQ(request.path_params, expected_params);
  7629. }
  7630. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7631. const auto pattern = "/users/:id/";
  7632. detail::PathParamsMatcher matcher(pattern);
  7633. Request request;
  7634. request.path = "/users/42/";
  7635. ASSERT_TRUE(matcher.match(request));
  7636. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7637. EXPECT_EQ(request.path_params, expected_params);
  7638. }
  7639. TEST(PathParamsTest, EmptyParam) {
  7640. const auto pattern = "/users/:id/";
  7641. detail::PathParamsMatcher matcher(pattern);
  7642. Request request;
  7643. request.path = "/users//";
  7644. ASSERT_TRUE(matcher.match(request));
  7645. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  7646. EXPECT_EQ(request.path_params, expected_params);
  7647. }
  7648. TEST(PathParamsTest, FragmentMismatch) {
  7649. const auto pattern = "/users/:id/";
  7650. detail::PathParamsMatcher matcher(pattern);
  7651. Request request;
  7652. request.path = "/admins/24/";
  7653. ASSERT_FALSE(matcher.match(request));
  7654. }
  7655. TEST(PathParamsTest, ExtraFragments) {
  7656. const auto pattern = "/users/:id";
  7657. detail::PathParamsMatcher matcher(pattern);
  7658. Request request;
  7659. request.path = "/users/42/subscriptions";
  7660. ASSERT_FALSE(matcher.match(request));
  7661. }
  7662. TEST(PathParamsTest, MissingTrailingParam) {
  7663. const auto pattern = "/users/:id";
  7664. detail::PathParamsMatcher matcher(pattern);
  7665. Request request;
  7666. request.path = "/users";
  7667. ASSERT_FALSE(matcher.match(request));
  7668. }
  7669. TEST(PathParamsTest, MissingParamInTheMiddle) {
  7670. const auto pattern = "/users/:id/subscriptions";
  7671. detail::PathParamsMatcher matcher(pattern);
  7672. Request request;
  7673. request.path = "/users/subscriptions";
  7674. ASSERT_FALSE(matcher.match(request));
  7675. }
  7676. TEST(PathParamsTest, MultipleParams) {
  7677. const auto pattern = "/users/:userid/subscriptions/:subid";
  7678. detail::PathParamsMatcher matcher(pattern);
  7679. Request request;
  7680. request.path = "/users/42/subscriptions/2";
  7681. ASSERT_TRUE(matcher.match(request));
  7682. std::unordered_map<std::string, std::string> expected_params = {
  7683. {"userid", "42"}, {"subid", "2"}};
  7684. EXPECT_EQ(request.path_params, expected_params);
  7685. }
  7686. TEST(PathParamsTest, SequenceOfParams) {
  7687. const auto pattern = "/values/:x/:y/:z";
  7688. detail::PathParamsMatcher matcher(pattern);
  7689. Request request;
  7690. request.path = "/values/1/2/3";
  7691. ASSERT_TRUE(matcher.match(request));
  7692. std::unordered_map<std::string, std::string> expected_params = {
  7693. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  7694. EXPECT_EQ(request.path_params, expected_params);
  7695. }
  7696. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  7697. const auto pattern = "/prefix:suffix";
  7698. detail::PathParamsMatcher matcher(pattern);
  7699. Request request;
  7700. request.path = "/prefix:suffix";
  7701. ASSERT_TRUE(matcher.match(request));
  7702. const std::unordered_map<std::string, std::string> expected_params = {};
  7703. EXPECT_EQ(request.path_params, expected_params);
  7704. }
  7705. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  7706. // If ipv6 regex working, regex match codepath is taken.
  7707. // else port will default to 80 in Client impl
  7708. int clientImplMagicPort = 80;
  7709. int port = 4321;
  7710. // above ports must be different to avoid false negative
  7711. EXPECT_NE(clientImplMagicPort, port);
  7712. std::string ipV6TestURL = "http://[ff06::c3]";
  7713. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  7714. CLIENT_PRIVATE_KEY_FILE);
  7715. EXPECT_EQ(cli.port(), port);
  7716. }
  7717. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  7718. auto file_path = "./www/dir/index.html";
  7719. auto dir_path = "./www/dir";
  7720. detail::FileStat stat_file(file_path);
  7721. EXPECT_TRUE(stat_file.is_file());
  7722. EXPECT_FALSE(stat_file.is_dir());
  7723. detail::FileStat stat_dir(dir_path);
  7724. EXPECT_FALSE(stat_dir.is_file());
  7725. EXPECT_TRUE(stat_dir.is_dir());
  7726. }
  7727. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  7728. Server svr;
  7729. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7730. EXPECT_EQ(res.status, 400);
  7731. });
  7732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7733. auto se = detail::scope_exit([&] {
  7734. svr.stop();
  7735. thread.join();
  7736. ASSERT_FALSE(svr.is_running());
  7737. });
  7738. svr.wait_until_ready();
  7739. Client cli(HOST, PORT);
  7740. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  7741. }
  7742. TEST(InvalidHeaderCharsTest, is_field_name) {
  7743. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  7744. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  7745. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  7746. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  7747. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  7748. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  7749. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  7750. EXPECT_FALSE(detail::fields::is_field_name(""));
  7751. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  7752. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  7753. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  7754. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  7755. }
  7756. TEST(InvalidHeaderCharsTest, is_field_value) {
  7757. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  7758. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  7759. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  7760. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  7761. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  7762. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  7763. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  7764. EXPECT_TRUE(detail::fields::is_field_value(""));
  7765. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  7766. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  7767. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  7768. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  7769. EXPECT_TRUE(detail::fields::is_field_value("0"));
  7770. }
  7771. TEST(InvalidHeaderCharsTest, OnServer) {
  7772. Server svr;
  7773. svr.Get("/test_name", [&](const Request &req, Response &res) {
  7774. std::string header = "Not Set";
  7775. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7776. res.set_header(header, "value");
  7777. res.set_content("Page Content Page Content", "text/plain");
  7778. });
  7779. svr.Get("/test_value", [&](const Request &req, Response &res) {
  7780. std::string header = "Not Set";
  7781. if (req.has_param("header")) { header = req.get_param_value("header"); }
  7782. res.set_header("X-Test", header);
  7783. res.set_content("Page Content Page Content", "text/plain");
  7784. });
  7785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7786. auto se = detail::scope_exit([&] {
  7787. svr.stop();
  7788. thread.join();
  7789. ASSERT_FALSE(svr.is_running());
  7790. });
  7791. svr.wait_until_ready();
  7792. Client cli(HOST, PORT);
  7793. {
  7794. auto res = cli.Get(
  7795. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7796. ASSERT_TRUE(res);
  7797. EXPECT_EQ("Page Content Page Content", res->body);
  7798. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7799. }
  7800. {
  7801. auto res = cli.Get(
  7802. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  7803. ASSERT_TRUE(res);
  7804. EXPECT_EQ("Page Content Page Content", res->body);
  7805. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  7806. }
  7807. }
  7808. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  7809. auto handled = false;
  7810. Server svr;
  7811. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  7812. thread t = thread([&] { svr.listen(HOST, PORT); });
  7813. auto se = detail::scope_exit([&] {
  7814. svr.stop();
  7815. t.join();
  7816. ASSERT_FALSE(svr.is_running());
  7817. ASSERT_FALSE(handled);
  7818. });
  7819. svr.wait_until_ready();
  7820. auto req = "POST /test HTTP/1.1\r\n"
  7821. "Content-Length: x\r\n"
  7822. "\r\n";
  7823. std::string response;
  7824. ASSERT_TRUE(send_request(1, req, &response));
  7825. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  7826. response.substr(0, response.find("\r\n")));
  7827. }
  7828. #ifndef _WIN32
  7829. TEST(Expect100ContinueTest, ServerClosesConnection) {
  7830. static constexpr char reject[] = "Unauthorized";
  7831. static constexpr char accept[] = "Upload accepted";
  7832. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  7833. Server svr;
  7834. svr.set_expect_100_continue_handler(
  7835. [](const Request & /*req*/, Response &res) {
  7836. res.status = StatusCode::Unauthorized_401;
  7837. res.set_content(reject, "text/plain");
  7838. return res.status;
  7839. });
  7840. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  7841. res.set_content(accept, "text/plain");
  7842. });
  7843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7844. auto se = detail::scope_exit([&] {
  7845. svr.stop();
  7846. thread.join();
  7847. ASSERT_FALSE(svr.is_running());
  7848. });
  7849. svr.wait_until_ready();
  7850. {
  7851. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  7852. curl_easy_init(), &curl_easy_cleanup};
  7853. ASSERT_NE(curl, nullptr);
  7854. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  7855. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  7856. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  7857. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  7858. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  7859. &curl_slist_free_all};
  7860. ASSERT_NE(list, nullptr);
  7861. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  7862. struct read_data {
  7863. size_t read_size;
  7864. size_t total_size;
  7865. } data = {0, total_size};
  7866. using read_callback_t =
  7867. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7868. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  7869. void *userdata) -> size_t {
  7870. read_data *data = (read_data *)userdata;
  7871. if (!userdata || data->read_size >= data->total_size) { return 0; }
  7872. std::fill_n(ptr, size * nmemb, 'A');
  7873. data->read_size += size * nmemb;
  7874. return size * nmemb;
  7875. };
  7876. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  7877. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  7878. std::vector<char> buffer;
  7879. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  7880. using write_callback_t =
  7881. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  7882. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  7883. void *userdata) -> size_t {
  7884. std::vector<char> *buffer = (std::vector<char> *)userdata;
  7885. buffer->reserve(buffer->size() + size * nmemb + 1);
  7886. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  7887. return size * nmemb;
  7888. };
  7889. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  7890. {
  7891. const auto res = curl_easy_perform(curl.get());
  7892. ASSERT_EQ(res, CURLE_OK);
  7893. }
  7894. {
  7895. auto response_code = long{};
  7896. const auto res =
  7897. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  7898. ASSERT_EQ(res, CURLE_OK);
  7899. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  7900. }
  7901. {
  7902. auto dl = curl_off_t{};
  7903. const auto res =
  7904. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  7905. ASSERT_EQ(res, CURLE_OK);
  7906. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  7907. }
  7908. {
  7909. buffer.push_back('\0');
  7910. ASSERT_STRCASEEQ(buffer.data(), reject);
  7911. }
  7912. }
  7913. }
  7914. #endif
  7915. template <typename S, typename C>
  7916. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  7917. svr.Get("/stream", [&](const Request &, Response &res) {
  7918. auto data = new std::string("01234567890123456789");
  7919. res.set_content_provider(
  7920. data->size(), "text/plain",
  7921. [&, data](size_t offset, size_t length, DataSink &sink) {
  7922. const size_t DATA_CHUNK_SIZE = 4;
  7923. const auto &d = *data;
  7924. std::this_thread::sleep_for(std::chrono::seconds(1));
  7925. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  7926. return true;
  7927. },
  7928. [data](bool success) {
  7929. EXPECT_FALSE(success);
  7930. delete data;
  7931. });
  7932. });
  7933. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  7934. auto i = new size_t(0);
  7935. res.set_content_provider(
  7936. "text/plain",
  7937. [i](size_t, DataSink &sink) {
  7938. if (*i < 5) {
  7939. std::this_thread::sleep_for(std::chrono::seconds(1));
  7940. sink.write("abcd", 4);
  7941. (*i)++;
  7942. } else {
  7943. sink.done();
  7944. }
  7945. return true;
  7946. },
  7947. [i](bool success) {
  7948. EXPECT_FALSE(success);
  7949. delete i;
  7950. });
  7951. });
  7952. svr.Get("/chunked", [&](const Request &, Response &res) {
  7953. auto i = new size_t(0);
  7954. res.set_chunked_content_provider(
  7955. "text/plain",
  7956. [i](size_t, DataSink &sink) {
  7957. if (*i < 5) {
  7958. std::this_thread::sleep_for(std::chrono::seconds(1));
  7959. sink.os << "abcd";
  7960. (*i)++;
  7961. } else {
  7962. sink.done();
  7963. }
  7964. return true;
  7965. },
  7966. [i](bool success) {
  7967. EXPECT_FALSE(success);
  7968. delete i;
  7969. });
  7970. });
  7971. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7972. auto se = detail::scope_exit([&] {
  7973. svr.stop();
  7974. listen_thread.join();
  7975. ASSERT_FALSE(svr.is_running());
  7976. });
  7977. svr.wait_until_ready();
  7978. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  7979. {
  7980. auto start = std::chrono::steady_clock::now();
  7981. auto res = cli.Get("/stream");
  7982. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7983. std::chrono::steady_clock::now() - start)
  7984. .count();
  7985. ASSERT_FALSE(res);
  7986. EXPECT_EQ(Error::Read, res.error());
  7987. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7988. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  7989. }
  7990. {
  7991. auto start = std::chrono::steady_clock::now();
  7992. auto res = cli.Get("/stream_without_length");
  7993. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  7994. std::chrono::steady_clock::now() - start)
  7995. .count();
  7996. ASSERT_FALSE(res);
  7997. EXPECT_EQ(Error::Read, res.error());
  7998. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  7999. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8000. }
  8001. {
  8002. auto start = std::chrono::steady_clock::now();
  8003. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8004. EXPECT_EQ("abcd", string(data, data_length));
  8005. return true;
  8006. });
  8007. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8008. std::chrono::steady_clock::now() - start)
  8009. .count();
  8010. ASSERT_FALSE(res);
  8011. EXPECT_EQ(Error::Read, res.error());
  8012. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8013. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8014. }
  8015. }
  8016. TEST(MaxTimeoutTest, ContentStream) {
  8017. time_t timeout = 2000;
  8018. time_t threshold = 200;
  8019. Server svr;
  8020. Client cli("localhost", PORT);
  8021. max_timeout_test(svr, cli, timeout, threshold);
  8022. }
  8023. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8024. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8025. time_t timeout = 2000;
  8026. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8028. SSLClient cli("localhost", PORT);
  8029. cli.enable_server_certificate_verification(false);
  8030. max_timeout_test(svr, cli, timeout, threshold);
  8031. }
  8032. #endif
  8033. class EventDispatcher {
  8034. public:
  8035. EventDispatcher() {}
  8036. void wait_event(DataSink *sink) {
  8037. unique_lock<mutex> lk(m_);
  8038. int id = id_;
  8039. cv_.wait(lk, [&] { return cid_ == id; });
  8040. sink->write(message_.data(), message_.size());
  8041. }
  8042. void send_event(const string &message) {
  8043. lock_guard<mutex> lk(m_);
  8044. cid_ = id_++;
  8045. message_ = message;
  8046. cv_.notify_all();
  8047. }
  8048. private:
  8049. mutex m_;
  8050. condition_variable cv_;
  8051. atomic_int id_{0};
  8052. atomic_int cid_{-1};
  8053. string message_;
  8054. };
  8055. TEST(ClientInThreadTest, Issue2068) {
  8056. EventDispatcher ed;
  8057. Server svr;
  8058. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8059. res.set_chunked_content_provider("text/event-stream",
  8060. [&](size_t /*offset*/, DataSink &sink) {
  8061. ed.wait_event(&sink);
  8062. return true;
  8063. });
  8064. });
  8065. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8066. svr.wait_until_ready();
  8067. thread event_thread([&] {
  8068. int id = 0;
  8069. while (svr.is_running()) {
  8070. this_thread::sleep_for(chrono::milliseconds(500));
  8071. std::stringstream ss;
  8072. ss << "data: " << id << "\n\n";
  8073. ed.send_event(ss.str());
  8074. id++;
  8075. }
  8076. });
  8077. auto se = detail::scope_exit([&] {
  8078. svr.stop();
  8079. listen_thread.join();
  8080. event_thread.join();
  8081. ASSERT_FALSE(svr.is_running());
  8082. });
  8083. {
  8084. auto client = detail::make_unique<Client>(HOST, PORT);
  8085. client->set_read_timeout(std::chrono::minutes(10));
  8086. std::atomic<bool> stop{false};
  8087. std::thread t([&] {
  8088. client->Get("/event1",
  8089. [&](const char *, size_t) -> bool { return !stop; });
  8090. });
  8091. std::this_thread::sleep_for(std::chrono::seconds(2));
  8092. stop = true;
  8093. client->stop();
  8094. client.reset();
  8095. t.join();
  8096. }
  8097. }