test.cc 267 KB

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