test.cc 304 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  49. const char *key) {
  50. auto it = std::find_if(
  51. files.begin(), files.end(),
  52. [&](const MultipartFormData &file) { return file.name == key; });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != files.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. #ifndef _WIN32
  148. TEST(SocketStream, wait_writable_UNIX) {
  149. int fds[2];
  150. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  151. const auto asSocketStream = [&](socket_t fd,
  152. std::function<bool(Stream &)> func) {
  153. return detail::process_client_socket(
  154. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  155. };
  156. asSocketStream(fds[0], [&](Stream &s0) {
  157. EXPECT_EQ(s0.socket(), fds[0]);
  158. EXPECT_TRUE(s0.wait_writable());
  159. EXPECT_EQ(0, close(fds[1]));
  160. EXPECT_FALSE(s0.wait_writable());
  161. return true;
  162. });
  163. EXPECT_EQ(0, close(fds[0]));
  164. }
  165. TEST(SocketStream, wait_writable_INET) {
  166. sockaddr_in addr;
  167. memset(&addr, 0, sizeof(addr));
  168. addr.sin_family = AF_INET;
  169. addr.sin_port = htons(PORT + 1);
  170. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  171. int disconnected_svr_sock = -1;
  172. std::thread svr{[&] {
  173. const int s = socket(AF_INET, SOCK_STREAM, 0);
  174. ASSERT_LE(0, s);
  175. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  176. ASSERT_EQ(0, listen(s, 1));
  177. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  178. ASSERT_EQ(0, close(s));
  179. }};
  180. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  181. std::thread cli{[&] {
  182. const int s = socket(AF_INET, SOCK_STREAM, 0);
  183. ASSERT_LE(0, s);
  184. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  185. ASSERT_EQ(0, close(s));
  186. }};
  187. cli.join();
  188. svr.join();
  189. ASSERT_NE(disconnected_svr_sock, -1);
  190. const auto asSocketStream = [&](socket_t fd,
  191. std::function<bool(Stream &)> func) {
  192. return detail::process_client_socket(
  193. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  194. };
  195. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  196. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  197. EXPECT_FALSE(ss.wait_writable());
  198. return true;
  199. });
  200. ASSERT_EQ(0, close(disconnected_svr_sock));
  201. }
  202. #endif // #ifndef _WIN32
  203. TEST(ClientTest, MoveConstructible) {
  204. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  205. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  206. }
  207. TEST(ClientTest, MoveAssignable) {
  208. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  209. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  210. }
  211. #ifdef _WIN32
  212. TEST(StartupTest, WSAStartup) {
  213. WSADATA wsaData;
  214. int ret = WSAStartup(0x0002, &wsaData);
  215. ASSERT_EQ(0, ret);
  216. }
  217. #endif
  218. TEST(DecodeURLTest, PercentCharacter) {
  219. EXPECT_EQ(
  220. detail::decode_url(
  221. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  222. false),
  223. u8"descrip=Gastos áéíóúñÑ 6");
  224. }
  225. TEST(DecodeURLTest, PercentCharacterNUL) {
  226. string expected;
  227. expected.push_back('x');
  228. expected.push_back('\0');
  229. expected.push_back('x');
  230. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  231. }
  232. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  233. string unescapedCharacters = "-_.!~*'()";
  234. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  235. }
  236. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  237. string reservedCharacters = ";,/?:@&=+$";
  238. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  239. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  240. }
  241. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  242. string chineseCharacters = u8"中国語";
  243. string russianCharacters = u8"дом";
  244. string brazilianCharacters = u8"óculos";
  245. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  246. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  247. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  248. "%D0%B4%D0%BE%D0%BC");
  249. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  250. }
  251. TEST(TrimTests, TrimStringTests) {
  252. EXPECT_EQ("abc", detail::trim_copy("abc"));
  253. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  254. EXPECT_TRUE(detail::trim_copy("").empty());
  255. }
  256. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  257. // Simple case without quality values
  258. std::vector<std::string> result1;
  259. EXPECT_TRUE(detail::parse_accept_header(
  260. "text/html,application/json,text/plain", result1));
  261. EXPECT_EQ(result1.size(), 3U);
  262. EXPECT_EQ(result1[0], "text/html");
  263. EXPECT_EQ(result1[1], "application/json");
  264. EXPECT_EQ(result1[2], "text/plain");
  265. // With quality values
  266. std::vector<std::string> result2;
  267. EXPECT_TRUE(detail::parse_accept_header(
  268. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  269. EXPECT_EQ(result2.size(), 3U);
  270. EXPECT_EQ(result2[0], "application/json"); // highest q value
  271. EXPECT_EQ(result2[1], "text/html");
  272. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  273. }
  274. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  275. // Mixed with and without quality values
  276. std::vector<std::string> result;
  277. EXPECT_TRUE(detail::parse_accept_header(
  278. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  279. EXPECT_EQ(result.size(), 3U);
  280. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  281. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  282. EXPECT_EQ(result[2], "application/json"); // q=0.5
  283. }
  284. TEST(ParseAcceptHeaderTest, EdgeCases) {
  285. // Empty header
  286. std::vector<std::string> empty_result;
  287. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  288. EXPECT_TRUE(empty_result.empty());
  289. // Single type
  290. std::vector<std::string> single_result;
  291. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  292. EXPECT_EQ(single_result.size(), 1U);
  293. EXPECT_EQ(single_result[0], "application/json");
  294. // Wildcard types
  295. std::vector<std::string> wildcard_result;
  296. EXPECT_TRUE(detail::parse_accept_header(
  297. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  298. EXPECT_EQ(wildcard_result.size(), 3U);
  299. EXPECT_EQ(wildcard_result[0], "application/json");
  300. EXPECT_EQ(wildcard_result[1], "text/*");
  301. EXPECT_EQ(wildcard_result[2], "*/*");
  302. }
  303. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  304. // Common browser Accept header
  305. std::vector<std::string> browser_result;
  306. EXPECT_TRUE(
  307. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  308. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  309. browser_result));
  310. EXPECT_EQ(browser_result.size(), 6U);
  311. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  312. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  313. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  314. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  315. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  316. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  317. // API client header
  318. std::vector<std::string> api_result;
  319. EXPECT_TRUE(detail::parse_accept_header(
  320. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  321. api_result));
  322. EXPECT_EQ(api_result.size(), 3U);
  323. EXPECT_EQ(api_result[0], "application/json");
  324. EXPECT_EQ(api_result[1], "application/xml");
  325. EXPECT_EQ(api_result[2], "text/plain");
  326. }
  327. TEST(ParseAcceptHeaderTest, SpecialCases) {
  328. // Quality value with 3 decimal places
  329. std::vector<std::string> decimal_result;
  330. EXPECT_TRUE(detail::parse_accept_header(
  331. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  332. EXPECT_EQ(decimal_result.size(), 2U);
  333. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  334. EXPECT_EQ(decimal_result[1], "text/html");
  335. // Zero quality (should still be included but with lowest priority)
  336. std::vector<std::string> zero_q_result;
  337. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  338. zero_q_result));
  339. EXPECT_EQ(zero_q_result.size(), 2U);
  340. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  341. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  342. // No spaces around commas
  343. std::vector<std::string> no_space_result;
  344. EXPECT_TRUE(detail::parse_accept_header(
  345. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  346. no_space_result));
  347. EXPECT_EQ(no_space_result.size(), 3U);
  348. EXPECT_EQ(no_space_result[0], "text/html");
  349. EXPECT_EQ(no_space_result[1], "application/json");
  350. EXPECT_EQ(no_space_result[2], "text/plain");
  351. }
  352. TEST(ParseAcceptHeaderTest, InvalidCases) {
  353. std::vector<std::string> result;
  354. // Invalid quality value (> 1.0)
  355. EXPECT_FALSE(
  356. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  357. // Invalid quality value (< 0.0)
  358. EXPECT_FALSE(
  359. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  360. // Invalid quality value (not a number)
  361. EXPECT_FALSE(detail::parse_accept_header(
  362. "text/html;q=invalid,application/json", result));
  363. // Empty quality value
  364. EXPECT_FALSE(
  365. detail::parse_accept_header("text/html;q=,application/json", result));
  366. // Invalid media type format (no slash and not wildcard)
  367. EXPECT_FALSE(
  368. detail::parse_accept_header("invalidtype,application/json", result));
  369. // Empty media type
  370. result.clear();
  371. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  372. // Only commas
  373. result.clear();
  374. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  375. // Valid cases should still work
  376. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  377. EXPECT_EQ(result.size(), 1U);
  378. EXPECT_EQ(result[0], "*/*");
  379. EXPECT_TRUE(detail::parse_accept_header("*", result));
  380. EXPECT_EQ(result.size(), 1U);
  381. EXPECT_EQ(result[0], "*");
  382. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  383. EXPECT_EQ(result.size(), 1U);
  384. EXPECT_EQ(result[0], "text/*");
  385. }
  386. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  387. Server svr;
  388. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  389. EXPECT_EQ(req.accept_content_types.size(), 3U);
  390. EXPECT_EQ(req.accept_content_types[0], "application/json");
  391. EXPECT_EQ(req.accept_content_types[1], "text/html");
  392. EXPECT_EQ(req.accept_content_types[2], "*/*");
  393. res.set_content("ok", "text/plain");
  394. });
  395. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  396. EXPECT_TRUE(false);
  397. res.set_content("bad request", "text/plain");
  398. });
  399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  400. auto se = detail::scope_exit([&] {
  401. svr.stop();
  402. listen_thread.join();
  403. ASSERT_FALSE(svr.is_running());
  404. });
  405. svr.wait_until_ready();
  406. Client cli("localhost", PORT);
  407. {
  408. auto res =
  409. cli.Get("/accept_ok",
  410. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  411. ASSERT_TRUE(res);
  412. EXPECT_EQ(StatusCode::OK_200, res->status);
  413. }
  414. {
  415. auto res = cli.Get("/accept_bad_request",
  416. {{"Accept", "text/html;q=abc,application/json"}});
  417. ASSERT_TRUE(res);
  418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  419. }
  420. }
  421. TEST(DivideTest, DivideStringTests) {
  422. auto divide = [](const std::string &str, char d) {
  423. std::string lhs;
  424. std::string rhs;
  425. detail::divide(str, d,
  426. [&](const char *lhs_data, std::size_t lhs_size,
  427. const char *rhs_data, std::size_t rhs_size) {
  428. lhs.assign(lhs_data, lhs_size);
  429. rhs.assign(rhs_data, rhs_size);
  430. });
  431. return std::make_pair(std::move(lhs), std::move(rhs));
  432. };
  433. {
  434. const auto res = divide("", '=');
  435. EXPECT_EQ(res.first, "");
  436. EXPECT_EQ(res.second, "");
  437. }
  438. {
  439. const auto res = divide("=", '=');
  440. EXPECT_EQ(res.first, "");
  441. EXPECT_EQ(res.second, "");
  442. }
  443. {
  444. const auto res = divide(" ", '=');
  445. EXPECT_EQ(res.first, " ");
  446. EXPECT_EQ(res.second, "");
  447. }
  448. {
  449. const auto res = divide("a", '=');
  450. EXPECT_EQ(res.first, "a");
  451. EXPECT_EQ(res.second, "");
  452. }
  453. {
  454. const auto res = divide("a=", '=');
  455. EXPECT_EQ(res.first, "a");
  456. EXPECT_EQ(res.second, "");
  457. }
  458. {
  459. const auto res = divide("=b", '=');
  460. EXPECT_EQ(res.first, "");
  461. EXPECT_EQ(res.second, "b");
  462. }
  463. {
  464. const auto res = divide("a=b", '=');
  465. EXPECT_EQ(res.first, "a");
  466. EXPECT_EQ(res.second, "b");
  467. }
  468. {
  469. const auto res = divide("a=b=", '=');
  470. EXPECT_EQ(res.first, "a");
  471. EXPECT_EQ(res.second, "b=");
  472. }
  473. {
  474. const auto res = divide("a=b=c", '=');
  475. EXPECT_EQ(res.first, "a");
  476. EXPECT_EQ(res.second, "b=c");
  477. }
  478. }
  479. TEST(SplitTest, ParseQueryString) {
  480. string s = "key1=val1&key2=val2&key3=val3";
  481. Params dic;
  482. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  483. [&](const char *b, const char *e) {
  484. string key, val;
  485. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  486. if (key.empty()) {
  487. key.assign(b2, e2);
  488. } else {
  489. val.assign(b2, e2);
  490. }
  491. });
  492. dic.emplace(key, val);
  493. });
  494. EXPECT_EQ("val1", dic.find("key1")->second);
  495. EXPECT_EQ("val2", dic.find("key2")->second);
  496. EXPECT_EQ("val3", dic.find("key3")->second);
  497. }
  498. TEST(SplitTest, ParseInvalidQueryTests) {
  499. {
  500. string s = " ";
  501. Params dict;
  502. detail::parse_query_text(s, dict);
  503. EXPECT_TRUE(dict.empty());
  504. }
  505. {
  506. string s = " = =";
  507. Params dict;
  508. detail::parse_query_text(s, dict);
  509. EXPECT_TRUE(dict.empty());
  510. }
  511. }
  512. TEST(ParseQueryTest, ParseQueryString) {
  513. {
  514. std::string s = "key1=val1&key2=val2&key3=val3";
  515. Params dic;
  516. detail::parse_query_text(s, dic);
  517. EXPECT_EQ("val1", dic.find("key1")->second);
  518. EXPECT_EQ("val2", dic.find("key2")->second);
  519. EXPECT_EQ("val3", dic.find("key3")->second);
  520. }
  521. {
  522. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  523. Params dic;
  524. detail::parse_query_text(s, dic);
  525. EXPECT_EQ("", dic.find("key1")->second);
  526. EXPECT_EQ("val1", dic.find("key2")->second);
  527. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  528. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  529. }
  530. }
  531. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  532. Params dic;
  533. EXPECT_EQ(detail::params_to_query_str(dic), "");
  534. dic.emplace("key1", "val1");
  535. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  536. dic.emplace("key2", "val2");
  537. dic.emplace("key3", "val3");
  538. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  539. }
  540. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  541. string content_type = "multipart/form-data; boundary=something";
  542. string boundary;
  543. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  544. EXPECT_TRUE(ret);
  545. EXPECT_EQ(boundary, "something");
  546. }
  547. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  548. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  549. string boundary;
  550. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  551. EXPECT_TRUE(ret);
  552. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  553. }
  554. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  555. string content_type =
  556. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  557. string boundary;
  558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  559. EXPECT_TRUE(ret);
  560. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  561. }
  562. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  563. string content_type =
  564. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  565. string boundary;
  566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  567. EXPECT_TRUE(ret);
  568. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  569. }
  570. TEST(GetHeaderValueTest, DefaultValue) {
  571. Headers headers = {{"Dummy", "Dummy"}};
  572. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  573. EXPECT_STREQ("text/plain", val);
  574. }
  575. TEST(GetHeaderValueTest, DefaultValueInt) {
  576. Headers headers = {{"Dummy", "Dummy"}};
  577. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  578. EXPECT_EQ(100ull, val);
  579. }
  580. TEST(GetHeaderValueTest, RegularValue) {
  581. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  582. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  583. EXPECT_STREQ("text/html", val);
  584. }
  585. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  586. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  587. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  588. EXPECT_STREQ("text/html", val);
  589. }
  590. TEST(GetHeaderValueTest, SetContent) {
  591. Response res;
  592. res.set_content("html", "text/html");
  593. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  594. res.set_content("text", "text/plain");
  595. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  596. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  597. }
  598. TEST(GetHeaderValueTest, RegularValueInt) {
  599. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  600. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  601. EXPECT_EQ(100ull, val);
  602. }
  603. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  604. Headers headers = {{"Content-Length", "x"}};
  605. auto is_invalid_value = false;
  606. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  607. is_invalid_value);
  608. EXPECT_EQ(0ull, val);
  609. EXPECT_TRUE(is_invalid_value);
  610. }
  611. TEST(GetHeaderValueTest, Range) {
  612. {
  613. Headers headers = {make_range_header({{1, -1}})};
  614. auto val = detail::get_header_value(headers, "Range", 0, 0);
  615. EXPECT_STREQ("bytes=1-", val);
  616. }
  617. {
  618. Headers headers = {make_range_header({{-1, 1}})};
  619. auto val = detail::get_header_value(headers, "Range", 0, 0);
  620. EXPECT_STREQ("bytes=-1", val);
  621. }
  622. {
  623. Headers headers = {make_range_header({{1, 10}})};
  624. auto val = detail::get_header_value(headers, "Range", 0, 0);
  625. EXPECT_STREQ("bytes=1-10", val);
  626. }
  627. {
  628. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  629. auto val = detail::get_header_value(headers, "Range", 0, 0);
  630. EXPECT_STREQ("bytes=1-10, 100-", val);
  631. }
  632. {
  633. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  634. auto val = detail::get_header_value(headers, "Range", 0, 0);
  635. EXPECT_STREQ("bytes=1-10, 100-200", val);
  636. }
  637. {
  638. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  639. auto val = detail::get_header_value(headers, "Range", 0, 0);
  640. EXPECT_STREQ("bytes=0-0, -1", val);
  641. }
  642. }
  643. TEST(ParseHeaderValueTest, Range) {
  644. {
  645. Ranges ranges;
  646. auto ret = detail::parse_range_header("bytes=1-", ranges);
  647. EXPECT_TRUE(ret);
  648. EXPECT_EQ(1u, ranges.size());
  649. EXPECT_EQ(1u, ranges[0].first);
  650. EXPECT_EQ(-1, ranges[0].second);
  651. }
  652. {
  653. Ranges ranges;
  654. auto ret = detail::parse_range_header("bytes=-1", ranges);
  655. EXPECT_TRUE(ret);
  656. EXPECT_EQ(1u, ranges.size());
  657. EXPECT_EQ(-1, ranges[0].first);
  658. EXPECT_EQ(1u, ranges[0].second);
  659. }
  660. {
  661. Ranges ranges;
  662. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  663. EXPECT_TRUE(ret);
  664. EXPECT_EQ(1u, ranges.size());
  665. EXPECT_EQ(1u, ranges[0].first);
  666. EXPECT_EQ(10u, ranges[0].second);
  667. }
  668. {
  669. Ranges ranges;
  670. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  671. EXPECT_FALSE(ret);
  672. }
  673. {
  674. Ranges ranges;
  675. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  676. EXPECT_TRUE(ret);
  677. EXPECT_EQ(2u, ranges.size());
  678. EXPECT_EQ(1u, ranges[0].first);
  679. EXPECT_EQ(10u, ranges[0].second);
  680. EXPECT_EQ(100u, ranges[1].first);
  681. EXPECT_EQ(-1, ranges[1].second);
  682. }
  683. {
  684. Ranges ranges;
  685. auto ret =
  686. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  687. EXPECT_TRUE(ret);
  688. EXPECT_EQ(3u, ranges.size());
  689. EXPECT_EQ(1u, ranges[0].first);
  690. EXPECT_EQ(10u, ranges[0].second);
  691. EXPECT_EQ(100u, ranges[1].first);
  692. EXPECT_EQ(200u, ranges[1].second);
  693. EXPECT_EQ(300u, ranges[2].first);
  694. EXPECT_EQ(400u, ranges[2].second);
  695. }
  696. {
  697. Ranges ranges;
  698. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  699. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  700. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  701. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  702. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  703. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  704. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  705. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  706. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  707. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  708. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  709. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  710. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  711. EXPECT_TRUE(ranges.empty());
  712. }
  713. }
  714. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  715. Request req;
  716. req.set_header("Accept-Encoding", "gzip");
  717. Response res;
  718. res.set_header("Content-Type", "text/plain");
  719. auto ret = detail::encoding_type(req, res);
  720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  721. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  722. #else
  723. EXPECT_TRUE(ret == detail::EncodingType::None);
  724. #endif
  725. }
  726. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  727. Request req;
  728. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  729. Response res;
  730. res.set_header("Content-Type", "text/plain");
  731. auto ret = detail::encoding_type(req, res);
  732. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  733. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  734. #elif CPPHTTPLIB_ZLIB_SUPPORT
  735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  736. #elif CPPHTTPLIB_ZSTD_SUPPORT
  737. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  738. #else
  739. EXPECT_TRUE(ret == detail::EncodingType::None);
  740. #endif
  741. }
  742. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  743. Request req;
  744. req.set_header("Accept-Encoding",
  745. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  746. Response res;
  747. res.set_header("Content-Type", "text/plain");
  748. auto ret = detail::encoding_type(req, res);
  749. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  750. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  751. #elif CPPHTTPLIB_ZLIB_SUPPORT
  752. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  753. #elif CPPHTTPLIB_ZSTD_SUPPORT
  754. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  755. #else
  756. EXPECT_TRUE(ret == detail::EncodingType::None);
  757. #endif
  758. }
  759. TEST(BufferStreamTest, read) {
  760. detail::BufferStream strm1;
  761. Stream &strm = strm1;
  762. EXPECT_EQ(5, strm.write("hello"));
  763. char buf[512];
  764. EXPECT_EQ(2, strm.read(buf, 2));
  765. EXPECT_EQ('h', buf[0]);
  766. EXPECT_EQ('e', buf[1]);
  767. EXPECT_EQ(2, strm.read(buf, 2));
  768. EXPECT_EQ('l', buf[0]);
  769. EXPECT_EQ('l', buf[1]);
  770. EXPECT_EQ(1, strm.read(buf, 1));
  771. EXPECT_EQ('o', buf[0]);
  772. EXPECT_EQ(0, strm.read(buf, 1));
  773. }
  774. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  775. auto host = "www.httpwatch.com";
  776. auto ip = hosted_at(host);
  777. EXPECT_EQ("23.96.13.243", ip);
  778. std::vector<std::string> addrs;
  779. hosted_at(host, addrs);
  780. EXPECT_EQ(1u, addrs.size());
  781. }
  782. #if 0 // It depends on each test environment...
  783. TEST(HostnameToIPConversionTest, YouTube_Online) {
  784. auto host = "www.youtube.com";
  785. std::vector<std::string> addrs;
  786. hosted_at(host, addrs);
  787. EXPECT_EQ(20u, addrs.size());
  788. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  789. EXPECT_TRUE(it != addrs.end());
  790. }
  791. #endif
  792. class ChunkedEncodingTest : public ::testing::Test {
  793. protected:
  794. ChunkedEncodingTest()
  795. : cli_(HOST, PORT)
  796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  797. ,
  798. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  799. #endif
  800. {
  801. cli_.set_connection_timeout(2);
  802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  803. cli_.enable_server_certificate_verification(false);
  804. #endif
  805. }
  806. virtual void SetUp() {
  807. read_file("./image.jpg", image_data_);
  808. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  809. res.set_content("Hello World!", "text/plain");
  810. });
  811. svr_.Get(
  812. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  813. res.set_chunked_content_provider(
  814. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  815. size_t remaining = image_data_.size() - offset;
  816. if (remaining == 0) {
  817. sink.done();
  818. } else {
  819. constexpr size_t CHUNK_SIZE = 1024;
  820. size_t send_size = std::min(CHUNK_SIZE, remaining);
  821. sink.write(&image_data_[offset], send_size);
  822. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  823. }
  824. return true;
  825. });
  826. });
  827. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  828. svr_.wait_until_ready();
  829. }
  830. virtual void TearDown() {
  831. svr_.stop();
  832. if (!request_threads_.empty()) {
  833. std::this_thread::sleep_for(std::chrono::seconds(1));
  834. for (auto &t : request_threads_) {
  835. t.join();
  836. }
  837. }
  838. t_.join();
  839. }
  840. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  841. SSLClient cli_;
  842. SSLServer svr_;
  843. #else
  844. Client cli_;
  845. Server svr_;
  846. #endif
  847. thread t_;
  848. std::vector<thread> request_threads_;
  849. std::string image_data_;
  850. };
  851. TEST_F(ChunkedEncodingTest, NormalGet) {
  852. auto res = cli_.Get("/chunked");
  853. ASSERT_TRUE(res);
  854. std::string out;
  855. read_file("./image.jpg", out);
  856. EXPECT_EQ(StatusCode::OK_200, res->status);
  857. EXPECT_EQ(out, res->body);
  858. }
  859. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  860. std::string body;
  861. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  862. body.append(data, data_length);
  863. return true;
  864. });
  865. ASSERT_TRUE(res);
  866. std::string out;
  867. read_file("./image.jpg", out);
  868. EXPECT_EQ(StatusCode::OK_200, res->status);
  869. EXPECT_EQ(out, body);
  870. }
  871. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  872. std::string body;
  873. auto res = cli_.Get(
  874. "/chunked",
  875. [&](const Response &response) {
  876. EXPECT_EQ(StatusCode::OK_200, response.status);
  877. return true;
  878. },
  879. [&](const char *data, size_t data_length) {
  880. body.append(data, data_length);
  881. return true;
  882. });
  883. ASSERT_TRUE(res);
  884. std::string out;
  885. read_file("./image.jpg", out);
  886. EXPECT_EQ(StatusCode::OK_200, res->status);
  887. EXPECT_EQ(out, body);
  888. }
  889. TEST(RangeTest, FromHTTPBin_Online) {
  890. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  891. auto host = "httpbin.org";
  892. auto path = std::string{"/range/32"};
  893. #else
  894. auto host = "nghttp2.org";
  895. auto path = std::string{"/httpbin/range/32"};
  896. #endif
  897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  898. auto port = 443;
  899. SSLClient cli(host, port);
  900. #else
  901. auto port = 80;
  902. Client cli(host, port);
  903. #endif
  904. cli.set_connection_timeout(5);
  905. {
  906. auto res = cli.Get(path);
  907. ASSERT_TRUE(res);
  908. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  909. EXPECT_EQ(StatusCode::OK_200, res->status);
  910. }
  911. {
  912. Headers headers = {make_range_header({{1, -1}})};
  913. auto res = cli.Get(path, headers);
  914. ASSERT_TRUE(res);
  915. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  917. }
  918. {
  919. Headers headers = {make_range_header({{1, 10}})};
  920. auto res = cli.Get(path, headers);
  921. ASSERT_TRUE(res);
  922. EXPECT_EQ("bcdefghijk", res->body);
  923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  924. }
  925. {
  926. Headers headers = {make_range_header({{0, 31}})};
  927. auto res = cli.Get(path, headers);
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  930. EXPECT_EQ(StatusCode::OK_200, res->status);
  931. }
  932. {
  933. Headers headers = {make_range_header({{0, -1}})};
  934. auto res = cli.Get(path, headers);
  935. ASSERT_TRUE(res);
  936. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  937. EXPECT_EQ(StatusCode::OK_200, res->status);
  938. }
  939. {
  940. Headers headers = {make_range_header({{0, 32}})};
  941. auto res = cli.Get(path, headers);
  942. ASSERT_TRUE(res);
  943. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  944. }
  945. }
  946. TEST(ConnectionErrorTest, InvalidHost) {
  947. auto host = "-abcde.com";
  948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  949. auto port = 443;
  950. SSLClient cli(host, port);
  951. #else
  952. auto port = 80;
  953. Client cli(host, port);
  954. #endif
  955. cli.set_connection_timeout(std::chrono::seconds(2));
  956. auto res = cli.Get("/");
  957. ASSERT_TRUE(!res);
  958. EXPECT_EQ(Error::Connection, res.error());
  959. }
  960. TEST(ConnectionErrorTest, InvalidHost2) {
  961. auto host = "httpbin.org/";
  962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  963. SSLClient cli(host);
  964. #else
  965. Client cli(host);
  966. #endif
  967. cli.set_connection_timeout(std::chrono::seconds(2));
  968. auto res = cli.Get("/");
  969. ASSERT_TRUE(!res);
  970. EXPECT_EQ(Error::Connection, res.error());
  971. }
  972. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  973. auto host = "httpbin.org/";
  974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  975. SSLClient cli(host);
  976. #else
  977. Client cli(host);
  978. #endif
  979. cli.set_connection_timeout(std::chrono::seconds(2));
  980. auto res = cli.Get("/");
  981. ASSERT_TRUE(!res);
  982. stringstream s;
  983. s << "error code: " << res.error();
  984. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  985. }
  986. TEST(ConnectionErrorTest, InvalidPort) {
  987. auto host = "localhost";
  988. auto port = 44380;
  989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  990. SSLClient cli(host, port);
  991. #else
  992. Client cli(host, port);
  993. #endif
  994. cli.set_connection_timeout(std::chrono::seconds(2));
  995. auto res = cli.Get("/");
  996. ASSERT_TRUE(!res);
  997. EXPECT_TRUE(Error::Connection == res.error() ||
  998. Error::ConnectionTimeout == res.error());
  999. }
  1000. TEST(ConnectionErrorTest, Timeout_Online) {
  1001. auto host = "google.com";
  1002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1003. auto port = 44380;
  1004. SSLClient cli(host, port);
  1005. #else
  1006. auto port = 8080;
  1007. Client cli(host, port);
  1008. #endif
  1009. cli.set_connection_timeout(std::chrono::seconds(2));
  1010. // only probe one address type so that the error reason
  1011. // correlates to the timed-out IPv4, not the unsupported
  1012. // IPv6 connection attempt
  1013. cli.set_address_family(AF_INET);
  1014. auto res = cli.Get("/");
  1015. ASSERT_TRUE(!res);
  1016. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1017. }
  1018. TEST(CancelTest, NoCancel_Online) {
  1019. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1020. auto host = "httpbin.org";
  1021. auto path = std::string{"/range/32"};
  1022. #else
  1023. auto host = "nghttp2.org";
  1024. auto path = std::string{"/httpbin/range/32"};
  1025. #endif
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. auto port = 443;
  1028. SSLClient cli(host, port);
  1029. #else
  1030. auto port = 80;
  1031. Client cli(host, port);
  1032. #endif
  1033. cli.set_connection_timeout(std::chrono::seconds(5));
  1034. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1035. ASSERT_TRUE(res);
  1036. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1037. EXPECT_EQ(StatusCode::OK_200, res->status);
  1038. }
  1039. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1040. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1041. auto host = "httpbin.org";
  1042. auto path = std::string{"/range/32"};
  1043. #else
  1044. auto host = "nghttp2.org";
  1045. auto path = std::string{"/httpbin/range/32"};
  1046. #endif
  1047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1048. auto port = 443;
  1049. SSLClient cli(host, port);
  1050. #else
  1051. auto port = 80;
  1052. Client cli(host, port);
  1053. #endif
  1054. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1055. cli.set_connection_timeout(std::chrono::seconds(5));
  1056. ASSERT_TRUE(!res);
  1057. EXPECT_EQ(Error::Canceled, res.error());
  1058. }
  1059. TEST(CancelTest, WithCancelLargePayload_Online) {
  1060. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1061. auto host = "httpbin.org";
  1062. auto path = std::string{"/range/65536"};
  1063. #else
  1064. auto host = "nghttp2.org";
  1065. auto path = std::string{"/httpbin/range/65536"};
  1066. #endif
  1067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1068. auto port = 443;
  1069. SSLClient cli(host, port);
  1070. #else
  1071. auto port = 80;
  1072. Client cli(host, port);
  1073. #endif
  1074. cli.set_connection_timeout(std::chrono::seconds(5));
  1075. uint32_t count = 0;
  1076. auto res =
  1077. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1078. ASSERT_TRUE(!res);
  1079. EXPECT_EQ(Error::Canceled, res.error());
  1080. }
  1081. TEST(CancelTest, NoCancelPost) {
  1082. Server svr;
  1083. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1084. res.set_content("Hello World!", "text/plain");
  1085. });
  1086. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1087. auto se = detail::scope_exit([&] {
  1088. svr.stop();
  1089. thread.join();
  1090. ASSERT_FALSE(svr.is_running());
  1091. });
  1092. svr.wait_until_ready();
  1093. Client cli(HOST, PORT);
  1094. cli.set_connection_timeout(std::chrono::seconds(5));
  1095. auto res =
  1096. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1097. "application/json", [](uint64_t, uint64_t) { return true; });
  1098. ASSERT_TRUE(res);
  1099. EXPECT_EQ("Hello World!", res->body);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. }
  1102. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1103. Server svr;
  1104. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1105. res.set_content("Hello World!", "text/plain");
  1106. });
  1107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1108. auto se = detail::scope_exit([&] {
  1109. svr.stop();
  1110. thread.join();
  1111. ASSERT_FALSE(svr.is_running());
  1112. });
  1113. svr.wait_until_ready();
  1114. Client cli(HOST, PORT);
  1115. cli.set_connection_timeout(std::chrono::seconds(5));
  1116. auto res =
  1117. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1118. "application/json", [](uint64_t, uint64_t) { return false; });
  1119. ASSERT_TRUE(!res);
  1120. EXPECT_EQ(Error::Canceled, res.error());
  1121. }
  1122. TEST(CancelTest, WithCancelLargePayloadPost) {
  1123. Server svr;
  1124. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1125. res.set_content(LARGE_DATA, "text/plain");
  1126. });
  1127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1128. auto se = detail::scope_exit([&] {
  1129. svr.stop();
  1130. thread.join();
  1131. ASSERT_FALSE(svr.is_running());
  1132. });
  1133. svr.wait_until_ready();
  1134. Client cli(HOST, PORT);
  1135. cli.set_connection_timeout(std::chrono::seconds(5));
  1136. auto res =
  1137. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1138. "application/json", [](uint64_t, uint64_t) { return false; });
  1139. ASSERT_TRUE(!res);
  1140. EXPECT_EQ(Error::Canceled, res.error());
  1141. }
  1142. TEST(CancelTest, NoCancelPut) {
  1143. Server svr;
  1144. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1145. res.set_content("Hello World!", "text/plain");
  1146. });
  1147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1148. auto se = detail::scope_exit([&] {
  1149. svr.stop();
  1150. thread.join();
  1151. ASSERT_FALSE(svr.is_running());
  1152. });
  1153. svr.wait_until_ready();
  1154. Client cli(HOST, PORT);
  1155. cli.set_connection_timeout(std::chrono::seconds(5));
  1156. auto res =
  1157. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1158. "application/json", [](uint64_t, uint64_t) { return true; });
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("Hello World!", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1164. Server svr;
  1165. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1166. res.set_content("Hello World!", "text/plain");
  1167. });
  1168. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1169. auto se = detail::scope_exit([&] {
  1170. svr.stop();
  1171. thread.join();
  1172. ASSERT_FALSE(svr.is_running());
  1173. });
  1174. svr.wait_until_ready();
  1175. Client cli(HOST, PORT);
  1176. cli.set_connection_timeout(std::chrono::seconds(5));
  1177. auto res =
  1178. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1179. "application/json", [](uint64_t, uint64_t) { return false; });
  1180. ASSERT_TRUE(!res);
  1181. EXPECT_EQ(Error::Canceled, res.error());
  1182. }
  1183. TEST(CancelTest, WithCancelLargePayloadPut) {
  1184. Server svr;
  1185. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1186. res.set_content(LARGE_DATA, "text/plain");
  1187. });
  1188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1189. auto se = detail::scope_exit([&] {
  1190. svr.stop();
  1191. thread.join();
  1192. ASSERT_FALSE(svr.is_running());
  1193. });
  1194. svr.wait_until_ready();
  1195. Client cli(HOST, PORT);
  1196. cli.set_connection_timeout(std::chrono::seconds(5));
  1197. auto res =
  1198. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1199. "application/json", [](uint64_t, uint64_t) { return false; });
  1200. ASSERT_TRUE(!res);
  1201. EXPECT_EQ(Error::Canceled, res.error());
  1202. }
  1203. TEST(CancelTest, NoCancelPatch) {
  1204. Server svr;
  1205. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1206. res.set_content("Hello World!", "text/plain");
  1207. });
  1208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. thread.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. Client cli(HOST, PORT);
  1216. cli.set_connection_timeout(std::chrono::seconds(5));
  1217. auto res =
  1218. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1219. "application/json", [](uint64_t, uint64_t) { return true; });
  1220. ASSERT_TRUE(res);
  1221. EXPECT_EQ("Hello World!", res->body);
  1222. EXPECT_EQ(StatusCode::OK_200, res->status);
  1223. }
  1224. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1225. Server svr;
  1226. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1227. res.set_content("Hello World!", "text/plain");
  1228. });
  1229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1230. auto se = detail::scope_exit([&] {
  1231. svr.stop();
  1232. thread.join();
  1233. ASSERT_FALSE(svr.is_running());
  1234. });
  1235. svr.wait_until_ready();
  1236. Client cli(HOST, PORT);
  1237. cli.set_connection_timeout(std::chrono::seconds(5));
  1238. auto res =
  1239. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1240. "application/json", [](uint64_t, uint64_t) { return false; });
  1241. ASSERT_TRUE(!res);
  1242. EXPECT_EQ(Error::Canceled, res.error());
  1243. }
  1244. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1245. Server svr;
  1246. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1247. res.set_content(LARGE_DATA, "text/plain");
  1248. });
  1249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1250. auto se = detail::scope_exit([&] {
  1251. svr.stop();
  1252. thread.join();
  1253. ASSERT_FALSE(svr.is_running());
  1254. });
  1255. svr.wait_until_ready();
  1256. Client cli(HOST, PORT);
  1257. cli.set_connection_timeout(std::chrono::seconds(5));
  1258. auto res =
  1259. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1260. "application/json", [](uint64_t, uint64_t) { return false; });
  1261. ASSERT_TRUE(!res);
  1262. EXPECT_EQ(Error::Canceled, res.error());
  1263. }
  1264. TEST(CancelTest, NoCancelDelete) {
  1265. Server svr;
  1266. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1267. res.set_content("Hello World!", "text/plain");
  1268. });
  1269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1270. auto se = detail::scope_exit([&] {
  1271. svr.stop();
  1272. thread.join();
  1273. ASSERT_FALSE(svr.is_running());
  1274. });
  1275. svr.wait_until_ready();
  1276. Client cli(HOST, PORT);
  1277. cli.set_connection_timeout(std::chrono::seconds(5));
  1278. auto res =
  1279. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1280. "application/json", [](uint64_t, uint64_t) { return true; });
  1281. ASSERT_TRUE(res);
  1282. EXPECT_EQ("Hello World!", res->body);
  1283. EXPECT_EQ(StatusCode::OK_200, res->status);
  1284. }
  1285. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1286. Server svr;
  1287. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1288. res.set_content("Hello World!", "text/plain");
  1289. });
  1290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1291. auto se = detail::scope_exit([&] {
  1292. svr.stop();
  1293. thread.join();
  1294. ASSERT_FALSE(svr.is_running());
  1295. });
  1296. svr.wait_until_ready();
  1297. Client cli(HOST, PORT);
  1298. cli.set_connection_timeout(std::chrono::seconds(5));
  1299. auto res =
  1300. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1301. "application/json", [](uint64_t, uint64_t) { return false; });
  1302. ASSERT_TRUE(!res);
  1303. EXPECT_EQ(Error::Canceled, res.error());
  1304. }
  1305. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1306. Server svr;
  1307. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1308. res.set_content(LARGE_DATA, "text/plain");
  1309. });
  1310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1311. auto se = detail::scope_exit([&] {
  1312. svr.stop();
  1313. thread.join();
  1314. ASSERT_FALSE(svr.is_running());
  1315. });
  1316. svr.wait_until_ready();
  1317. Client cli(HOST, PORT);
  1318. cli.set_connection_timeout(std::chrono::seconds(5));
  1319. auto res =
  1320. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1321. "application/json", [](uint64_t, uint64_t) { return false; });
  1322. ASSERT_TRUE(!res);
  1323. EXPECT_EQ(Error::Canceled, res.error());
  1324. }
  1325. static std::string remove_whitespace(const std::string &input) {
  1326. std::string output;
  1327. output.reserve(input.size());
  1328. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1329. [](unsigned char c) { return !std::isspace(c); });
  1330. return output;
  1331. }
  1332. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1333. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1334. auto host = "httpbin.org";
  1335. auto path = std::string{"/basic-auth/hello/world"};
  1336. #else
  1337. auto host = "nghttp2.org";
  1338. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1339. #endif
  1340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1341. auto port = 443;
  1342. SSLClient cli(host, port);
  1343. #else
  1344. auto port = 80;
  1345. Client cli(host, port);
  1346. #endif
  1347. {
  1348. auto res = cli.Get(path);
  1349. ASSERT_TRUE(res);
  1350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1351. }
  1352. {
  1353. auto res =
  1354. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1355. ASSERT_TRUE(res);
  1356. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1357. remove_whitespace(res->body));
  1358. EXPECT_EQ(StatusCode::OK_200, res->status);
  1359. }
  1360. {
  1361. cli.set_basic_auth("hello", "world");
  1362. auto res = cli.Get(path);
  1363. ASSERT_TRUE(res);
  1364. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1365. remove_whitespace(res->body));
  1366. EXPECT_EQ(StatusCode::OK_200, res->status);
  1367. }
  1368. {
  1369. cli.set_basic_auth("hello", "bad");
  1370. auto res = cli.Get(path);
  1371. ASSERT_TRUE(res);
  1372. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1373. }
  1374. {
  1375. cli.set_basic_auth("bad", "world");
  1376. auto res = cli.Get(path);
  1377. ASSERT_TRUE(res);
  1378. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1379. }
  1380. }
  1381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1382. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1383. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1384. auto host = "httpbin.org";
  1385. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1386. auto paths = std::vector<std::string>{
  1387. "/digest-auth/auth/hello/world/MD5",
  1388. "/digest-auth/auth/hello/world/SHA-256",
  1389. "/digest-auth/auth/hello/world/SHA-512",
  1390. "/digest-auth/auth-int/hello/world/MD5",
  1391. };
  1392. #else
  1393. auto host = "nghttp2.org";
  1394. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1395. auto paths = std::vector<std::string>{
  1396. "/httpbin/digest-auth/auth/hello/world/MD5",
  1397. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1398. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1399. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1400. };
  1401. #endif
  1402. auto port = 443;
  1403. SSLClient cli(host, port);
  1404. {
  1405. auto res = cli.Get(unauth_path);
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1408. }
  1409. {
  1410. cli.set_digest_auth("hello", "world");
  1411. for (const auto &path : paths) {
  1412. auto res = cli.Get(path.c_str());
  1413. ASSERT_TRUE(res);
  1414. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1415. remove_whitespace(res->body));
  1416. EXPECT_EQ(StatusCode::OK_200, res->status);
  1417. }
  1418. cli.set_digest_auth("hello", "bad");
  1419. for (const auto &path : paths) {
  1420. auto res = cli.Get(path.c_str());
  1421. ASSERT_TRUE(res);
  1422. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1423. }
  1424. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1425. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1426. // cli.set_digest_auth("bad", "world");
  1427. // for (const auto& path : paths) {
  1428. // auto res = cli.Get(path.c_str());
  1429. // ASSERT_TRUE(res);
  1430. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1431. // }
  1432. }
  1433. }
  1434. #endif
  1435. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1436. auto host = "google.com";
  1437. auto another_host = "example.com";
  1438. auto wrong_ip = "0.0.0.0";
  1439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1440. SSLClient cli(host);
  1441. #else
  1442. Client cli(host);
  1443. #endif
  1444. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1445. auto res = cli.Get("/");
  1446. ASSERT_TRUE(res);
  1447. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1448. }
  1449. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1450. auto host = "google.com";
  1451. auto wrong_ip = "0.0.0.0";
  1452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1453. SSLClient cli(host);
  1454. #else
  1455. Client cli(host);
  1456. #endif
  1457. cli.set_hostname_addr_map({{host, wrong_ip}});
  1458. auto res = cli.Get("/");
  1459. ASSERT_TRUE(!res);
  1460. EXPECT_EQ(Error::Connection, res.error());
  1461. }
  1462. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1463. auto host = "nghttp2.org";
  1464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1465. SSLClient cli(host);
  1466. #else
  1467. Client cli(host);
  1468. #endif
  1469. cli.set_follow_location(true);
  1470. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ(StatusCode::OK_200, res->status);
  1473. }
  1474. TEST(RedirectTest, Redirect_Online) {
  1475. auto host = "nghttp2.org";
  1476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1477. SSLClient cli(host);
  1478. #else
  1479. Client cli(host);
  1480. #endif
  1481. cli.set_follow_location(true);
  1482. auto res = cli.Get("/httpbin/redirect/3");
  1483. ASSERT_TRUE(res);
  1484. EXPECT_EQ(StatusCode::OK_200, res->status);
  1485. }
  1486. TEST(RelativeRedirectTest, Redirect_Online) {
  1487. auto host = "nghttp2.org";
  1488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1489. SSLClient cli(host);
  1490. #else
  1491. Client cli(host);
  1492. #endif
  1493. cli.set_follow_location(true);
  1494. auto res = cli.Get("/httpbin/relative-redirect/3");
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ(StatusCode::OK_200, res->status);
  1497. }
  1498. TEST(TooManyRedirectTest, Redirect_Online) {
  1499. auto host = "nghttp2.org";
  1500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1501. SSLClient cli(host);
  1502. #else
  1503. Client cli(host);
  1504. #endif
  1505. cli.set_follow_location(true);
  1506. auto res = cli.Get("/httpbin/redirect/21");
  1507. ASSERT_TRUE(!res);
  1508. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1509. }
  1510. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1511. TEST(YahooRedirectTest, Redirect_Online) {
  1512. Client cli("yahoo.com");
  1513. auto res = cli.Get("/");
  1514. ASSERT_TRUE(res);
  1515. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1516. cli.set_follow_location(true);
  1517. res = cli.Get("/");
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ(StatusCode::OK_200, res->status);
  1520. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1521. }
  1522. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1523. #define REDIR_HOST "httpbingo.org"
  1524. #define REDIR_PATH "/redirect-to"
  1525. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1526. SSLClient cli(REDIR_HOST);
  1527. cli.set_follow_location(true);
  1528. auto res =
  1529. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ(StatusCode::OK_200, res->status);
  1532. }
  1533. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1534. SSLClient cli(REDIR_HOST);
  1535. cli.set_follow_location(true);
  1536. Params params;
  1537. params.emplace("url", "http://example.com");
  1538. params.emplace("status_code", "302");
  1539. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1540. ASSERT_TRUE(res);
  1541. EXPECT_EQ(StatusCode::OK_200, res->status);
  1542. }
  1543. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1544. SSLClient cli(REDIR_HOST);
  1545. cli.set_follow_location(true);
  1546. Params params;
  1547. params.emplace("url", "http://example.com");
  1548. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1549. ASSERT_TRUE(res);
  1550. EXPECT_EQ(StatusCode::OK_200, res->status);
  1551. }
  1552. TEST(UrlWithSpace, Redirect_Online) {
  1553. SSLClient cli("edge.forgecdn.net");
  1554. cli.set_follow_location(true);
  1555. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1556. ASSERT_TRUE(res);
  1557. EXPECT_EQ(StatusCode::OK_200, res->status);
  1558. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1559. }
  1560. #endif
  1561. #if !defined(_WIN32) && !defined(_WIN64)
  1562. TEST(ReceiveSignals, Signal) {
  1563. auto setupSignalHandlers = []() {
  1564. struct sigaction act;
  1565. sigemptyset(&act.sa_mask);
  1566. act.sa_flags = SA_SIGINFO;
  1567. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1568. switch (sig) {
  1569. case SIGINT:
  1570. default: break;
  1571. }
  1572. };
  1573. ::sigaction(SIGINT, &act, nullptr);
  1574. };
  1575. Server svr;
  1576. int port = 0;
  1577. auto thread = std::thread([&]() {
  1578. setupSignalHandlers();
  1579. port = svr.bind_to_any_port("localhost");
  1580. svr.listen_after_bind();
  1581. });
  1582. auto se = detail::scope_exit([&] {
  1583. svr.stop();
  1584. thread.join();
  1585. ASSERT_FALSE(svr.is_running());
  1586. });
  1587. svr.wait_until_ready();
  1588. ASSERT_TRUE(svr.is_running());
  1589. pthread_kill(thread.native_handle(), SIGINT);
  1590. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1591. ASSERT_TRUE(svr.is_running());
  1592. }
  1593. #endif
  1594. TEST(RedirectToDifferentPort, Redirect) {
  1595. Server svr1;
  1596. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1597. res.set_content("Hello World!", "text/plain");
  1598. });
  1599. int svr1_port = 0;
  1600. auto thread1 = std::thread([&]() {
  1601. svr1_port = svr1.bind_to_any_port("localhost");
  1602. svr1.listen_after_bind();
  1603. });
  1604. Server svr2;
  1605. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1606. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1607. });
  1608. int svr2_port = 0;
  1609. auto thread2 = std::thread([&]() {
  1610. svr2_port = svr2.bind_to_any_port("localhost");
  1611. svr2.listen_after_bind();
  1612. });
  1613. auto se = detail::scope_exit([&] {
  1614. svr2.stop();
  1615. thread2.join();
  1616. svr1.stop();
  1617. thread1.join();
  1618. ASSERT_FALSE(svr2.is_running());
  1619. ASSERT_FALSE(svr1.is_running());
  1620. });
  1621. svr1.wait_until_ready();
  1622. svr2.wait_until_ready();
  1623. Client cli("localhost", svr2_port);
  1624. cli.set_follow_location(true);
  1625. auto res = cli.Get("/2");
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::OK_200, res->status);
  1628. EXPECT_EQ("Hello World!", res->body);
  1629. }
  1630. TEST(RedirectFromPageWithContent, Redirect) {
  1631. Server svr;
  1632. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1633. res.set_content("___", "text/plain");
  1634. res.set_redirect("/2");
  1635. });
  1636. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1637. res.set_content("Hello World!", "text/plain");
  1638. });
  1639. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. th.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. {
  1647. Client cli("localhost", PORT);
  1648. cli.set_follow_location(true);
  1649. std::string body;
  1650. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1651. body.append(data, data_length);
  1652. return true;
  1653. });
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::OK_200, res->status);
  1656. EXPECT_EQ("Hello World!", body);
  1657. }
  1658. {
  1659. Client cli("localhost", PORT);
  1660. std::string body;
  1661. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1662. body.append(data, data_length);
  1663. return true;
  1664. });
  1665. ASSERT_TRUE(res);
  1666. EXPECT_EQ(StatusCode::Found_302, res->status);
  1667. EXPECT_EQ("___", body);
  1668. }
  1669. }
  1670. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1671. Server svr;
  1672. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1673. res.set_content("___", "text/plain");
  1674. // res.set_redirect("/2");
  1675. res.set_redirect("http://[::1]:1234/2");
  1676. });
  1677. svr.Get("/2", [&](const Request &req, Response &res) {
  1678. auto host_header = req.headers.find("Host");
  1679. ASSERT_TRUE(host_header != req.headers.end());
  1680. EXPECT_EQ("[::1]:1234", host_header->second);
  1681. res.set_content("Hello World!", "text/plain");
  1682. });
  1683. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1684. auto se = detail::scope_exit([&] {
  1685. svr.stop();
  1686. th.join();
  1687. ASSERT_FALSE(svr.is_running());
  1688. });
  1689. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1690. // actually starts anything, so the condition !svr.is_running() will
  1691. // always remain true, and the loop never stops.
  1692. // This basically counts how many milliseconds have passed since the
  1693. // call to svr.listen(), and if after 5 seconds nothing started yet
  1694. // aborts the test.
  1695. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1696. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1697. ASSERT_LT(milliseconds, 5000U);
  1698. }
  1699. {
  1700. Client cli("http://[::1]:1234");
  1701. cli.set_follow_location(true);
  1702. std::string body;
  1703. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1704. body.append(data, data_length);
  1705. return true;
  1706. });
  1707. ASSERT_TRUE(res);
  1708. EXPECT_EQ(StatusCode::OK_200, res->status);
  1709. EXPECT_EQ("Hello World!", body);
  1710. }
  1711. {
  1712. Client cli("http://[::1]:1234");
  1713. std::string body;
  1714. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1715. body.append(data, data_length);
  1716. return true;
  1717. });
  1718. ASSERT_TRUE(res);
  1719. EXPECT_EQ(StatusCode::Found_302, res->status);
  1720. EXPECT_EQ("___", body);
  1721. }
  1722. }
  1723. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1724. Server svr;
  1725. svr.Get("/foo", [](const Request &req, Response &res) {
  1726. auto a = req.params.find("a");
  1727. if (a != req.params.end()) {
  1728. res.set_content((*a).second, "text/plain");
  1729. res.status = StatusCode::OK_200;
  1730. } else {
  1731. res.status = StatusCode::BadRequest_400;
  1732. }
  1733. });
  1734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1735. auto se = detail::scope_exit([&] {
  1736. svr.stop();
  1737. thread.join();
  1738. ASSERT_FALSE(svr.is_running());
  1739. });
  1740. svr.wait_until_ready();
  1741. {
  1742. Client cli(HOST, PORT);
  1743. cli.set_url_encode(false);
  1744. auto res = cli.Get("/foo?a=explicitly+encoded");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. // This expects it back with a space, as the `+` won't have been
  1748. // url-encoded, and server-side the params get decoded turning `+`
  1749. // into spaces.
  1750. EXPECT_EQ("explicitly encoded", res->body);
  1751. }
  1752. }
  1753. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1754. Server svr;
  1755. svr.Get("/", [](const Request &req, Response &) {
  1756. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1757. });
  1758. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1759. auto se = detail::scope_exit([&] {
  1760. svr.stop();
  1761. thread.join();
  1762. ASSERT_FALSE(svr.is_running());
  1763. });
  1764. svr.wait_until_ready();
  1765. {
  1766. Client cli(HOST, PORT);
  1767. cli.set_url_encode(false);
  1768. auto res = cli.Get("/?something=%0A");
  1769. ASSERT_TRUE(res);
  1770. EXPECT_EQ(StatusCode::OK_200, res->status);
  1771. }
  1772. }
  1773. TEST(BindServerTest, DISABLED_BindDualStack) {
  1774. Server svr;
  1775. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1776. res.set_content("Hello World!", "text/plain");
  1777. });
  1778. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1779. auto se = detail::scope_exit([&] {
  1780. svr.stop();
  1781. thread.join();
  1782. ASSERT_FALSE(svr.is_running());
  1783. });
  1784. svr.wait_until_ready();
  1785. {
  1786. Client cli("127.0.0.1", PORT);
  1787. auto res = cli.Get("/1");
  1788. ASSERT_TRUE(res);
  1789. EXPECT_EQ(StatusCode::OK_200, res->status);
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. {
  1793. Client cli("::1", PORT);
  1794. auto res = cli.Get("/1");
  1795. ASSERT_TRUE(res);
  1796. EXPECT_EQ(StatusCode::OK_200, res->status);
  1797. EXPECT_EQ("Hello World!", res->body);
  1798. }
  1799. }
  1800. TEST(BindServerTest, BindAndListenSeparately) {
  1801. Server svr;
  1802. int port = svr.bind_to_any_port("0.0.0.0");
  1803. ASSERT_TRUE(svr.is_valid());
  1804. ASSERT_TRUE(port > 0);
  1805. svr.stop();
  1806. }
  1807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1808. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1810. CLIENT_CA_CERT_DIR);
  1811. int port = svr.bind_to_any_port("0.0.0.0");
  1812. ASSERT_TRUE(svr.is_valid());
  1813. ASSERT_TRUE(port > 0);
  1814. svr.stop();
  1815. }
  1816. #endif
  1817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1818. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1819. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1820. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1821. int port = svr.bind_to_any_port("0.0.0.0");
  1822. ASSERT_TRUE(svr.is_valid());
  1823. ASSERT_TRUE(port > 0);
  1824. svr.stop();
  1825. }
  1826. #endif
  1827. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1828. X509 *readCertificate(const std::string &strFileName) {
  1829. std::ifstream inStream(strFileName);
  1830. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1831. std::istreambuf_iterator<char>());
  1832. if (strCertPEM.empty()) return (nullptr);
  1833. BIO *pbCert = BIO_new(BIO_s_mem());
  1834. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1835. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1836. BIO_free(pbCert);
  1837. return (pCert);
  1838. }
  1839. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1840. std::ifstream inStream(strFileName);
  1841. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1842. std::istreambuf_iterator<char>());
  1843. if (strPrivateKeyPEM.empty()) return (nullptr);
  1844. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1845. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1846. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1847. BIO_free(pbPrivKey);
  1848. return (pPrivateKey);
  1849. }
  1850. TEST(BindServerTest, UpdateCerts) {
  1851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1852. int port = svr.bind_to_any_port("0.0.0.0");
  1853. ASSERT_TRUE(svr.is_valid());
  1854. ASSERT_TRUE(port > 0);
  1855. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1856. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1857. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1858. ASSERT_TRUE(cert != nullptr);
  1859. ASSERT_TRUE(ca_cert != nullptr);
  1860. ASSERT_TRUE(key != nullptr);
  1861. X509_STORE *cert_store = X509_STORE_new();
  1862. X509_STORE_add_cert(cert_store, ca_cert);
  1863. svr.update_certs(cert, key, cert_store);
  1864. ASSERT_TRUE(svr.is_valid());
  1865. svr.stop();
  1866. X509_free(cert);
  1867. X509_free(ca_cert);
  1868. EVP_PKEY_free(key);
  1869. }
  1870. #endif
  1871. TEST(ErrorHandlerTest, ContentLength) {
  1872. Server svr;
  1873. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1874. res.status = StatusCode::OK_200;
  1875. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1876. "text/html"); // <= Content-Length still 13
  1877. });
  1878. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!\n", "text/plain");
  1880. res.status = 524;
  1881. });
  1882. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1883. auto se = detail::scope_exit([&] {
  1884. svr.stop();
  1885. thread.join();
  1886. ASSERT_FALSE(svr.is_running());
  1887. });
  1888. svr.wait_until_ready();
  1889. {
  1890. Client cli(HOST, PORT);
  1891. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1892. ASSERT_TRUE(res);
  1893. EXPECT_EQ(StatusCode::OK_200, res->status);
  1894. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1895. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1896. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1897. }
  1898. }
  1899. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1900. TEST(ExceptionTest, WithoutExceptionHandler) {
  1901. Server svr;
  1902. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  1903. throw std::runtime_error("exception...");
  1904. });
  1905. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  1906. throw std::runtime_error("exception\r\n...");
  1907. });
  1908. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1909. auto se = detail::scope_exit([&] {
  1910. svr.stop();
  1911. listen_thread.join();
  1912. ASSERT_FALSE(svr.is_running());
  1913. });
  1914. svr.wait_until_ready();
  1915. Client cli("localhost", PORT);
  1916. {
  1917. auto res = cli.Get("/exception");
  1918. ASSERT_TRUE(res);
  1919. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1920. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1921. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  1922. }
  1923. {
  1924. auto res = cli.Get("/unknown");
  1925. ASSERT_TRUE(res);
  1926. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1927. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  1928. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  1929. }
  1930. }
  1931. TEST(ExceptionTest, WithExceptionHandler) {
  1932. Server svr;
  1933. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1934. std::exception_ptr ep) {
  1935. EXPECT_FALSE(ep == nullptr);
  1936. try {
  1937. std::rethrow_exception(ep);
  1938. } catch (std::exception &e) {
  1939. EXPECT_EQ("abc", std::string(e.what()));
  1940. } catch (...) {}
  1941. res.status = StatusCode::InternalServerError_500;
  1942. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1943. "text/html"); // <= Content-Length still 13 at this point
  1944. });
  1945. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1946. res.set_content("Hello World!\n", "text/plain");
  1947. throw std::runtime_error("abc");
  1948. });
  1949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1950. auto se = detail::scope_exit([&] {
  1951. svr.stop();
  1952. thread.join();
  1953. ASSERT_FALSE(svr.is_running());
  1954. });
  1955. svr.wait_until_ready();
  1956. for (size_t i = 0; i < 10; i++) {
  1957. Client cli(HOST, PORT);
  1958. for (size_t j = 0; j < 100; j++) {
  1959. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1962. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1963. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1964. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1965. }
  1966. cli.set_keep_alive(true);
  1967. for (size_t j = 0; j < 100; j++) {
  1968. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  1969. ASSERT_TRUE(res);
  1970. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1971. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1972. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1973. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1974. }
  1975. }
  1976. }
  1977. TEST(ExceptionTest, AndErrorHandler) {
  1978. Server svr;
  1979. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1980. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  1981. });
  1982. svr.set_exception_handler(
  1983. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  1984. EXPECT_FALSE(ep == nullptr);
  1985. try {
  1986. std::rethrow_exception(ep);
  1987. } catch (std::exception &e) {
  1988. res.set_content(e.what(), "text/html");
  1989. } catch (...) {}
  1990. res.status = StatusCode::InternalServerError_500;
  1991. });
  1992. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  1993. throw std::runtime_error("EXCEPTION");
  1994. });
  1995. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  1996. res.set_content("ERROR", "text/html");
  1997. res.status = StatusCode::InternalServerError_500;
  1998. });
  1999. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2000. auto se = detail::scope_exit([&] {
  2001. svr.stop();
  2002. thread.join();
  2003. ASSERT_FALSE(svr.is_running());
  2004. });
  2005. svr.wait_until_ready();
  2006. Client cli(HOST, PORT);
  2007. {
  2008. auto res = cli.Get("/exception");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2011. EXPECT_EQ("EXCEPTION", res->body);
  2012. }
  2013. {
  2014. auto res = cli.Get("/error");
  2015. ASSERT_TRUE(res);
  2016. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2017. EXPECT_EQ("ERROR", res->body);
  2018. }
  2019. {
  2020. auto res = cli.Get("/invalid");
  2021. ASSERT_TRUE(res);
  2022. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2023. EXPECT_EQ("NOT_FOUND", res->body);
  2024. }
  2025. }
  2026. #endif
  2027. TEST(NoContentTest, ContentLength) {
  2028. Server svr;
  2029. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2030. res.status = StatusCode::NoContent_204;
  2031. });
  2032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2033. auto se = detail::scope_exit([&] {
  2034. svr.stop();
  2035. thread.join();
  2036. ASSERT_FALSE(svr.is_running());
  2037. });
  2038. svr.wait_until_ready();
  2039. {
  2040. Client cli(HOST, PORT);
  2041. auto res = cli.Get("/hi");
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2044. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2045. }
  2046. }
  2047. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2050. ASSERT_TRUE(svr.is_valid());
  2051. #else
  2052. Server svr;
  2053. #endif
  2054. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2055. if (req.path == "/routing_handler") {
  2056. res.set_header("PRE_ROUTING", "on");
  2057. res.set_content("Routing Handler", "text/plain");
  2058. return httplib::Server::HandlerResponse::Handled;
  2059. }
  2060. return httplib::Server::HandlerResponse::Unhandled;
  2061. });
  2062. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2063. res.set_content("Error", "text/html");
  2064. });
  2065. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2066. if (req.path == "/routing_handler") {
  2067. res.set_header("POST_ROUTING", "on");
  2068. }
  2069. });
  2070. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2071. res.set_content("Hello World!\n", "text/plain");
  2072. });
  2073. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2074. auto se = detail::scope_exit([&] {
  2075. svr.stop();
  2076. thread.join();
  2077. ASSERT_FALSE(svr.is_running());
  2078. });
  2079. svr.wait_until_ready();
  2080. {
  2081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2082. SSLClient cli(HOST, PORT);
  2083. cli.enable_server_certificate_verification(false);
  2084. #else
  2085. Client cli(HOST, PORT);
  2086. #endif
  2087. auto res = cli.Get("/routing_handler");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::OK_200, res->status);
  2090. EXPECT_EQ("Routing Handler", res->body);
  2091. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2092. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2093. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2094. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2095. }
  2096. {
  2097. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2098. SSLClient cli(HOST, PORT);
  2099. cli.enable_server_certificate_verification(false);
  2100. #else
  2101. Client cli(HOST, PORT);
  2102. #endif
  2103. auto res = cli.Get("/hi");
  2104. ASSERT_TRUE(res);
  2105. EXPECT_EQ(StatusCode::OK_200, res->status);
  2106. EXPECT_EQ("Hello World!\n", res->body);
  2107. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2108. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2109. }
  2110. {
  2111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2112. SSLClient cli(HOST, PORT);
  2113. cli.enable_server_certificate_verification(false);
  2114. #else
  2115. Client cli(HOST, PORT);
  2116. #endif
  2117. auto res = cli.Get("/aaa");
  2118. ASSERT_TRUE(res);
  2119. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2120. EXPECT_EQ("Error", res->body);
  2121. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2122. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2123. }
  2124. }
  2125. TEST(RequestHandlerTest, PreRequestHandler) {
  2126. auto route_path = "/user/:user";
  2127. Server svr;
  2128. svr.Get("/hi", [](const Request &, Response &res) {
  2129. res.set_content("hi", "text/plain");
  2130. });
  2131. svr.Get(route_path, [](const Request &req, Response &res) {
  2132. res.set_content(req.path_params.at("user"), "text/plain");
  2133. });
  2134. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2135. if (req.matched_route == route_path) {
  2136. auto user = req.path_params.at("user");
  2137. if (user != "john") {
  2138. res.status = StatusCode::Forbidden_403;
  2139. res.set_content("error", "text/html");
  2140. return Server::HandlerResponse::Handled;
  2141. }
  2142. }
  2143. return Server::HandlerResponse::Unhandled;
  2144. });
  2145. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2146. auto se = detail::scope_exit([&] {
  2147. svr.stop();
  2148. thread.join();
  2149. ASSERT_FALSE(svr.is_running());
  2150. });
  2151. svr.wait_until_ready();
  2152. Client cli(HOST, PORT);
  2153. {
  2154. auto res = cli.Get("/hi");
  2155. ASSERT_TRUE(res);
  2156. EXPECT_EQ(StatusCode::OK_200, res->status);
  2157. EXPECT_EQ("hi", res->body);
  2158. }
  2159. {
  2160. auto res = cli.Get("/user/john");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::OK_200, res->status);
  2163. EXPECT_EQ("john", res->body);
  2164. }
  2165. {
  2166. auto res = cli.Get("/user/invalid-user");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2169. EXPECT_EQ("error", res->body);
  2170. }
  2171. }
  2172. TEST(InvalidFormatTest, StatusCode) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.set_content("Hello World!\n", "text/plain");
  2176. res.status = 9999; // Status should be a three-digit code...
  2177. });
  2178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2179. auto se = detail::scope_exit([&] {
  2180. svr.stop();
  2181. thread.join();
  2182. ASSERT_FALSE(svr.is_running());
  2183. });
  2184. svr.wait_until_ready();
  2185. {
  2186. Client cli(HOST, PORT);
  2187. auto res = cli.Get("/hi");
  2188. ASSERT_FALSE(res);
  2189. }
  2190. }
  2191. TEST(URLFragmentTest, WithFragment) {
  2192. Server svr;
  2193. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2194. EXPECT_TRUE(req.target == "/hi");
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2206. EXPECT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::OK_200, res->status);
  2208. res = cli.Get("/hi%23key1=val1=key2=val2");
  2209. EXPECT_TRUE(res);
  2210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2211. }
  2212. }
  2213. TEST(HeaderWriter, SetHeaderWriter) {
  2214. Server svr;
  2215. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2216. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2217. return detail::write_headers(strm, hdrs);
  2218. });
  2219. svr.Get("/hi", [](const Request &req, Response &res) {
  2220. auto it = req.headers.find("CustomClientHeader");
  2221. EXPECT_TRUE(it != req.headers.end());
  2222. EXPECT_EQ(it->second, "CustomClientValue");
  2223. res.set_content("Hello World!\n", "text/plain");
  2224. });
  2225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2226. auto se = detail::scope_exit([&] {
  2227. svr.stop();
  2228. thread.join();
  2229. ASSERT_FALSE(svr.is_running());
  2230. });
  2231. svr.wait_until_ready();
  2232. {
  2233. Client cli(HOST, PORT);
  2234. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2235. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2236. return detail::write_headers(strm, hdrs);
  2237. });
  2238. auto res = cli.Get("/hi");
  2239. EXPECT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. auto it = res->headers.find("CustomServerHeader");
  2242. EXPECT_TRUE(it != res->headers.end());
  2243. EXPECT_EQ(it->second, "CustomServerValue");
  2244. }
  2245. }
  2246. class ServerTest : public ::testing::Test {
  2247. protected:
  2248. ServerTest()
  2249. : cli_(HOST, PORT)
  2250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2251. ,
  2252. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2253. #endif
  2254. {
  2255. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2256. cli_.enable_server_certificate_verification(false);
  2257. #endif
  2258. }
  2259. virtual void SetUp() {
  2260. svr_.set_mount_point("/", "./www");
  2261. svr_.set_mount_point("/mount", "./www2");
  2262. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2263. svr_.Get("/hi",
  2264. [&](const Request & /*req*/, Response &res) {
  2265. res.set_content("Hello World!", "text/plain");
  2266. })
  2267. .Get("/file_content",
  2268. [&](const Request & /*req*/, Response &res) {
  2269. res.set_file_content("./www/dir/test.html");
  2270. })
  2271. .Get("/file_content_with_content_type",
  2272. [&](const Request & /*req*/, Response &res) {
  2273. res.set_file_content("./www/file", "text/plain");
  2274. })
  2275. .Get("/invalid_file_content",
  2276. [&](const Request & /*req*/, Response &res) {
  2277. res.set_file_content("./www/dir/invalid_file_path");
  2278. })
  2279. .Get("/http_response_splitting",
  2280. [&](const Request & /*req*/, Response &res) {
  2281. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2282. EXPECT_EQ(0U, res.headers.size());
  2283. EXPECT_FALSE(res.has_header("a"));
  2284. res.set_header("a", "1\nSet-Cookie: a=1");
  2285. EXPECT_EQ(0U, res.headers.size());
  2286. EXPECT_FALSE(res.has_header("a"));
  2287. res.set_header("a", "1\rSet-Cookie: a=1");
  2288. EXPECT_EQ(0U, res.headers.size());
  2289. EXPECT_FALSE(res.has_header("a"));
  2290. res.set_header("a\r\nb", "0");
  2291. EXPECT_EQ(0U, res.headers.size());
  2292. EXPECT_FALSE(res.has_header("a"));
  2293. res.set_header("a\rb", "0");
  2294. EXPECT_EQ(0U, res.headers.size());
  2295. EXPECT_FALSE(res.has_header("a"));
  2296. res.set_header("a\nb", "0");
  2297. EXPECT_EQ(0U, res.headers.size());
  2298. EXPECT_FALSE(res.has_header("a"));
  2299. res.set_redirect("1\r\nSet-Cookie: a=1");
  2300. EXPECT_EQ(0U, res.headers.size());
  2301. EXPECT_FALSE(res.has_header("Location"));
  2302. })
  2303. .Get("/slow",
  2304. [&](const Request & /*req*/, Response &res) {
  2305. std::this_thread::sleep_for(std::chrono::seconds(2));
  2306. res.set_content("slow", "text/plain");
  2307. })
  2308. #if 0
  2309. .Post("/slowpost",
  2310. [&](const Request & /*req*/, Response &res) {
  2311. std::this_thread::sleep_for(std::chrono::seconds(2));
  2312. res.set_content("slow", "text/plain");
  2313. })
  2314. #endif
  2315. .Get("/remote_addr",
  2316. [&](const Request &req, Response &res) {
  2317. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2318. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2319. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2320. EXPECT_EQ(req.remote_port,
  2321. std::stoi(req.get_header_value("REMOTE_PORT")));
  2322. res.set_content(remote_addr.c_str(), "text/plain");
  2323. })
  2324. .Get("/local_addr",
  2325. [&](const Request &req, Response &res) {
  2326. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2327. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2328. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2329. auto local_port = req.get_header_value("LOCAL_PORT");
  2330. EXPECT_EQ(req.local_addr, local_addr);
  2331. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2332. res.set_content(local_addr.append(":").append(local_port),
  2333. "text/plain");
  2334. })
  2335. .Get("/endwith%",
  2336. [&](const Request & /*req*/, Response &res) {
  2337. res.set_content("Hello World!", "text/plain");
  2338. })
  2339. .Get("/a\\+\\+b",
  2340. [&](const Request &req, Response &res) {
  2341. ASSERT_TRUE(req.has_param("a +b"));
  2342. auto val = req.get_param_value("a +b");
  2343. res.set_content(val, "text/plain");
  2344. })
  2345. .Get("/", [&](const Request & /*req*/,
  2346. Response &res) { res.set_redirect("/hi"); })
  2347. .Post("/1",
  2348. [](const Request & /*req*/, Response &res) {
  2349. res.set_redirect("/2", StatusCode::SeeOther_303);
  2350. })
  2351. .Get("/2",
  2352. [](const Request & /*req*/, Response &res) {
  2353. res.set_content("redirected.", "text/plain");
  2354. res.status = StatusCode::OK_200;
  2355. })
  2356. .Post("/person",
  2357. [&](const Request &req, Response &res) {
  2358. if (req.has_param("name") && req.has_param("note")) {
  2359. persons_[req.get_param_value("name")] =
  2360. req.get_param_value("note");
  2361. } else {
  2362. res.status = StatusCode::BadRequest_400;
  2363. }
  2364. })
  2365. .Put("/person",
  2366. [&](const Request &req, Response &res) {
  2367. if (req.has_param("name") && req.has_param("note")) {
  2368. persons_[req.get_param_value("name")] =
  2369. req.get_param_value("note");
  2370. } else {
  2371. res.status = StatusCode::BadRequest_400;
  2372. }
  2373. })
  2374. .Get("/person/(.*)",
  2375. [&](const Request &req, Response &res) {
  2376. string name = req.matches[1];
  2377. if (persons_.find(name) != persons_.end()) {
  2378. auto note = persons_[name];
  2379. res.set_content(note, "text/plain");
  2380. } else {
  2381. res.status = StatusCode::NotFound_404;
  2382. }
  2383. })
  2384. .Delete("/person",
  2385. [&](const Request &req, Response &res) {
  2386. if (req.has_param("name")) {
  2387. string name = req.get_param_value("name");
  2388. if (persons_.find(name) != persons_.end()) {
  2389. persons_.erase(name);
  2390. res.set_content("DELETED", "text/plain");
  2391. } else {
  2392. res.status = StatusCode::NotFound_404;
  2393. }
  2394. } else {
  2395. res.status = StatusCode::BadRequest_400;
  2396. }
  2397. })
  2398. .Post("/x-www-form-urlencoded-json",
  2399. [&](const Request &req, Response &res) {
  2400. auto json = req.get_param_value("json");
  2401. ASSERT_EQ(JSON_DATA, json);
  2402. res.set_content(json, "appliation/json");
  2403. res.status = StatusCode::OK_200;
  2404. })
  2405. .Get("/streamed-chunked",
  2406. [&](const Request & /*req*/, Response &res) {
  2407. res.set_chunked_content_provider(
  2408. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2409. sink.os << "123";
  2410. sink.os << "456";
  2411. sink.os << "789";
  2412. sink.done();
  2413. return true;
  2414. });
  2415. })
  2416. .Get("/streamed-chunked2",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. auto i = new int(0);
  2419. res.set_chunked_content_provider(
  2420. "text/plain",
  2421. [i](size_t /*offset*/, DataSink &sink) {
  2422. switch (*i) {
  2423. case 0: sink.os << "123"; break;
  2424. case 1: sink.os << "456"; break;
  2425. case 2: sink.os << "789"; break;
  2426. case 3: sink.done(); break;
  2427. }
  2428. (*i)++;
  2429. return true;
  2430. },
  2431. [i](bool success) {
  2432. EXPECT_TRUE(success);
  2433. delete i;
  2434. });
  2435. })
  2436. .Get("/streamed-chunked-with-trailer",
  2437. [&](const Request & /*req*/, Response &res) {
  2438. auto i = new int(0);
  2439. res.set_header("Trailer", "Dummy1, Dummy2");
  2440. res.set_chunked_content_provider(
  2441. "text/plain",
  2442. [i](size_t /*offset*/, DataSink &sink) {
  2443. switch (*i) {
  2444. case 0: sink.os << "123"; break;
  2445. case 1: sink.os << "456"; break;
  2446. case 2: sink.os << "789"; break;
  2447. case 3: {
  2448. sink.done_with_trailer(
  2449. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2450. } break;
  2451. }
  2452. (*i)++;
  2453. return true;
  2454. },
  2455. [i](bool success) {
  2456. EXPECT_TRUE(success);
  2457. delete i;
  2458. });
  2459. })
  2460. .Get("/streamed",
  2461. [&](const Request & /*req*/, Response &res) {
  2462. res.set_content_provider(
  2463. 6, "text/plain",
  2464. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2465. sink.os << (offset < 3 ? "a" : "b");
  2466. return true;
  2467. });
  2468. })
  2469. .Get("/streamed-with-range",
  2470. [&](const Request &req, Response &res) {
  2471. auto data = new std::string("abcdefg");
  2472. res.set_content_provider(
  2473. data->size(), "text/plain",
  2474. [data](size_t offset, size_t length, DataSink &sink) {
  2475. size_t DATA_CHUNK_SIZE = 4;
  2476. const auto &d = *data;
  2477. auto out_len =
  2478. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2479. auto ret =
  2480. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2481. EXPECT_TRUE(ret);
  2482. return true;
  2483. },
  2484. [data, &req](bool success) {
  2485. EXPECT_EQ(success, !req.has_param("error"));
  2486. delete data;
  2487. });
  2488. })
  2489. .Get("/streamed-cancel",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_content_provider(
  2492. size_t(-1), "text/plain",
  2493. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2494. sink.os << "data_chunk";
  2495. return true;
  2496. });
  2497. })
  2498. .Get("/regex-with-delimiter",
  2499. [&](const Request &req, Response & /*res*/) {
  2500. ASSERT_TRUE(req.has_param("key"));
  2501. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2502. })
  2503. .Get("/with-range",
  2504. [&](const Request & /*req*/, Response &res) {
  2505. res.set_content("abcdefg", "text/plain");
  2506. })
  2507. .Get("/with-range-customized-response",
  2508. [&](const Request & /*req*/, Response &res) {
  2509. res.status = StatusCode::BadRequest_400;
  2510. res.set_content(JSON_DATA, "application/json");
  2511. })
  2512. .Post("/chunked",
  2513. [&](const Request &req, Response & /*res*/) {
  2514. EXPECT_EQ(req.body, "dechunked post body");
  2515. })
  2516. .Post("/large-chunked",
  2517. [&](const Request &req, Response & /*res*/) {
  2518. std::string expected(6 * 30 * 1024u, 'a');
  2519. EXPECT_EQ(req.body, expected);
  2520. })
  2521. .Post("/multipart",
  2522. [&](const Request &req, Response & /*res*/) {
  2523. EXPECT_EQ(6u, req.files.size());
  2524. ASSERT_TRUE(!req.has_file("???"));
  2525. ASSERT_TRUE(req.body.empty());
  2526. {
  2527. const auto &file = req.get_file_value("text1");
  2528. EXPECT_TRUE(file.filename.empty());
  2529. EXPECT_EQ("text default", file.content);
  2530. }
  2531. {
  2532. const auto &file = req.get_file_value("text2");
  2533. EXPECT_TRUE(file.filename.empty());
  2534. EXPECT_EQ("aωb", file.content);
  2535. }
  2536. {
  2537. const auto &file = req.get_file_value("file1");
  2538. EXPECT_EQ("hello.txt", file.filename);
  2539. EXPECT_EQ("text/plain", file.content_type);
  2540. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2541. }
  2542. {
  2543. const auto &file = req.get_file_value("file3");
  2544. EXPECT_TRUE(file.filename.empty());
  2545. EXPECT_EQ("application/octet-stream", file.content_type);
  2546. EXPECT_EQ(0u, file.content.size());
  2547. }
  2548. {
  2549. const auto &file = req.get_file_value("file4");
  2550. EXPECT_TRUE(file.filename.empty());
  2551. EXPECT_EQ(0u, file.content.size());
  2552. EXPECT_EQ("application/json tmp-string", file.content_type);
  2553. }
  2554. })
  2555. .Post("/multipart/multi_file_values",
  2556. [&](const Request &req, Response & /*res*/) {
  2557. EXPECT_EQ(5u, req.files.size());
  2558. ASSERT_TRUE(!req.has_file("???"));
  2559. ASSERT_TRUE(req.body.empty());
  2560. {
  2561. const auto &text_value = req.get_file_values("text");
  2562. EXPECT_EQ(1u, text_value.size());
  2563. auto &text = text_value[0];
  2564. EXPECT_TRUE(text.filename.empty());
  2565. EXPECT_EQ("default text", text.content);
  2566. }
  2567. {
  2568. const auto &text1_values = req.get_file_values("multi_text1");
  2569. EXPECT_EQ(2u, text1_values.size());
  2570. EXPECT_EQ("aaaaa", text1_values[0].content);
  2571. EXPECT_EQ("bbbbb", text1_values[1].content);
  2572. }
  2573. {
  2574. const auto &file1_values = req.get_file_values("multi_file1");
  2575. EXPECT_EQ(2u, file1_values.size());
  2576. auto file1 = file1_values[0];
  2577. EXPECT_EQ(file1.filename, "hello.txt");
  2578. EXPECT_EQ(file1.content_type, "text/plain");
  2579. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2580. auto file2 = file1_values[1];
  2581. EXPECT_EQ(file2.filename, "world.json");
  2582. EXPECT_EQ(file2.content_type, "application/json");
  2583. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2584. }
  2585. })
  2586. .Post("/empty",
  2587. [&](const Request &req, Response &res) {
  2588. EXPECT_EQ(req.body, "");
  2589. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2590. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2591. res.set_content("empty", "text/plain");
  2592. })
  2593. .Post("/empty-no-content-type",
  2594. [&](const Request &req, Response &res) {
  2595. EXPECT_EQ(req.body, "");
  2596. EXPECT_FALSE(req.has_header("Content-Type"));
  2597. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2598. res.set_content("empty-no-content-type", "text/plain");
  2599. })
  2600. .Post("/path-only",
  2601. [&](const Request &req, Response &res) {
  2602. EXPECT_EQ(req.body, "");
  2603. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2604. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2605. res.set_content("path-only", "text/plain");
  2606. })
  2607. .Post("/path-headers-only",
  2608. [&](const Request &req, Response &res) {
  2609. EXPECT_EQ(req.body, "");
  2610. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2611. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2612. EXPECT_EQ("world", req.get_header_value("hello"));
  2613. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2614. res.set_content("path-headers-only", "text/plain");
  2615. })
  2616. .Post("/post-large",
  2617. [&](const Request &req, Response &res) {
  2618. EXPECT_EQ(req.body, LARGE_DATA);
  2619. res.set_content(req.body, "text/plain");
  2620. })
  2621. .Put("/empty-no-content-type",
  2622. [&](const Request &req, Response &res) {
  2623. EXPECT_EQ(req.body, "");
  2624. EXPECT_FALSE(req.has_header("Content-Type"));
  2625. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2626. res.set_content("empty-no-content-type", "text/plain");
  2627. })
  2628. .Put("/put",
  2629. [&](const Request &req, Response &res) {
  2630. EXPECT_EQ(req.body, "PUT");
  2631. res.set_content(req.body, "text/plain");
  2632. })
  2633. .Put("/put-large",
  2634. [&](const Request &req, Response &res) {
  2635. EXPECT_EQ(req.body, LARGE_DATA);
  2636. res.set_content(req.body, "text/plain");
  2637. })
  2638. .Patch("/patch",
  2639. [&](const Request &req, Response &res) {
  2640. EXPECT_EQ(req.body, "PATCH");
  2641. res.set_content(req.body, "text/plain");
  2642. })
  2643. .Delete("/delete",
  2644. [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("DELETE", "text/plain");
  2646. })
  2647. .Delete("/delete-body",
  2648. [&](const Request &req, Response &res) {
  2649. EXPECT_EQ(req.body, "content");
  2650. res.set_content(req.body, "text/plain");
  2651. })
  2652. .Options(R"(\*)",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2655. })
  2656. .Get("/request-target",
  2657. [&](const Request &req, Response & /*res*/) {
  2658. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2659. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2660. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2661. })
  2662. .Get("/long-query-value",
  2663. [&](const Request &req, Response & /*res*/) {
  2664. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2665. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2666. })
  2667. .Get("/too-long-query-value",
  2668. [&](const Request &req, Response & /*res*/) {
  2669. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2670. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2671. })
  2672. .Get("/array-param",
  2673. [&](const Request &req, Response & /*res*/) {
  2674. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2675. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2676. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2677. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2678. })
  2679. .Post("/validate-no-multiple-headers",
  2680. [&](const Request &req, Response & /*res*/) {
  2681. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2682. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2683. })
  2684. .Post("/content_receiver",
  2685. [&](const Request &req, Response &res,
  2686. const ContentReader &content_reader) {
  2687. if (req.is_multipart_form_data()) {
  2688. MultipartFormDataItems files;
  2689. content_reader(
  2690. [&](const MultipartFormData &file) {
  2691. files.push_back(file);
  2692. return true;
  2693. },
  2694. [&](const char *data, size_t data_length) {
  2695. files.back().content.append(data, data_length);
  2696. return true;
  2697. });
  2698. EXPECT_EQ(5u, files.size());
  2699. {
  2700. const auto &file = get_file_value(files, "text1");
  2701. EXPECT_TRUE(file.filename.empty());
  2702. EXPECT_EQ("text default", file.content);
  2703. }
  2704. {
  2705. const auto &file = get_file_value(files, "text2");
  2706. EXPECT_TRUE(file.filename.empty());
  2707. EXPECT_EQ("aωb", file.content);
  2708. }
  2709. {
  2710. const auto &file = get_file_value(files, "file1");
  2711. EXPECT_EQ("hello.txt", file.filename);
  2712. EXPECT_EQ("text/plain", file.content_type);
  2713. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2714. }
  2715. {
  2716. const auto &file = get_file_value(files, "file3");
  2717. EXPECT_TRUE(file.filename.empty());
  2718. EXPECT_EQ("application/octet-stream", file.content_type);
  2719. EXPECT_EQ(0u, file.content.size());
  2720. }
  2721. } else {
  2722. std::string body;
  2723. content_reader([&](const char *data, size_t data_length) {
  2724. EXPECT_EQ(7U, data_length);
  2725. body.append(data, data_length);
  2726. return true;
  2727. });
  2728. EXPECT_EQ(body, "content");
  2729. res.set_content(body, "text/plain");
  2730. }
  2731. })
  2732. .Put("/content_receiver",
  2733. [&](const Request & /*req*/, Response &res,
  2734. const ContentReader &content_reader) {
  2735. std::string body;
  2736. content_reader([&](const char *data, size_t data_length) {
  2737. body.append(data, data_length);
  2738. return true;
  2739. });
  2740. EXPECT_EQ(body, "content");
  2741. res.set_content(body, "text/plain");
  2742. })
  2743. .Patch("/content_receiver",
  2744. [&](const Request & /*req*/, Response &res,
  2745. const ContentReader &content_reader) {
  2746. std::string body;
  2747. content_reader([&](const char *data, size_t data_length) {
  2748. body.append(data, data_length);
  2749. return true;
  2750. });
  2751. EXPECT_EQ(body, "content");
  2752. res.set_content(body, "text/plain");
  2753. })
  2754. .Post("/query-string-and-body",
  2755. [&](const Request &req, Response & /*res*/) {
  2756. ASSERT_TRUE(req.has_param("key"));
  2757. EXPECT_EQ(req.get_param_value("key"), "value");
  2758. EXPECT_EQ(req.body, "content");
  2759. })
  2760. .Get("/last-request",
  2761. [&](const Request &req, Response & /*res*/) {
  2762. EXPECT_EQ("close", req.get_header_value("Connection"));
  2763. })
  2764. .Get(R"(/redirect/(\d+))",
  2765. [&](const Request &req, Response &res) {
  2766. auto num = std::stoi(req.matches[1]) + 1;
  2767. std::string url = "/redirect/" + std::to_string(num);
  2768. res.set_redirect(url);
  2769. })
  2770. .Post("/binary",
  2771. [&](const Request &req, Response &res) {
  2772. EXPECT_EQ(4U, req.body.size());
  2773. EXPECT_EQ("application/octet-stream",
  2774. req.get_header_value("Content-Type"));
  2775. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2776. res.set_content(req.body, "application/octet-stream");
  2777. })
  2778. .Put("/binary",
  2779. [&](const Request &req, Response &res) {
  2780. EXPECT_EQ(4U, req.body.size());
  2781. EXPECT_EQ("application/octet-stream",
  2782. req.get_header_value("Content-Type"));
  2783. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2784. res.set_content(req.body, "application/octet-stream");
  2785. })
  2786. .Patch("/binary",
  2787. [&](const Request &req, Response &res) {
  2788. EXPECT_EQ(4U, req.body.size());
  2789. EXPECT_EQ("application/octet-stream",
  2790. req.get_header_value("Content-Type"));
  2791. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2792. res.set_content(req.body, "application/octet-stream");
  2793. })
  2794. .Delete("/binary",
  2795. [&](const Request &req, Response &res) {
  2796. EXPECT_EQ(4U, req.body.size());
  2797. EXPECT_EQ("application/octet-stream",
  2798. req.get_header_value("Content-Type"));
  2799. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2800. res.set_content(req.body, "application/octet-stream");
  2801. })
  2802. .Get("/issue1772",
  2803. [&](const Request & /*req*/, Response &res) {
  2804. res.status = 401;
  2805. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2806. })
  2807. .Delete("/issue609",
  2808. [](const httplib::Request &, httplib::Response &res,
  2809. const httplib::ContentReader &) {
  2810. res.set_content("ok", "text/plain");
  2811. })
  2812. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2813. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2814. .Get("/compress",
  2815. [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(
  2817. "12345678901234567890123456789012345678901234567890123456789"
  2818. "01234567890123456789012345678901234567890",
  2819. "text/plain");
  2820. })
  2821. .Get("/nocompress",
  2822. [&](const Request & /*req*/, Response &res) {
  2823. res.set_content(
  2824. "12345678901234567890123456789012345678901234567890123456789"
  2825. "01234567890123456789012345678901234567890",
  2826. "application/octet-stream");
  2827. })
  2828. .Post("/compress-multipart",
  2829. [&](const Request &req, Response & /*res*/) {
  2830. EXPECT_EQ(2u, req.files.size());
  2831. ASSERT_TRUE(!req.has_file("???"));
  2832. {
  2833. const auto &file = req.get_file_value("key1");
  2834. EXPECT_TRUE(file.filename.empty());
  2835. EXPECT_EQ("test", file.content);
  2836. }
  2837. {
  2838. const auto &file = req.get_file_value("key2");
  2839. EXPECT_TRUE(file.filename.empty());
  2840. EXPECT_EQ("--abcdefg123", file.content);
  2841. }
  2842. })
  2843. #endif
  2844. ;
  2845. persons_["john"] = "programmer";
  2846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2847. svr_.wait_until_ready();
  2848. }
  2849. virtual void TearDown() {
  2850. svr_.stop();
  2851. if (!request_threads_.empty()) {
  2852. std::this_thread::sleep_for(std::chrono::seconds(1));
  2853. for (auto &t : request_threads_) {
  2854. t.join();
  2855. }
  2856. }
  2857. t_.join();
  2858. }
  2859. map<string, string> persons_;
  2860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2861. SSLClient cli_;
  2862. SSLServer svr_;
  2863. #else
  2864. Client cli_;
  2865. Server svr_;
  2866. #endif
  2867. thread t_;
  2868. std::vector<thread> request_threads_;
  2869. };
  2870. TEST_F(ServerTest, GetMethod200) {
  2871. auto res = cli_.Get("/hi");
  2872. ASSERT_TRUE(res);
  2873. EXPECT_EQ("HTTP/1.1", res->version);
  2874. EXPECT_EQ(StatusCode::OK_200, res->status);
  2875. EXPECT_EQ("OK", res->reason);
  2876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2877. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2878. EXPECT_EQ("Hello World!", res->body);
  2879. }
  2880. void performance_test(const char *host) {
  2881. auto port = 1234;
  2882. Server svr;
  2883. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  2884. res.set_content("Benchmark Response", "text/plain");
  2885. });
  2886. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  2887. auto se = detail::scope_exit([&] {
  2888. svr.stop();
  2889. listen_thread.join();
  2890. ASSERT_FALSE(svr.is_running());
  2891. });
  2892. svr.wait_until_ready();
  2893. Client cli(host, port);
  2894. auto start = std::chrono::high_resolution_clock::now();
  2895. auto res = cli.Get("/benchmark");
  2896. ASSERT_TRUE(res);
  2897. EXPECT_EQ(StatusCode::OK_200, res->status);
  2898. auto end = std::chrono::high_resolution_clock::now();
  2899. auto elapsed =
  2900. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  2901. .count();
  2902. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  2903. << "ms (Issue #1777)";
  2904. }
  2905. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  2906. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  2907. TEST_F(ServerTest, GetEmptyFile) {
  2908. auto res = cli_.Get("/empty_file");
  2909. ASSERT_TRUE(res);
  2910. EXPECT_EQ(StatusCode::OK_200, res->status);
  2911. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2912. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2913. EXPECT_EQ("", res->body);
  2914. }
  2915. TEST_F(ServerTest, GetFileContent) {
  2916. auto res = cli_.Get("/file_content");
  2917. ASSERT_TRUE(res);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2920. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2921. EXPECT_EQ("test.html", res->body);
  2922. }
  2923. TEST_F(ServerTest, GetFileContentWithRange) {
  2924. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  2925. ASSERT_TRUE(res);
  2926. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2927. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2928. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  2929. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  2930. EXPECT_EQ("est", res->body);
  2931. }
  2932. TEST_F(ServerTest, GetFileContentWithContentType) {
  2933. auto res = cli_.Get("/file_content_with_content_type");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2937. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2938. EXPECT_EQ("file\n", res->body);
  2939. }
  2940. TEST_F(ServerTest, GetInvalidFileContent) {
  2941. auto res = cli_.Get("/invalid_file_content");
  2942. ASSERT_TRUE(res);
  2943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2944. }
  2945. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2946. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2947. ASSERT_TRUE(res);
  2948. EXPECT_EQ("HTTP/1.1", res->version);
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2951. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2952. EXPECT_EQ("Hello World!", res->body);
  2953. }
  2954. TEST_F(ServerTest, GetMethod302) {
  2955. auto res = cli_.Get("/");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::Found_302, res->status);
  2958. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2959. }
  2960. TEST_F(ServerTest, GetMethod302Redirect) {
  2961. cli_.set_follow_location(true);
  2962. auto res = cli_.Get("/");
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ(StatusCode::OK_200, res->status);
  2965. EXPECT_EQ("Hello World!", res->body);
  2966. EXPECT_EQ("/hi", res->location);
  2967. }
  2968. TEST_F(ServerTest, GetMethod404) {
  2969. auto res = cli_.Get("/invalid");
  2970. ASSERT_TRUE(res);
  2971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2972. }
  2973. TEST_F(ServerTest, HeadMethod200) {
  2974. auto res = cli_.Head("/hi");
  2975. ASSERT_TRUE(res);
  2976. EXPECT_EQ(StatusCode::OK_200, res->status);
  2977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2978. EXPECT_TRUE(res->body.empty());
  2979. }
  2980. TEST_F(ServerTest, HeadMethod200Static) {
  2981. auto res = cli_.Head("/mount/dir/index.html");
  2982. ASSERT_TRUE(res);
  2983. EXPECT_EQ(StatusCode::OK_200, res->status);
  2984. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2985. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2986. EXPECT_TRUE(res->body.empty());
  2987. }
  2988. TEST_F(ServerTest, HeadMethod404) {
  2989. auto res = cli_.Head("/invalid");
  2990. ASSERT_TRUE(res);
  2991. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2992. EXPECT_TRUE(res->body.empty());
  2993. }
  2994. TEST_F(ServerTest, GetMethodPersonJohn) {
  2995. auto res = cli_.Get("/person/john");
  2996. ASSERT_TRUE(res);
  2997. EXPECT_EQ(StatusCode::OK_200, res->status);
  2998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2999. EXPECT_EQ("programmer", res->body);
  3000. }
  3001. TEST_F(ServerTest, PostMethod1) {
  3002. auto res = cli_.Get("/person/john1");
  3003. ASSERT_TRUE(res);
  3004. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3005. res = cli_.Post("/person", "name=john1&note=coder",
  3006. "application/x-www-form-urlencoded");
  3007. ASSERT_TRUE(res);
  3008. ASSERT_EQ(StatusCode::OK_200, res->status);
  3009. res = cli_.Get("/person/john1");
  3010. ASSERT_TRUE(res);
  3011. ASSERT_EQ(StatusCode::OK_200, res->status);
  3012. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3013. ASSERT_EQ("coder", res->body);
  3014. }
  3015. TEST_F(ServerTest, PostMethod2) {
  3016. auto res = cli_.Get("/person/john2");
  3017. ASSERT_TRUE(res);
  3018. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3019. Params params;
  3020. params.emplace("name", "john2");
  3021. params.emplace("note", "coder");
  3022. res = cli_.Post("/person", params);
  3023. ASSERT_TRUE(res);
  3024. ASSERT_EQ(StatusCode::OK_200, res->status);
  3025. res = cli_.Get("/person/john2");
  3026. ASSERT_TRUE(res);
  3027. ASSERT_EQ(StatusCode::OK_200, res->status);
  3028. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3029. ASSERT_EQ("coder", res->body);
  3030. }
  3031. TEST_F(ServerTest, PutMethod3) {
  3032. auto res = cli_.Get("/person/john3");
  3033. ASSERT_TRUE(res);
  3034. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3035. Params params;
  3036. params.emplace("name", "john3");
  3037. params.emplace("note", "coder");
  3038. res = cli_.Put("/person", params);
  3039. ASSERT_TRUE(res);
  3040. ASSERT_EQ(StatusCode::OK_200, res->status);
  3041. res = cli_.Get("/person/john3");
  3042. ASSERT_TRUE(res);
  3043. ASSERT_EQ(StatusCode::OK_200, res->status);
  3044. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3045. ASSERT_EQ("coder", res->body);
  3046. }
  3047. TEST_F(ServerTest, DeleteMethod1) {
  3048. auto res = cli_.Get("/person/john4");
  3049. ASSERT_TRUE(res);
  3050. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3051. Params params;
  3052. params.emplace("name", "john4");
  3053. params.emplace("note", "coder");
  3054. res = cli_.Post("/person", params);
  3055. ASSERT_TRUE(res);
  3056. ASSERT_EQ(StatusCode::OK_200, res->status);
  3057. res = cli_.Get("/person/john4");
  3058. ASSERT_TRUE(res);
  3059. ASSERT_EQ(StatusCode::OK_200, res->status);
  3060. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3061. ASSERT_EQ("coder", res->body);
  3062. Params delete_params;
  3063. delete_params.emplace("name", "john4");
  3064. res = cli_.Delete("/person", delete_params);
  3065. ASSERT_TRUE(res);
  3066. ASSERT_EQ(StatusCode::OK_200, res->status);
  3067. ASSERT_EQ("DELETED", res->body);
  3068. res = cli_.Get("/person/john4");
  3069. ASSERT_TRUE(res);
  3070. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3071. }
  3072. TEST_F(ServerTest, DeleteMethod2) {
  3073. auto res = cli_.Get("/person/john5");
  3074. ASSERT_TRUE(res);
  3075. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3076. Params params;
  3077. params.emplace("name", "john5");
  3078. params.emplace("note", "developer");
  3079. res = cli_.Post("/person", params);
  3080. ASSERT_TRUE(res);
  3081. ASSERT_EQ(StatusCode::OK_200, res->status);
  3082. res = cli_.Get("/person/john5");
  3083. ASSERT_TRUE(res);
  3084. ASSERT_EQ(StatusCode::OK_200, res->status);
  3085. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3086. ASSERT_EQ("developer", res->body);
  3087. Params delete_params;
  3088. delete_params.emplace("name", "john5");
  3089. Headers headers;
  3090. headers.emplace("Custom-Header", "test-value");
  3091. res = cli_.Delete("/person", headers, delete_params);
  3092. ASSERT_TRUE(res);
  3093. ASSERT_EQ(StatusCode::OK_200, res->status);
  3094. ASSERT_EQ("DELETED", res->body);
  3095. res = cli_.Get("/person/john5");
  3096. ASSERT_TRUE(res);
  3097. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3098. }
  3099. TEST_F(ServerTest, DeleteMethod3) {
  3100. auto res = cli_.Get("/person/john6");
  3101. ASSERT_TRUE(res);
  3102. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3103. Params params;
  3104. params.emplace("name", "john6");
  3105. params.emplace("note", "tester");
  3106. res = cli_.Post("/person", params);
  3107. ASSERT_TRUE(res);
  3108. ASSERT_EQ(StatusCode::OK_200, res->status);
  3109. res = cli_.Get("/person/john6");
  3110. ASSERT_TRUE(res);
  3111. ASSERT_EQ(StatusCode::OK_200, res->status);
  3112. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3113. ASSERT_EQ("tester", res->body);
  3114. Params delete_params;
  3115. delete_params.emplace("name", "john6");
  3116. Headers headers;
  3117. headers.emplace("Custom-Header", "test-value");
  3118. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3119. ASSERT_TRUE(res);
  3120. ASSERT_EQ(StatusCode::OK_200, res->status);
  3121. ASSERT_EQ("DELETED", res->body);
  3122. res = cli_.Get("/person/john6");
  3123. ASSERT_TRUE(res);
  3124. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3125. }
  3126. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3127. Params params;
  3128. params.emplace("json", JSON_DATA);
  3129. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3130. ASSERT_TRUE(res);
  3131. ASSERT_EQ(StatusCode::OK_200, res->status);
  3132. ASSERT_EQ(JSON_DATA, res->body);
  3133. }
  3134. TEST_F(ServerTest, PostEmptyContent) {
  3135. auto res = cli_.Post("/empty", "", "text/plain");
  3136. ASSERT_TRUE(res);
  3137. ASSERT_EQ(StatusCode::OK_200, res->status);
  3138. ASSERT_EQ("empty", res->body);
  3139. }
  3140. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3141. auto res = cli_.Post("/empty-no-content-type");
  3142. ASSERT_TRUE(res);
  3143. ASSERT_EQ(StatusCode::OK_200, res->status);
  3144. ASSERT_EQ("empty-no-content-type", res->body);
  3145. }
  3146. TEST_F(ServerTest, PostPathOnly) {
  3147. auto res = cli_.Post("/path-only");
  3148. ASSERT_TRUE(res);
  3149. ASSERT_EQ(StatusCode::OK_200, res->status);
  3150. ASSERT_EQ("path-only", res->body);
  3151. }
  3152. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3153. auto res = cli_.Post("/path-headers-only",
  3154. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3155. ASSERT_TRUE(res);
  3156. ASSERT_EQ(StatusCode::OK_200, res->status);
  3157. ASSERT_EQ("path-headers-only", res->body);
  3158. }
  3159. TEST_F(ServerTest, PostLarge) {
  3160. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3161. ASSERT_TRUE(res);
  3162. ASSERT_EQ(StatusCode::OK_200, res->status);
  3163. EXPECT_EQ(LARGE_DATA, res->body);
  3164. }
  3165. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3166. auto res = cli_.Put("/empty-no-content-type");
  3167. ASSERT_TRUE(res);
  3168. ASSERT_EQ(StatusCode::OK_200, res->status);
  3169. ASSERT_EQ("empty-no-content-type", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetMethodDir) {
  3172. auto res = cli_.Get("/dir/");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::OK_200, res->status);
  3175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3176. auto body = R"(<html>
  3177. <head>
  3178. </head>
  3179. <body>
  3180. <a href="/dir/test.html">Test</a>
  3181. <a href="/hi">hi</a>
  3182. </body>
  3183. </html>
  3184. )";
  3185. EXPECT_EQ(body, res->body);
  3186. }
  3187. TEST_F(ServerTest, GetMethodDirTest) {
  3188. auto res = cli_.Get("/dir/test.html");
  3189. ASSERT_TRUE(res);
  3190. EXPECT_EQ(StatusCode::OK_200, res->status);
  3191. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3192. EXPECT_EQ("test.html", res->body);
  3193. }
  3194. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3195. auto res = cli_.Get("/dir/../dir/test.html");
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3199. EXPECT_EQ("test.html", res->body);
  3200. }
  3201. TEST_F(ServerTest, GetMethodInvalidPath) {
  3202. auto res = cli_.Get("/dir/../test.html");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3205. }
  3206. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3207. auto res = cli_.Get("/../www/dir/test.html");
  3208. ASSERT_TRUE(res);
  3209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3210. }
  3211. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3212. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3215. }
  3216. TEST_F(ServerTest, GetMethodDirMountTest) {
  3217. auto res = cli_.Get("/mount/dir/test.html");
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("test.html", res->body);
  3222. }
  3223. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3224. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3228. EXPECT_EQ("test.html", res->body);
  3229. }
  3230. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3231. auto res = cli_.Get("/mount/dir/../test.html");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3234. }
  3235. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3236. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3237. ASSERT_TRUE(res);
  3238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3239. }
  3240. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3241. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3246. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3249. }
  3250. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3251. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3252. ASSERT_TRUE(res);
  3253. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3254. }
  3255. TEST_F(ServerTest, PostMethod303) {
  3256. auto res = cli_.Post("/1", "body", "text/plain");
  3257. ASSERT_TRUE(res);
  3258. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3259. EXPECT_EQ("/2", res->get_header_value("Location"));
  3260. }
  3261. TEST_F(ServerTest, PostMethod303Redirect) {
  3262. cli_.set_follow_location(true);
  3263. auto res = cli_.Post("/1", "body", "text/plain");
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. EXPECT_EQ("redirected.", res->body);
  3267. EXPECT_EQ("/2", res->location);
  3268. }
  3269. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3270. auto res = cli_.Get("/dir/test.abcde");
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3274. EXPECT_EQ("abcde", res->body);
  3275. }
  3276. TEST_F(ServerTest, StaticFileRange) {
  3277. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3278. ASSERT_TRUE(res);
  3279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3280. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3281. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3282. EXPECT_EQ(true, res->has_header("Content-Range"));
  3283. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3284. EXPECT_EQ(std::string("cd"), res->body);
  3285. }
  3286. TEST_F(ServerTest, StaticFileRanges) {
  3287. auto res =
  3288. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3291. EXPECT_TRUE(
  3292. res->get_header_value("Content-Type")
  3293. .find(
  3294. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3295. 0);
  3296. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3297. }
  3298. TEST_F(ServerTest, StaticFileRangeHead) {
  3299. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3300. ASSERT_TRUE(res);
  3301. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3302. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3303. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3304. EXPECT_EQ(true, res->has_header("Content-Range"));
  3305. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3306. }
  3307. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3308. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3309. ASSERT_TRUE(res);
  3310. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3311. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3312. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3313. EXPECT_EQ(true, res->has_header("Content-Range"));
  3314. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3315. res->get_header_value("Content-Range"));
  3316. EXPECT_EQ("LAST\n", res->body);
  3317. }
  3318. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3319. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3322. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3323. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3324. EXPECT_EQ(true, res->has_header("Content-Range"));
  3325. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3326. }
  3327. TEST_F(ServerTest, StaticFileBigFile) {
  3328. auto res = cli_.Get("/dir/1MB.txt");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3333. }
  3334. TEST_F(ServerTest, InvalidBaseDirMount) {
  3335. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3336. }
  3337. TEST_F(ServerTest, Binary) {
  3338. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3339. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3340. "application/octet-stream");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ(4U, res->body.size());
  3344. res = cli_.Put("/binary", binary.data(), binary.size(),
  3345. "application/octet-stream");
  3346. ASSERT_TRUE(res);
  3347. ASSERT_EQ(StatusCode::OK_200, res->status);
  3348. ASSERT_EQ(4U, res->body.size());
  3349. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3350. "application/octet-stream");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ(4U, res->body.size());
  3354. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3355. "application/octet-stream");
  3356. ASSERT_TRUE(res);
  3357. ASSERT_EQ(StatusCode::OK_200, res->status);
  3358. ASSERT_EQ(4U, res->body.size());
  3359. }
  3360. TEST_F(ServerTest, BinaryString) {
  3361. auto binary = std::string("\x00\x01\x02\x03", 4);
  3362. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3363. ASSERT_TRUE(res);
  3364. ASSERT_EQ(StatusCode::OK_200, res->status);
  3365. ASSERT_EQ(4U, res->body.size());
  3366. res = cli_.Put("/binary", binary, "application/octet-stream");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ(4U, res->body.size());
  3370. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3371. ASSERT_TRUE(res);
  3372. ASSERT_EQ(StatusCode::OK_200, res->status);
  3373. ASSERT_EQ(4U, res->body.size());
  3374. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3375. ASSERT_TRUE(res);
  3376. ASSERT_EQ(StatusCode::OK_200, res->status);
  3377. ASSERT_EQ(4U, res->body.size());
  3378. }
  3379. TEST_F(ServerTest, EmptyRequest) {
  3380. auto res = cli_.Get("");
  3381. ASSERT_TRUE(!res);
  3382. EXPECT_EQ(Error::Connection, res.error());
  3383. }
  3384. TEST_F(ServerTest, LongRequest) {
  3385. std::string request;
  3386. for (size_t i = 0; i < 545; i++) {
  3387. request += "/TooLongRequest";
  3388. }
  3389. request += "OK";
  3390. auto res = cli_.Get(request.c_str());
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, TooLongRequest) {
  3395. std::string request;
  3396. for (size_t i = 0; i < 546; i++) {
  3397. request += "/TooLongRequest";
  3398. }
  3399. request += "_NG";
  3400. auto res = cli_.Get(request.c_str());
  3401. ASSERT_TRUE(res);
  3402. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3403. }
  3404. TEST_F(ServerTest, AlmostTooLongRequest) {
  3405. // test for #2046 - URI length check shouldn't include other content on req
  3406. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3407. // leading /, space, HTTP/1.1)
  3408. std::string request =
  3409. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3410. auto res = cli_.Get(request.c_str());
  3411. ASSERT_TRUE(res);
  3412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3413. }
  3414. TEST_F(ServerTest, LongHeader) {
  3415. Request req;
  3416. req.method = "GET";
  3417. req.path = "/hi";
  3418. std::string host_and_port;
  3419. host_and_port += HOST;
  3420. host_and_port += ":";
  3421. host_and_port += std::to_string(PORT);
  3422. req.headers.emplace("Host", host_and_port.c_str());
  3423. req.headers.emplace("Accept", "*/*");
  3424. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3425. req.headers.emplace(
  3426. "Header-Name",
  3427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3445. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3446. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3447. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3448. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3449. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3450. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3451. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3452. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3453. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3454. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3455. "@@@@@@@@@@@@@@@@");
  3456. auto res = std::make_shared<Response>();
  3457. auto error = Error::Success;
  3458. auto ret = cli_.send(req, *res, error);
  3459. ASSERT_TRUE(ret);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. }
  3462. TEST_F(ServerTest, LongQueryValue) {
  3463. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3466. }
  3467. TEST_F(ServerTest, TooLongQueryValue) {
  3468. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3469. ASSERT_FALSE(res);
  3470. EXPECT_EQ(Error::Read, res.error());
  3471. }
  3472. TEST_F(ServerTest, TooLongHeader) {
  3473. Request req;
  3474. req.method = "GET";
  3475. req.path = "/hi";
  3476. std::string host_and_port;
  3477. host_and_port += HOST;
  3478. host_and_port += ":";
  3479. host_and_port += std::to_string(PORT);
  3480. req.headers.emplace("Host", host_and_port.c_str());
  3481. req.headers.emplace("Accept", "*/*");
  3482. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3483. req.headers.emplace(
  3484. "Header-Name",
  3485. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3486. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3487. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3488. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3489. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3490. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3491. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3492. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3493. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3494. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3495. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3496. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3497. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3498. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3499. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3500. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3501. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3502. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3503. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3504. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3505. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3506. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3507. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3508. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3509. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3510. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3511. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3512. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3513. "@@@@@@@@@@@@@@@@@");
  3514. auto res = std::make_shared<Response>();
  3515. auto error = Error::Success;
  3516. auto ret = cli_.send(req, *res, error);
  3517. ASSERT_TRUE(ret);
  3518. EXPECT_EQ(StatusCode::OK_200, res->status);
  3519. }
  3520. TEST_F(ServerTest, HeaderCountAtLimit) {
  3521. // Test with headers just under the 100 limit
  3522. httplib::Headers headers;
  3523. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3524. // This should keep us just under the 100 header limit
  3525. for (int i = 0; i < 95; i++) {
  3526. std::string name = "X-Test-Header-" + std::to_string(i);
  3527. std::string value = "value" + std::to_string(i);
  3528. headers.emplace(name, value);
  3529. }
  3530. // This should work fine as we're under the limit
  3531. auto res = cli_.Get("/hi", headers);
  3532. EXPECT_TRUE(res);
  3533. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3534. }
  3535. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3536. // Test with many headers to exceed the 100 limit
  3537. httplib::Headers headers;
  3538. // Add 150 headers to definitely exceed the 100 limit
  3539. for (int i = 0; i < 150; i++) {
  3540. std::string name = "X-Test-Header-" + std::to_string(i);
  3541. std::string value = "value" + std::to_string(i);
  3542. headers.emplace(name, value);
  3543. }
  3544. // This should fail due to exceeding header count limit
  3545. auto res = cli_.Get("/hi", headers);
  3546. // The request should either fail or return 400 Bad Request
  3547. if (res) {
  3548. // If we get a response, it should be 400 Bad Request
  3549. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3550. } else {
  3551. // Or the request should fail entirely
  3552. EXPECT_FALSE(res);
  3553. }
  3554. }
  3555. TEST_F(ServerTest, PercentEncoding) {
  3556. auto res = cli_.Get("/e%6edwith%");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. TEST_F(ServerTest, PercentEncodingUnicode) {
  3561. auto res = cli_.Get("/e%u006edwith%");
  3562. ASSERT_TRUE(res);
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. }
  3565. TEST_F(ServerTest, InvalidPercentEncoding) {
  3566. auto res = cli_.Get("/%endwith%");
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3569. }
  3570. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3571. auto res = cli_.Get("/%uendwith%");
  3572. ASSERT_TRUE(res);
  3573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3574. }
  3575. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3576. auto res = cli_.Get("/hello?aaa=bbb%");
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3579. }
  3580. TEST_F(ServerTest, PlusSignEncoding) {
  3581. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ("a +b", res->body);
  3585. }
  3586. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3587. // This test simulates a potential DoS attack using many headers
  3588. // to verify our security fix prevents memory exhaustion
  3589. httplib::Headers attack_headers;
  3590. // Attempt to add many headers like an attacker would (200 headers to far
  3591. // exceed limit)
  3592. for (int i = 0; i < 200; i++) {
  3593. std::string name = "X-Attack-Header-" + std::to_string(i);
  3594. std::string value = "attack_payload_" + std::to_string(i);
  3595. attack_headers.emplace(name, value);
  3596. }
  3597. // Try to POST with excessive headers
  3598. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3599. // Should either fail or return 400 Bad Request due to security limit
  3600. if (res) {
  3601. // If we get a response, it should be 400 Bad Request
  3602. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3603. } else {
  3604. // Request failed, which is the expected behavior for DoS protection
  3605. EXPECT_FALSE(res);
  3606. }
  3607. }
  3608. TEST_F(ServerTest, MultipartFormData) {
  3609. MultipartFormDataItemsForClientInput items = {
  3610. {"text1", "text default", "", ""},
  3611. {"text2", "aωb", "", ""},
  3612. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3613. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3614. {"file3", "", "", "application/octet-stream"},
  3615. {"file4", "", "", " application/json tmp-string "}};
  3616. auto res = cli_.Post("/multipart", items);
  3617. ASSERT_TRUE(res);
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. }
  3620. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3621. MultipartFormDataItemsForClientInput items = {
  3622. {"text", "default text", "", ""},
  3623. {"multi_text1", "aaaaa", "", ""},
  3624. {"multi_text1", "bbbbb", "", ""},
  3625. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3626. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3627. "application/json"},
  3628. };
  3629. auto res = cli_.Post("/multipart/multi_file_values", items);
  3630. ASSERT_TRUE(res);
  3631. EXPECT_EQ(StatusCode::OK_200, res->status);
  3632. }
  3633. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3634. auto res = cli_.Get("/hi");
  3635. ASSERT_TRUE(res);
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3638. EXPECT_EQ("Hello World!", res->body);
  3639. }
  3640. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3641. Request req;
  3642. req.method = "POST";
  3643. req.path = "/chunked";
  3644. std::string host_and_port;
  3645. host_and_port += HOST;
  3646. host_and_port += ":";
  3647. host_and_port += std::to_string(PORT);
  3648. req.headers.emplace("Host", host_and_port.c_str());
  3649. req.headers.emplace("Accept", "*/*");
  3650. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3651. req.headers.emplace("Content-Type", "text/plain");
  3652. req.headers.emplace("Content-Length", "0");
  3653. req.headers.emplace(
  3654. "Transfer-Encoding",
  3655. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3656. // Client does not chunk, so make a chunked body manually.
  3657. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3658. auto res = std::make_shared<Response>();
  3659. auto error = Error::Success;
  3660. auto ret = cli_.send(req, *res, error);
  3661. ASSERT_TRUE(ret);
  3662. EXPECT_EQ(StatusCode::OK_200, res->status);
  3663. }
  3664. TEST_F(ServerTest, GetStreamed2) {
  3665. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3668. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3669. EXPECT_EQ(true, res->has_header("Content-Range"));
  3670. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3671. EXPECT_EQ(std::string("ab"), res->body);
  3672. }
  3673. TEST_F(ServerTest, GetStreamed) {
  3674. auto res = cli_.Get("/streamed");
  3675. ASSERT_TRUE(res);
  3676. EXPECT_EQ(StatusCode::OK_200, res->status);
  3677. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3678. EXPECT_EQ(std::string("aaabbb"), res->body);
  3679. }
  3680. TEST_F(ServerTest, GetStreamedWithRange1) {
  3681. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3682. ASSERT_TRUE(res);
  3683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3684. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3685. EXPECT_EQ(true, res->has_header("Content-Range"));
  3686. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3687. EXPECT_EQ(std::string("def"), res->body);
  3688. }
  3689. TEST_F(ServerTest, GetStreamedWithRange2) {
  3690. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3693. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3694. EXPECT_EQ(true, res->has_header("Content-Range"));
  3695. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3696. EXPECT_EQ(std::string("bcdefg"), res->body);
  3697. }
  3698. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3699. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3702. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3703. EXPECT_EQ(true, res->has_header("Content-Range"));
  3704. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3705. EXPECT_EQ(std::string("efg"), res->body);
  3706. }
  3707. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3708. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3711. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3712. EXPECT_EQ(false, res->has_header("Content-Range"));
  3713. EXPECT_EQ(0U, res->body.size());
  3714. }
  3715. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3716. auto res = cli_.Get("/streamed-with-range",
  3717. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3718. "92233720368547758079223372036854775807"}});
  3719. ASSERT_TRUE(res);
  3720. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3721. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3722. EXPECT_EQ(false, res->has_header("Content-Range"));
  3723. EXPECT_EQ(0U, res->body.size());
  3724. }
  3725. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3726. auto res = cli_.Get(
  3727. "/with-range",
  3728. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3729. {"Accept-Encoding", ""}});
  3730. ASSERT_TRUE(res);
  3731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3732. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3733. EXPECT_EQ(true, res->has_header("Content-Range"));
  3734. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3735. EXPECT_EQ(std::string("abcdefg"), res->body);
  3736. }
  3737. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3738. auto res = cli_.Get("/with-range", {
  3739. {"Range", "bytes=0-"},
  3740. {"Accept-Encoding", ""},
  3741. });
  3742. ASSERT_TRUE(res);
  3743. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3744. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3745. EXPECT_EQ(true, res->has_header("Content-Range"));
  3746. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3747. EXPECT_EQ(std::string("abcdefg"), res->body);
  3748. }
  3749. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3750. auto res =
  3751. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3752. ASSERT_TRUE(res);
  3753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3754. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3755. EXPECT_EQ(false, res->has_header("Content-Range"));
  3756. EXPECT_EQ(267U, res->body.size());
  3757. // Check that both range contents are present
  3758. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3759. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3760. // Check that Content-Range headers are present for both ranges
  3761. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3762. std::string::npos);
  3763. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3764. std::string::npos);
  3765. }
  3766. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3767. Ranges ranges;
  3768. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3769. ranges.emplace_back(0, -1);
  3770. }
  3771. auto res =
  3772. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3775. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3776. EXPECT_EQ(false, res->has_header("Content-Range"));
  3777. EXPECT_EQ(0U, res->body.size());
  3778. }
  3779. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3780. auto res =
  3781. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3782. ASSERT_TRUE(res);
  3783. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3784. EXPECT_EQ(5U, res->body.size());
  3785. // Check that overlapping ranges are coalesced into a single range
  3786. EXPECT_EQ("bcdef", res->body);
  3787. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3788. // Should be single range, not multipart
  3789. EXPECT_TRUE(res->has_header("Content-Range"));
  3790. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3791. }
  3792. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3793. auto res =
  3794. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3797. EXPECT_EQ(268U, res->body.size());
  3798. // Check that both range contents are present
  3799. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3800. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3801. // Check that Content-Range headers are present for both ranges
  3802. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3803. std::string::npos);
  3804. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3805. std::string::npos);
  3806. }
  3807. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3808. auto res =
  3809. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3812. EXPECT_EQ(269U, res->body.size());
  3813. // Check that both duplicate range contents are present
  3814. size_t first_abc = res->body.find("abc\r\n");
  3815. EXPECT_TRUE(first_abc != std::string::npos);
  3816. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3817. EXPECT_TRUE(second_abc != std::string::npos);
  3818. // Check that Content-Range headers are present for both ranges
  3819. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3820. EXPECT_TRUE(first_range != std::string::npos);
  3821. size_t second_range =
  3822. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3823. EXPECT_TRUE(second_range != std::string::npos);
  3824. }
  3825. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3826. auto res = cli_.Get("/streamed-with-range?error",
  3827. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3830. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3831. EXPECT_EQ(false, res->has_header("Content-Range"));
  3832. EXPECT_EQ(0U, res->body.size());
  3833. }
  3834. TEST_F(ServerTest, GetStreamedEndless) {
  3835. uint64_t offset = 0;
  3836. auto res = cli_.Get("/streamed-cancel",
  3837. [&](const char * /*data*/, uint64_t data_length) {
  3838. if (offset < 100) {
  3839. offset += data_length;
  3840. return true;
  3841. }
  3842. return false;
  3843. });
  3844. ASSERT_TRUE(!res);
  3845. EXPECT_EQ(Error::Canceled, res.error());
  3846. }
  3847. TEST_F(ServerTest, ClientStop) {
  3848. std::atomic_size_t count{4};
  3849. std::vector<std::thread> threads;
  3850. for (auto i = count.load(); i != 0; --i) {
  3851. threads.emplace_back([&]() {
  3852. auto res = cli_.Get("/streamed-cancel",
  3853. [&](const char *, uint64_t) { return true; });
  3854. --count;
  3855. ASSERT_TRUE(!res);
  3856. EXPECT_TRUE(res.error() == Error::Canceled ||
  3857. res.error() == Error::Read || res.error() == Error::Write);
  3858. });
  3859. }
  3860. std::this_thread::sleep_for(std::chrono::seconds(2));
  3861. while (count != 0) {
  3862. cli_.stop();
  3863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3864. }
  3865. for (auto &t : threads) {
  3866. t.join();
  3867. }
  3868. }
  3869. TEST_F(ServerTest, GetWithRange1) {
  3870. auto res = cli_.Get("/with-range", {
  3871. make_range_header({{3, 5}}),
  3872. {"Accept-Encoding", ""},
  3873. });
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3876. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(true, res->has_header("Content-Range"));
  3878. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3879. EXPECT_EQ(std::string("def"), res->body);
  3880. }
  3881. TEST_F(ServerTest, GetWithRange2) {
  3882. auto res = cli_.Get("/with-range", {
  3883. make_range_header({{1, -1}}),
  3884. {"Accept-Encoding", ""},
  3885. });
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3888. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ(true, res->has_header("Content-Range"));
  3890. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3891. EXPECT_EQ(std::string("bcdefg"), res->body);
  3892. }
  3893. TEST_F(ServerTest, GetWithRange3) {
  3894. auto res = cli_.Get("/with-range", {
  3895. make_range_header({{0, 0}}),
  3896. {"Accept-Encoding", ""},
  3897. });
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3900. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3901. EXPECT_EQ(true, res->has_header("Content-Range"));
  3902. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3903. EXPECT_EQ(std::string("a"), res->body);
  3904. }
  3905. TEST_F(ServerTest, GetWithRange4) {
  3906. auto res = cli_.Get("/with-range", {
  3907. make_range_header({{-1, 2}}),
  3908. {"Accept-Encoding", ""},
  3909. });
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3912. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3913. EXPECT_EQ(true, res->has_header("Content-Range"));
  3914. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3915. EXPECT_EQ(std::string("fg"), res->body);
  3916. }
  3917. TEST_F(ServerTest, GetWithRange5) {
  3918. auto res = cli_.Get("/with-range", {
  3919. make_range_header({{0, 5}}),
  3920. {"Accept-Encoding", ""},
  3921. });
  3922. ASSERT_TRUE(res);
  3923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3924. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3925. EXPECT_EQ(true, res->has_header("Content-Range"));
  3926. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  3927. EXPECT_EQ(std::string("abcdef"), res->body);
  3928. }
  3929. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3930. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3931. ASSERT_TRUE(res);
  3932. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3933. }
  3934. TEST_F(ServerTest, GetWithRangeMultipart) {
  3935. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3936. ASSERT_TRUE(res);
  3937. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3938. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3939. EXPECT_EQ(false, res->has_header("Content-Range"));
  3940. EXPECT_EQ(267U, res->body.size());
  3941. }
  3942. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3943. auto res =
  3944. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3947. }
  3948. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3949. auto res = cli_.Get("/with-range-customized-response",
  3950. {{make_range_header({{1, 2}})}});
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3953. EXPECT_EQ(true, res->has_header("Content-Length"));
  3954. EXPECT_EQ(false, res->has_header("Content-Range"));
  3955. EXPECT_EQ(JSON_DATA, res->body);
  3956. }
  3957. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3958. auto res = cli_.Get("/with-range-customized-response",
  3959. {{make_range_header({{1, 2}, {4, 5}})}});
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3962. EXPECT_EQ(true, res->has_header("Content-Length"));
  3963. EXPECT_EQ(false, res->has_header("Content-Range"));
  3964. EXPECT_EQ(JSON_DATA, res->body);
  3965. }
  3966. TEST_F(ServerTest, Issue1772) {
  3967. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3968. ASSERT_TRUE(res);
  3969. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3970. }
  3971. TEST_F(ServerTest, Issue609) {
  3972. auto res = cli_.Delete("/issue609");
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::OK_200, res->status);
  3975. EXPECT_EQ(std::string("ok"), res->body);
  3976. }
  3977. TEST_F(ServerTest, GetStreamedChunked) {
  3978. auto res = cli_.Get("/streamed-chunked");
  3979. ASSERT_TRUE(res);
  3980. EXPECT_EQ(StatusCode::OK_200, res->status);
  3981. EXPECT_EQ(std::string("123456789"), res->body);
  3982. }
  3983. TEST_F(ServerTest, GetStreamedChunked2) {
  3984. auto res = cli_.Get("/streamed-chunked2");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ(std::string("123456789"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3990. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::OK_200, res->status);
  3993. EXPECT_EQ(std::string("123456789"), res->body);
  3994. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3995. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3996. }
  3997. TEST_F(ServerTest, LargeChunkedPost) {
  3998. Request req;
  3999. req.method = "POST";
  4000. req.path = "/large-chunked";
  4001. std::string host_and_port;
  4002. host_and_port += HOST;
  4003. host_and_port += ":";
  4004. host_and_port += std::to_string(PORT);
  4005. req.headers.emplace("Host", host_and_port.c_str());
  4006. req.headers.emplace("Accept", "*/*");
  4007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4008. req.headers.emplace("Content-Type", "text/plain");
  4009. req.headers.emplace("Content-Length", "0");
  4010. req.headers.emplace("Transfer-Encoding", "chunked");
  4011. std::string long_string(30 * 1024u, 'a');
  4012. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4013. // Attempt to make a large enough post to exceed OS buffers, to test that
  4014. // the server handles short reads if the full chunk data isn't available.
  4015. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4016. auto res = std::make_shared<Response>();
  4017. auto error = Error::Success;
  4018. auto ret = cli_.send(req, *res, error);
  4019. ASSERT_TRUE(ret);
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. }
  4022. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4023. auto res = cli_.Get("/remote_addr");
  4024. ASSERT_TRUE(res);
  4025. EXPECT_EQ(StatusCode::OK_200, res->status);
  4026. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4027. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4028. }
  4029. TEST_F(ServerTest, GetMethodLocalAddr) {
  4030. auto res = cli_.Get("/local_addr");
  4031. ASSERT_TRUE(res);
  4032. EXPECT_EQ(StatusCode::OK_200, res->status);
  4033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4034. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4035. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4036. }
  4037. TEST_F(ServerTest, HTTPResponseSplitting) {
  4038. auto res = cli_.Get("/http_response_splitting");
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. TEST_F(ServerTest, SlowRequest) {
  4043. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4044. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4045. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4046. }
  4047. #if 0
  4048. TEST_F(ServerTest, SlowPost) {
  4049. char buffer[64 * 1024];
  4050. memset(buffer, 0x42, sizeof(buffer));
  4051. auto res = cli_.Post(
  4052. "/slowpost", 64 * 1024 * 1024,
  4053. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4054. auto ret = sink.write(buffer, sizeof(buffer));
  4055. EXPECT_TRUE(ret);
  4056. return true;
  4057. },
  4058. "text/plain");
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::OK_200, res->status);
  4061. }
  4062. TEST_F(ServerTest, SlowPostFail) {
  4063. char buffer[64 * 1024];
  4064. memset(buffer, 0x42, sizeof(buffer));
  4065. cli_.set_write_timeout(std::chrono::seconds(0));
  4066. auto res = cli_.Post(
  4067. "/slowpost", 64 * 1024 * 1024,
  4068. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4069. sink.write(buffer, sizeof(buffer));
  4070. return true;
  4071. },
  4072. "text/plain");
  4073. ASSERT_TRUE(!res);
  4074. EXPECT_EQ(Error::Write, res.error());
  4075. }
  4076. #endif
  4077. TEST_F(ServerTest, Put) {
  4078. auto res = cli_.Put("/put", "PUT", "text/plain");
  4079. ASSERT_TRUE(res);
  4080. EXPECT_EQ(StatusCode::OK_200, res->status);
  4081. EXPECT_EQ("PUT", res->body);
  4082. }
  4083. TEST_F(ServerTest, PutWithContentProvider) {
  4084. auto res = cli_.Put(
  4085. "/put", 3,
  4086. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4087. sink.os << "PUT";
  4088. return true;
  4089. },
  4090. "text/plain");
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("PUT", res->body);
  4094. }
  4095. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4096. auto res = cli_.Post(
  4097. "/post", 42,
  4098. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4099. return false;
  4100. },
  4101. "text/plain");
  4102. ASSERT_TRUE(!res);
  4103. EXPECT_EQ(Error::Canceled, res.error());
  4104. }
  4105. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4106. auto res = cli_.Put(
  4107. "/put",
  4108. [](size_t /*offset*/, DataSink &sink) {
  4109. sink.os << "PUT";
  4110. sink.done();
  4111. return true;
  4112. },
  4113. "text/plain");
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::OK_200, res->status);
  4116. EXPECT_EQ("PUT", res->body);
  4117. }
  4118. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4119. auto res = cli_.Post(
  4120. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4121. "text/plain");
  4122. ASSERT_TRUE(!res);
  4123. EXPECT_EQ(Error::Canceled, res.error());
  4124. }
  4125. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4126. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4127. cli_.set_compress(true);
  4128. auto res = cli_.Put(
  4129. "/put", 3,
  4130. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4131. sink.os << "PUT";
  4132. return true;
  4133. },
  4134. "text/plain");
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::OK_200, res->status);
  4137. EXPECT_EQ("PUT", res->body);
  4138. }
  4139. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4140. cli_.set_compress(true);
  4141. auto res = cli_.Post(
  4142. "/post", 42,
  4143. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4144. return false;
  4145. },
  4146. "text/plain");
  4147. ASSERT_TRUE(!res);
  4148. EXPECT_EQ(Error::Canceled, res.error());
  4149. }
  4150. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4151. cli_.set_compress(true);
  4152. auto res = cli_.Put(
  4153. "/put",
  4154. [](size_t /*offset*/, DataSink &sink) {
  4155. sink.os << "PUT";
  4156. sink.done();
  4157. return true;
  4158. },
  4159. "text/plain");
  4160. ASSERT_TRUE(res);
  4161. EXPECT_EQ(StatusCode::OK_200, res->status);
  4162. EXPECT_EQ("PUT", res->body);
  4163. }
  4164. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4165. cli_.set_compress(true);
  4166. auto res = cli_.Post(
  4167. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4168. "text/plain");
  4169. ASSERT_TRUE(!res);
  4170. EXPECT_EQ(Error::Canceled, res.error());
  4171. }
  4172. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4173. cli_.set_compress(true);
  4174. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. EXPECT_EQ(LARGE_DATA, res->body);
  4178. }
  4179. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4181. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4182. Client cli(s.c_str());
  4183. cli.enable_server_certificate_verification(false);
  4184. #else
  4185. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4186. Client cli(s.c_str());
  4187. #endif
  4188. cli.set_compress(true);
  4189. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ(LARGE_DATA, res->body);
  4193. // The compressed size should be less than a 10th of the original. May vary
  4194. // depending on the zlib library.
  4195. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4196. static_cast<uint64_t>(10 * 1024 * 1024));
  4197. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4198. }
  4199. TEST_F(ServerTest, PutContentWithDeflate) {
  4200. cli_.set_compress(false);
  4201. Headers headers;
  4202. headers.emplace("Content-Encoding", "deflate");
  4203. // PUT in deflate format:
  4204. auto res = cli_.Put("/put", headers,
  4205. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::OK_200, res->status);
  4208. EXPECT_EQ("PUT", res->body);
  4209. }
  4210. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4211. Headers headers;
  4212. headers.emplace("Accept-Encoding", "gzip, deflate");
  4213. auto res = cli_.Get("/streamed-chunked", headers);
  4214. ASSERT_TRUE(res);
  4215. EXPECT_EQ(StatusCode::OK_200, res->status);
  4216. EXPECT_EQ(std::string("123456789"), res->body);
  4217. }
  4218. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4219. Headers headers;
  4220. headers.emplace("Accept-Encoding", "gzip, deflate");
  4221. auto res = cli_.Get("/streamed-chunked2", headers);
  4222. ASSERT_TRUE(res);
  4223. EXPECT_EQ(StatusCode::OK_200, res->status);
  4224. EXPECT_EQ(std::string("123456789"), res->body);
  4225. }
  4226. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4227. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST(GzipDecompressor, ChunkedDecompression) {
  4232. std::string data;
  4233. for (size_t i = 0; i < 32 * 1024; ++i) {
  4234. data.push_back(static_cast<char>('a' + i % 26));
  4235. }
  4236. std::string compressed_data;
  4237. {
  4238. httplib::detail::gzip_compressor compressor;
  4239. bool result = compressor.compress(
  4240. data.data(), data.size(),
  4241. /*last=*/true,
  4242. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4243. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4244. compressed_data_size);
  4245. return true;
  4246. });
  4247. ASSERT_TRUE(result);
  4248. }
  4249. std::string decompressed_data;
  4250. {
  4251. httplib::detail::gzip_decompressor decompressor;
  4252. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4253. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4254. size_t chunk_size = 130;
  4255. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4256. chunk_begin += chunk_size) {
  4257. size_t current_chunk_size =
  4258. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4259. bool result = decompressor.decompress(
  4260. compressed_data.data() + chunk_begin, current_chunk_size,
  4261. [&](const char *decompressed_data_chunk,
  4262. size_t decompressed_data_chunk_size) {
  4263. decompressed_data.insert(decompressed_data.size(),
  4264. decompressed_data_chunk,
  4265. decompressed_data_chunk_size);
  4266. return true;
  4267. });
  4268. ASSERT_TRUE(result);
  4269. }
  4270. }
  4271. ASSERT_EQ(data, decompressed_data);
  4272. }
  4273. TEST(GzipDecompressor, DeflateDecompression) {
  4274. std::string original_text = "Raw deflate without gzip";
  4275. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4276. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4277. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4278. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4279. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4280. std::string decompressed_data;
  4281. {
  4282. httplib::detail::gzip_decompressor decompressor;
  4283. bool result = decompressor.decompress(
  4284. compressed_data.data(), compressed_data.size(),
  4285. [&](const char *decompressed_data_chunk,
  4286. size_t decompressed_data_chunk_size) {
  4287. decompressed_data.insert(decompressed_data.size(),
  4288. decompressed_data_chunk,
  4289. decompressed_data_chunk_size);
  4290. return true;
  4291. });
  4292. ASSERT_TRUE(result);
  4293. }
  4294. ASSERT_EQ(original_text, decompressed_data);
  4295. }
  4296. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4297. std::string original_text = "Raw deflate without gzip";
  4298. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4299. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4300. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4301. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4302. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4303. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4304. std::string decompressed_data;
  4305. {
  4306. httplib::detail::gzip_decompressor decompressor;
  4307. bool result = decompressor.decompress(
  4308. compressed_data.data(), compressed_data.size(),
  4309. [&](const char *decompressed_data_chunk,
  4310. size_t decompressed_data_chunk_size) {
  4311. decompressed_data.insert(decompressed_data.size(),
  4312. decompressed_data_chunk,
  4313. decompressed_data_chunk_size);
  4314. return true;
  4315. });
  4316. ASSERT_TRUE(result);
  4317. }
  4318. ASSERT_EQ(original_text, decompressed_data);
  4319. }
  4320. #ifdef _WIN32
  4321. TEST(GzipDecompressor, LargeRandomData) {
  4322. // prepare large random data that is difficult to be compressed and is
  4323. // expected to have large size even when compressed
  4324. std::random_device seed_gen;
  4325. std::mt19937 random(seed_gen());
  4326. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4327. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4328. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4329. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4330. // compress data over 4GiB
  4331. std::string compressed_data;
  4332. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4333. httplib::detail::gzip_compressor compressor;
  4334. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4335. data.size() * sizeof(std::uint32_t), true,
  4336. [&](const char *data, size_t size) {
  4337. compressed_data.insert(
  4338. compressed_data.size(), data, size);
  4339. return true;
  4340. });
  4341. ASSERT_TRUE(result);
  4342. // FIXME: compressed data size is expected to be greater than 4GiB,
  4343. // but there is no guarantee
  4344. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4345. // decompress data over 4GiB
  4346. std::string decompressed_data;
  4347. decompressed_data.reserve(data_size);
  4348. httplib::detail::gzip_decompressor decompressor;
  4349. result = decompressor.decompress(
  4350. compressed_data.data(), compressed_data.size(),
  4351. [&](const char *data, size_t size) {
  4352. decompressed_data.insert(decompressed_data.size(), data, size);
  4353. return true;
  4354. });
  4355. ASSERT_TRUE(result);
  4356. // compare
  4357. ASSERT_EQ(data_size, decompressed_data.size());
  4358. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4359. 0);
  4360. }
  4361. #endif
  4362. #endif
  4363. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4364. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4365. Headers headers;
  4366. headers.emplace("Accept-Encoding", "br");
  4367. auto res = cli_.Get("/streamed-chunked", headers);
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::OK_200, res->status);
  4370. EXPECT_EQ(std::string("123456789"), res->body);
  4371. }
  4372. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4373. Headers headers;
  4374. headers.emplace("Accept-Encoding", "br");
  4375. auto res = cli_.Get("/streamed-chunked2", headers);
  4376. ASSERT_TRUE(res);
  4377. EXPECT_EQ(StatusCode::OK_200, res->status);
  4378. EXPECT_EQ(std::string("123456789"), res->body);
  4379. }
  4380. #endif
  4381. TEST_F(ServerTest, Patch) {
  4382. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. EXPECT_EQ("PATCH", res->body);
  4386. }
  4387. TEST_F(ServerTest, Delete) {
  4388. auto res = cli_.Delete("/delete");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(StatusCode::OK_200, res->status);
  4391. EXPECT_EQ("DELETE", res->body);
  4392. }
  4393. TEST_F(ServerTest, DeleteContentReceiver) {
  4394. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("content", res->body);
  4398. }
  4399. TEST_F(ServerTest, Options) {
  4400. auto res = cli_.Options("*");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::OK_200, res->status);
  4403. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4404. EXPECT_TRUE(res->body.empty());
  4405. }
  4406. TEST_F(ServerTest, URL) {
  4407. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. }
  4411. TEST_F(ServerTest, ArrayParam) {
  4412. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4413. ASSERT_TRUE(res);
  4414. EXPECT_EQ(StatusCode::OK_200, res->status);
  4415. }
  4416. TEST_F(ServerTest, NoMultipleHeaders) {
  4417. Headers headers = {{"Content-Length", "5"}};
  4418. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4419. "text/plain");
  4420. ASSERT_TRUE(res);
  4421. EXPECT_EQ(StatusCode::OK_200, res->status);
  4422. }
  4423. TEST_F(ServerTest, PostContentReceiver) {
  4424. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4425. ASSERT_TRUE(res);
  4426. ASSERT_EQ(StatusCode::OK_200, res->status);
  4427. ASSERT_EQ("content", res->body);
  4428. }
  4429. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4430. MultipartFormDataItemsForClientInput items = {
  4431. {"text1", "text default", "", ""},
  4432. {"text2", "aωb", "", ""},
  4433. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4434. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4435. {"file3", "", "", "application/octet-stream"},
  4436. };
  4437. auto res = cli_.Post("/content_receiver", items);
  4438. ASSERT_TRUE(res);
  4439. EXPECT_EQ(StatusCode::OK_200, res->status);
  4440. }
  4441. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4442. MultipartFormDataItemsForClientInput items = {
  4443. {"text1", "text default", "", ""},
  4444. {"text2", "aωb", "", ""},
  4445. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4446. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  4447. {"file3", "", "", "application/octet-stream"},
  4448. };
  4449. auto boundary = std::string("+++++");
  4450. std::string body;
  4451. for (const auto &item : items) {
  4452. body += "--" + boundary + "\r\n";
  4453. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4454. if (!item.filename.empty()) {
  4455. body += "; filename=\"" + item.filename + "\"";
  4456. }
  4457. body += "\r\n";
  4458. if (!item.content_type.empty()) {
  4459. body += "Content-Type: " + item.content_type + "\r\n";
  4460. }
  4461. body += "\r\n";
  4462. body += item.content + "\r\n";
  4463. }
  4464. body += "--" + boundary + "--\r\n";
  4465. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4466. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. }
  4470. TEST_F(ServerTest, PostContentReceiverGzip) {
  4471. cli_.set_compress(true);
  4472. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4473. ASSERT_TRUE(res);
  4474. ASSERT_EQ(StatusCode::OK_200, res->status);
  4475. ASSERT_EQ("content", res->body);
  4476. }
  4477. TEST_F(ServerTest, PutContentReceiver) {
  4478. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4479. ASSERT_TRUE(res);
  4480. ASSERT_EQ(StatusCode::OK_200, res->status);
  4481. ASSERT_EQ("content", res->body);
  4482. }
  4483. TEST_F(ServerTest, PatchContentReceiver) {
  4484. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4485. ASSERT_TRUE(res);
  4486. ASSERT_EQ(StatusCode::OK_200, res->status);
  4487. ASSERT_EQ("content", res->body);
  4488. }
  4489. template <typename ClientType>
  4490. void TestWithHeadersAndContentReceiver(
  4491. ClientType &cli,
  4492. std::function<Result(ClientType &, const std::string &, const Headers &,
  4493. const std::string &, const std::string &,
  4494. ContentReceiver, DownloadProgress)>
  4495. request_func) {
  4496. Headers headers;
  4497. headers.emplace("X-Custom-Header", "test-value");
  4498. std::string received_body;
  4499. auto res = request_func(
  4500. cli, "/content_receiver", headers, "content", "application/json",
  4501. [&](const char *data, size_t data_length) {
  4502. received_body.append(data, data_length);
  4503. return true;
  4504. },
  4505. nullptr);
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("content", received_body);
  4509. }
  4510. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4512. using ClientT = SSLClient;
  4513. #else
  4514. using ClientT = Client;
  4515. #endif
  4516. TestWithHeadersAndContentReceiver<ClientT>(
  4517. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4518. const std::string &body, const std::string &content_type,
  4519. ContentReceiver receiver, DownloadProgress progress) {
  4520. return cli.Post(path, headers, body, content_type, receiver, progress);
  4521. });
  4522. }
  4523. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4524. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4525. using ClientT = SSLClient;
  4526. #else
  4527. using ClientT = Client;
  4528. #endif
  4529. TestWithHeadersAndContentReceiver<ClientT>(
  4530. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4531. const std::string &body, const std::string &content_type,
  4532. ContentReceiver receiver, DownloadProgress progress) {
  4533. return cli.Put(path, headers, body, content_type, receiver, progress);
  4534. });
  4535. }
  4536. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4538. using ClientT = SSLClient;
  4539. #else
  4540. using ClientT = Client;
  4541. #endif
  4542. TestWithHeadersAndContentReceiver<ClientT>(
  4543. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4544. const std::string &body, const std::string &content_type,
  4545. ContentReceiver receiver, DownloadProgress progress) {
  4546. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4547. });
  4548. }
  4549. template <typename ClientType>
  4550. void TestWithHeadersAndContentReceiverWithProgress(
  4551. ClientType &cli,
  4552. std::function<Result(ClientType &, const std::string &, const Headers &,
  4553. const std::string &, const std::string &,
  4554. ContentReceiver, DownloadProgress)>
  4555. request_func) {
  4556. Headers headers;
  4557. headers.emplace("X-Test-Header", "progress-test");
  4558. std::string received_body;
  4559. auto progress_called = false;
  4560. auto res = request_func(
  4561. cli, "/content_receiver", headers, "content", "text/plain",
  4562. [&](const char *data, size_t data_length) {
  4563. received_body.append(data, data_length);
  4564. return true;
  4565. },
  4566. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4567. progress_called = true;
  4568. return true;
  4569. });
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(StatusCode::OK_200, res->status);
  4572. EXPECT_EQ("content", received_body);
  4573. EXPECT_TRUE(progress_called);
  4574. }
  4575. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4577. using ClientT = SSLClient;
  4578. #else
  4579. using ClientT = Client;
  4580. #endif
  4581. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4582. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4583. const std::string &body, const std::string &content_type,
  4584. ContentReceiver receiver, DownloadProgress progress) {
  4585. return cli.Post(path, headers, body, content_type, receiver, progress);
  4586. });
  4587. }
  4588. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4590. using ClientT = SSLClient;
  4591. #else
  4592. using ClientT = Client;
  4593. #endif
  4594. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4595. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4596. const std::string &body, const std::string &content_type,
  4597. ContentReceiver receiver, DownloadProgress progress) {
  4598. return cli.Put(path, headers, body, content_type, receiver, progress);
  4599. });
  4600. }
  4601. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4602. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4603. using ClientT = SSLClient;
  4604. #else
  4605. using ClientT = Client;
  4606. #endif
  4607. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4608. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4609. const std::string &body, const std::string &content_type,
  4610. ContentReceiver receiver, DownloadProgress progress) {
  4611. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4612. });
  4613. }
  4614. template <typename ClientType>
  4615. void TestWithHeadersAndContentReceiverError(
  4616. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4617. const Headers &, const std::string &,
  4618. const std::string &, ContentReceiver)>
  4619. request_func) {
  4620. Headers headers;
  4621. headers.emplace("X-Error-Test", "true");
  4622. std::string received_body;
  4623. auto receiver_failed = false;
  4624. auto res =
  4625. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4626. [&](const char *data, size_t data_length) {
  4627. received_body.append(data, data_length);
  4628. receiver_failed = true;
  4629. return false;
  4630. });
  4631. ASSERT_FALSE(res);
  4632. EXPECT_TRUE(receiver_failed);
  4633. }
  4634. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4636. using ClientT = SSLClient;
  4637. #else
  4638. using ClientT = Client;
  4639. #endif
  4640. TestWithHeadersAndContentReceiverError<ClientT>(
  4641. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4642. const std::string &body, const std::string &content_type,
  4643. ContentReceiver receiver) {
  4644. return cli.Post(path, headers, body, content_type, receiver);
  4645. });
  4646. }
  4647. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4648. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4649. using ClientT = SSLClient;
  4650. #else
  4651. using ClientT = Client;
  4652. #endif
  4653. TestWithHeadersAndContentReceiverError<ClientT>(
  4654. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4655. const std::string &body, const std::string &content_type,
  4656. ContentReceiver receiver) {
  4657. return cli.Put(path, headers, body, content_type, receiver);
  4658. });
  4659. }
  4660. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4662. using ClientT = SSLClient;
  4663. #else
  4664. using ClientT = Client;
  4665. #endif
  4666. TestWithHeadersAndContentReceiverError<ClientT>(
  4667. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4668. const std::string &body, const std::string &content_type,
  4669. ContentReceiver receiver) {
  4670. return cli.Patch(path, headers, body, content_type, receiver);
  4671. });
  4672. }
  4673. TEST_F(ServerTest, PostQueryStringAndBody) {
  4674. auto res =
  4675. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4676. ASSERT_TRUE(res);
  4677. ASSERT_EQ(StatusCode::OK_200, res->status);
  4678. }
  4679. TEST_F(ServerTest, HTTP2Magic) {
  4680. Request req;
  4681. req.method = "PRI";
  4682. req.path = "*";
  4683. req.body = "SM";
  4684. auto res = std::make_shared<Response>();
  4685. auto error = Error::Success;
  4686. auto ret = cli_.send(req, *res, error);
  4687. ASSERT_TRUE(ret);
  4688. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4689. }
  4690. TEST_F(ServerTest, KeepAlive) {
  4691. auto res = cli_.Get("/hi");
  4692. ASSERT_TRUE(res);
  4693. EXPECT_EQ(StatusCode::OK_200, res->status);
  4694. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4695. EXPECT_EQ("Hello World!", res->body);
  4696. res = cli_.Get("/hi");
  4697. ASSERT_TRUE(res);
  4698. EXPECT_EQ(StatusCode::OK_200, res->status);
  4699. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4700. EXPECT_EQ("Hello World!", res->body);
  4701. res = cli_.Get("/hi");
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4705. EXPECT_EQ("Hello World!", res->body);
  4706. res = cli_.Get("/not-exist");
  4707. ASSERT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4709. res = cli_.Post("/empty", "", "text/plain");
  4710. ASSERT_TRUE(res);
  4711. EXPECT_EQ(StatusCode::OK_200, res->status);
  4712. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4713. EXPECT_EQ("empty", res->body);
  4714. EXPECT_EQ("close", res->get_header_value("Connection"));
  4715. res = cli_.Post(
  4716. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4717. "text/plain");
  4718. ASSERT_TRUE(res);
  4719. EXPECT_EQ(StatusCode::OK_200, res->status);
  4720. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4721. EXPECT_EQ("empty", res->body);
  4722. cli_.set_keep_alive(false);
  4723. res = cli_.Get("/last-request");
  4724. ASSERT_TRUE(res);
  4725. EXPECT_EQ(StatusCode::OK_200, res->status);
  4726. EXPECT_EQ("close", res->get_header_value("Connection"));
  4727. }
  4728. TEST_F(ServerTest, TooManyRedirect) {
  4729. cli_.set_follow_location(true);
  4730. auto res = cli_.Get("/redirect/0");
  4731. ASSERT_TRUE(!res);
  4732. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4733. }
  4734. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4735. TEST_F(ServerTest, Gzip) {
  4736. Headers headers;
  4737. headers.emplace("Accept-Encoding", "gzip, deflate");
  4738. auto res = cli_.Get("/compress", headers);
  4739. ASSERT_TRUE(res);
  4740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4742. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4743. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4744. "7890123456789012345678901234567890",
  4745. res->body);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. }
  4748. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4749. Headers headers;
  4750. headers.emplace("Accept-Encoding", "");
  4751. auto res = cli_.Get("/compress", headers);
  4752. ASSERT_TRUE(res);
  4753. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4755. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4756. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4757. "7890123456789012345678901234567890",
  4758. res->body);
  4759. EXPECT_EQ(StatusCode::OK_200, res->status);
  4760. }
  4761. TEST_F(ServerTest, GzipWithContentReceiver) {
  4762. Headers headers;
  4763. headers.emplace("Accept-Encoding", "gzip, deflate");
  4764. std::string body;
  4765. auto res = cli_.Get("/compress", headers,
  4766. [&](const char *data, uint64_t data_length) {
  4767. EXPECT_EQ(100U, data_length);
  4768. body.append(data, data_length);
  4769. return true;
  4770. });
  4771. ASSERT_TRUE(res);
  4772. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4773. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4774. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4775. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4776. "7890123456789012345678901234567890",
  4777. body);
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. }
  4780. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4781. Headers headers;
  4782. headers.emplace("Accept-Encoding", "gzip, deflate");
  4783. cli_.set_decompress(false);
  4784. auto res = cli_.Get("/compress", headers);
  4785. ASSERT_TRUE(res);
  4786. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4788. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4789. EXPECT_EQ(33U, res->body.size());
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. }
  4792. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4793. Headers headers;
  4794. headers.emplace("Accept-Encoding", "");
  4795. std::string body;
  4796. auto res = cli_.Get("/compress", headers,
  4797. [&](const char *data, uint64_t data_length) {
  4798. EXPECT_EQ(100U, data_length);
  4799. body.append(data, data_length);
  4800. return true;
  4801. });
  4802. ASSERT_TRUE(res);
  4803. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4804. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4805. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4806. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4807. "7890123456789012345678901234567890",
  4808. body);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, NoGzip) {
  4812. Headers headers;
  4813. headers.emplace("Accept-Encoding", "gzip, deflate");
  4814. auto res = cli_.Get("/nocompress", headers);
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4817. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4818. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4819. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4820. "7890123456789012345678901234567890",
  4821. res->body);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4825. Headers headers;
  4826. headers.emplace("Accept-Encoding", "gzip, deflate");
  4827. std::string body;
  4828. auto res = cli_.Get("/nocompress", headers,
  4829. [&](const char *data, uint64_t data_length) {
  4830. EXPECT_EQ(100U, data_length);
  4831. body.append(data, data_length);
  4832. return true;
  4833. });
  4834. ASSERT_TRUE(res);
  4835. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4836. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4837. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4838. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4839. "7890123456789012345678901234567890",
  4840. body);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. }
  4843. TEST_F(ServerTest, MultipartFormDataGzip) {
  4844. MultipartFormDataItemsForClientInput items = {
  4845. {"key1", "test", "", ""},
  4846. {"key2", "--abcdefg123", "", ""},
  4847. };
  4848. cli_.set_compress(true);
  4849. auto res = cli_.Post("/compress-multipart", items);
  4850. ASSERT_TRUE(res);
  4851. EXPECT_EQ(StatusCode::OK_200, res->status);
  4852. }
  4853. #endif
  4854. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4855. TEST_F(ServerTest, Brotli) {
  4856. Headers headers;
  4857. headers.emplace("Accept-Encoding", "br");
  4858. auto res = cli_.Get("/compress", headers);
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  4861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4862. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4863. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4864. "7890123456789012345678901234567890",
  4865. res->body);
  4866. EXPECT_EQ(StatusCode::OK_200, res->status);
  4867. }
  4868. #endif
  4869. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  4870. TEST_F(ServerTest, Zstd) {
  4871. Headers headers;
  4872. headers.emplace("Accept-Encoding", "zstd");
  4873. auto res = cli_.Get("/compress", headers);
  4874. ASSERT_TRUE(res);
  4875. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4877. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4879. "7890123456789012345678901234567890",
  4880. res->body);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  4884. Headers headers;
  4885. headers.emplace("Accept-Encoding", "");
  4886. auto res = cli_.Get("/compress", headers);
  4887. ASSERT_TRUE(res);
  4888. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4889. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4890. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4891. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4892. "7890123456789012345678901234567890",
  4893. res->body);
  4894. EXPECT_EQ(StatusCode::OK_200, res->status);
  4895. }
  4896. TEST_F(ServerTest, ZstdWithContentReceiver) {
  4897. Headers headers;
  4898. headers.emplace("Accept-Encoding", "zstd");
  4899. std::string body;
  4900. auto res = cli_.Get("/compress", headers,
  4901. [&](const char *data, uint64_t data_length) {
  4902. EXPECT_EQ(100U, data_length);
  4903. body.append(data, data_length);
  4904. return true;
  4905. });
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4908. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4909. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4910. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4911. "7890123456789012345678901234567890",
  4912. body);
  4913. EXPECT_EQ(StatusCode::OK_200, res->status);
  4914. }
  4915. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  4916. Headers headers;
  4917. headers.emplace("Accept-Encoding", "zstd");
  4918. cli_.set_decompress(false);
  4919. auto res = cli_.Get("/compress", headers);
  4920. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  4921. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  4922. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  4923. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  4924. ASSERT_TRUE(res);
  4925. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  4926. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4927. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4928. EXPECT_EQ(StatusCode::OK_200, res->status);
  4929. ASSERT_EQ(26U, res->body.size());
  4930. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  4931. 0);
  4932. }
  4933. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  4934. Headers headers;
  4935. headers.emplace("Accept-Encoding", "");
  4936. std::string body;
  4937. auto res = cli_.Get("/compress", headers,
  4938. [&](const char *data, uint64_t data_length) {
  4939. EXPECT_EQ(100U, data_length);
  4940. body.append(data, data_length);
  4941. return true;
  4942. });
  4943. ASSERT_TRUE(res);
  4944. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4946. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4947. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4948. "7890123456789012345678901234567890",
  4949. body);
  4950. EXPECT_EQ(StatusCode::OK_200, res->status);
  4951. }
  4952. TEST_F(ServerTest, NoZstd) {
  4953. Headers headers;
  4954. headers.emplace("Accept-Encoding", "zstd");
  4955. auto res = cli_.Get("/nocompress", headers);
  4956. ASSERT_TRUE(res);
  4957. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4958. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4959. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4960. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4961. "7890123456789012345678901234567890",
  4962. res->body);
  4963. EXPECT_EQ(StatusCode::OK_200, res->status);
  4964. }
  4965. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  4966. Headers headers;
  4967. headers.emplace("Accept-Encoding", "zstd");
  4968. std::string body;
  4969. auto res = cli_.Get("/nocompress", headers,
  4970. [&](const char *data, uint64_t data_length) {
  4971. EXPECT_EQ(100U, data_length);
  4972. body.append(data, data_length);
  4973. return true;
  4974. });
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4977. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4978. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4979. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4980. "7890123456789012345678901234567890",
  4981. body);
  4982. EXPECT_EQ(StatusCode::OK_200, res->status);
  4983. }
  4984. // TODO: How to enable zstd ??
  4985. TEST_F(ServerTest, MultipartFormDataZstd) {
  4986. MultipartFormDataItemsForClientInput items = {
  4987. {"key1", "test", "", ""},
  4988. {"key2", "--abcdefg123", "", ""},
  4989. };
  4990. Headers headers;
  4991. headers.emplace("Accept-Encoding", "zstd");
  4992. cli_.set_compress(true);
  4993. auto res = cli_.Post("/compress-multipart", headers, items);
  4994. ASSERT_TRUE(res);
  4995. EXPECT_EQ(StatusCode::OK_200, res->status);
  4996. }
  4997. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  4998. Headers headers;
  4999. headers.emplace("Accept-Encoding", "zstd");
  5000. cli_.set_compress(true);
  5001. auto res = cli_.Put(
  5002. "/put", headers, 3,
  5003. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5004. sink.os << "PUT";
  5005. return true;
  5006. },
  5007. "text/plain");
  5008. ASSERT_TRUE(res);
  5009. EXPECT_EQ(StatusCode::OK_200, res->status);
  5010. EXPECT_EQ("PUT", res->body);
  5011. }
  5012. TEST(ZstdDecompressor, ChunkedDecompression) {
  5013. std::string data;
  5014. for (size_t i = 0; i < 32 * 1024; ++i) {
  5015. data.push_back(static_cast<char>('a' + i % 26));
  5016. }
  5017. std::string compressed_data;
  5018. {
  5019. httplib::detail::zstd_compressor compressor;
  5020. bool result = compressor.compress(
  5021. data.data(), data.size(),
  5022. /*last=*/true,
  5023. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5024. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5025. compressed_data_size);
  5026. return true;
  5027. });
  5028. ASSERT_TRUE(result);
  5029. }
  5030. std::string decompressed_data;
  5031. {
  5032. httplib::detail::zstd_decompressor decompressor;
  5033. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5034. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5035. size_t chunk_size = 130;
  5036. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5037. chunk_begin += chunk_size) {
  5038. size_t current_chunk_size =
  5039. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5040. bool result = decompressor.decompress(
  5041. compressed_data.data() + chunk_begin, current_chunk_size,
  5042. [&](const char *decompressed_data_chunk,
  5043. size_t decompressed_data_chunk_size) {
  5044. decompressed_data.insert(decompressed_data.size(),
  5045. decompressed_data_chunk,
  5046. decompressed_data_chunk_size);
  5047. return true;
  5048. });
  5049. ASSERT_TRUE(result);
  5050. }
  5051. }
  5052. ASSERT_EQ(data, decompressed_data);
  5053. }
  5054. TEST(ZstdDecompressor, Decompress) {
  5055. std::string original_text = "Compressed with ZSTD";
  5056. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5057. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5058. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5059. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5060. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5061. std::string decompressed_data;
  5062. {
  5063. httplib::detail::zstd_decompressor decompressor;
  5064. bool result = decompressor.decompress(
  5065. compressed_data.data(), compressed_data.size(),
  5066. [&](const char *decompressed_data_chunk,
  5067. size_t decompressed_data_chunk_size) {
  5068. decompressed_data.insert(decompressed_data.size(),
  5069. decompressed_data_chunk,
  5070. decompressed_data_chunk_size);
  5071. return true;
  5072. });
  5073. ASSERT_TRUE(result);
  5074. }
  5075. ASSERT_EQ(original_text, decompressed_data);
  5076. }
  5077. #endif
  5078. // Sends a raw request to a server listening at HOST:PORT.
  5079. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5080. std::string *resp = nullptr) {
  5081. auto error = Error::Success;
  5082. auto client_sock = detail::create_client_socket(
  5083. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5084. /*connection_timeout_sec=*/5, 0,
  5085. /*read_timeout_sec=*/5, 0,
  5086. /*write_timeout_sec=*/5, 0, std::string(), error);
  5087. if (client_sock == INVALID_SOCKET) { return false; }
  5088. auto ret = detail::process_client_socket(
  5089. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5090. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5091. if (req.size() !=
  5092. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5093. return false;
  5094. }
  5095. char buf[512];
  5096. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5097. while (line_reader.getline()) {
  5098. if (resp) { *resp += line_reader.ptr(); }
  5099. }
  5100. return true;
  5101. });
  5102. detail::close_socket(client_sock);
  5103. return ret;
  5104. }
  5105. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5106. Server svr;
  5107. std::string header_value;
  5108. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5109. header_value = req.get_header_value("foo");
  5110. res.set_content("ok", "text/plain");
  5111. });
  5112. thread t = thread([&] { svr.listen(HOST, PORT); });
  5113. auto se = detail::scope_exit([&] {
  5114. svr.stop();
  5115. t.join();
  5116. ASSERT_FALSE(svr.is_running());
  5117. });
  5118. svr.wait_until_ready();
  5119. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5120. // like characters are not treated the same - use vertical tab and escape.
  5121. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5122. "foo: \t \v bar \x1B\t \r\n"
  5123. "Connection: close\r\n"
  5124. "\r\n";
  5125. std::string res;
  5126. ASSERT_TRUE(send_request(5, req, &res));
  5127. EXPECT_EQ(header_value, "");
  5128. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5129. }
  5130. // Sends a raw request and verifies that there isn't a crash or exception.
  5131. static void test_raw_request(const std::string &req,
  5132. std::string *out = nullptr) {
  5133. Server svr;
  5134. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5135. res.set_content("ok", "text/plain");
  5136. });
  5137. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5138. res.set_content("ok", "text/plain");
  5139. });
  5140. svr.Get("/header_field_value_check",
  5141. [&](const Request & /*req*/, Response &res) {
  5142. res.set_content("ok", "text/plain");
  5143. });
  5144. // Server read timeout must be longer than the client read timeout for the
  5145. // bug to reproduce, probably to force the server to process a request
  5146. // without a trailing blank line.
  5147. const time_t client_read_timeout_sec = 1;
  5148. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5149. bool listen_thread_ok = false;
  5150. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5151. auto se = detail::scope_exit([&] {
  5152. svr.stop();
  5153. t.join();
  5154. ASSERT_FALSE(svr.is_running());
  5155. EXPECT_TRUE(listen_thread_ok);
  5156. });
  5157. svr.wait_until_ready();
  5158. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5159. }
  5160. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5161. // A certain header line causes an exception if the header property is parsed
  5162. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5163. test_raw_request(
  5164. "GET /hi HTTP/1.1\r\n"
  5165. " : "
  5166. " "
  5167. " ");
  5168. }
  5169. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5170. // A certain header line causes an exception if the header property *name* is
  5171. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5172. // greedy matcher and requires backtracking when there are a lot of ":"
  5173. // characters.
  5174. // This occurs with libc++ but not libstdc++.
  5175. test_raw_request(
  5176. "GET /hi HTTP/1.1\r\n"
  5177. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5178. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5179. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5180. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5181. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5182. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5183. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5184. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5185. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5186. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5187. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5188. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5189. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5190. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5191. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5192. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5193. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5194. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5195. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5196. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5197. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5198. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5199. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5200. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5201. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5202. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5203. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5204. "&&&%%%");
  5205. }
  5206. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5207. // Make sure this doesn't crash the server.
  5208. // In a previous version of the header line regex, the "\r" rendered the line
  5209. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5210. // a new position where the leading white space ended and the field value
  5211. // began.
  5212. // The crash occurs with libc++ but not libstdc++.
  5213. test_raw_request("GET /hi HTTP/1.1\r\n"
  5214. "a:" +
  5215. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5216. "\r\n"
  5217. "\r\n");
  5218. }
  5219. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5220. std::string out;
  5221. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5222. "Content-Type: text/plain\r\n"
  5223. "Transfer-Encoding: chunked\r\n"
  5224. "\r\n"
  5225. "nothex\r\n",
  5226. &out);
  5227. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5228. }
  5229. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5230. std::string out;
  5231. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5232. "Content-Type: text/plain\r\n"
  5233. "Transfer-Encoding: chunked\r\n"
  5234. "\r\n"
  5235. "3\r\n"
  5236. "xyz\r\n"
  5237. "NaN\r\n",
  5238. &out);
  5239. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5240. }
  5241. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5242. std::string out;
  5243. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5244. "Content-Type: text/plain\r\n"
  5245. "Transfer-Encoding: chunked\r\n"
  5246. "\r\n"
  5247. // Length is too large for 64 bits.
  5248. "1ffffffffffffffff\r\n"
  5249. "xyz\r\n",
  5250. &out);
  5251. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5252. }
  5253. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5254. test_raw_request("GET /hi HTTP/1.1\r\n"
  5255. "Content-Type: text/plain\r\n\r");
  5256. }
  5257. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5258. std::string out;
  5259. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5260. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5261. }
  5262. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5263. std::string out;
  5264. std::string request(
  5265. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5266. test_raw_request(request, &out);
  5267. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5268. }
  5269. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5270. std::string out;
  5271. std::string request(
  5272. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5273. test_raw_request(request, &out);
  5274. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5275. }
  5276. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5277. std::string out;
  5278. std::string request(
  5279. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5280. test_raw_request(request, &out);
  5281. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5282. }
  5283. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5284. std::string out;
  5285. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5286. "Test: \r\n\r\n",
  5287. &out);
  5288. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5289. }
  5290. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5291. Server svr;
  5292. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5293. res.set_header("Cache-Control", "no-cache");
  5294. res.set_chunked_content_provider(
  5295. "text/event-stream", [](size_t offset, DataSink &sink) {
  5296. std::string s = "data:";
  5297. s += std::to_string(offset);
  5298. s += "\n\n";
  5299. auto ret = sink.write(s.data(), s.size());
  5300. EXPECT_TRUE(ret);
  5301. std::this_thread::sleep_for(std::chrono::seconds(1));
  5302. return true;
  5303. });
  5304. });
  5305. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5306. svr.wait_until_ready();
  5307. Client client(HOST, PORT);
  5308. const Headers headers = {{"Accept", "text/event-stream"}};
  5309. auto get_thread = std::thread([&client, &headers]() {
  5310. auto res = client.Get(
  5311. "/events", headers,
  5312. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5313. });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. get_thread.join();
  5317. listen_thread.join();
  5318. ASSERT_FALSE(svr.is_running());
  5319. });
  5320. // Give GET time to get a few messages.
  5321. std::this_thread::sleep_for(std::chrono::seconds(2));
  5322. }
  5323. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5324. httplib::Server svr;
  5325. svr.Post("/hi",
  5326. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5327. res.status = StatusCode::OK_200;
  5328. });
  5329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5330. svr.wait_until_ready();
  5331. Client cli(HOST, PORT);
  5332. auto res = cli.Post("/hi", "data", "text/plain");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. svr.stop();
  5336. thread.join();
  5337. ASSERT_FALSE(svr.is_running());
  5338. res = cli.Post("/hi", "data", "text/plain");
  5339. ASSERT_FALSE(res);
  5340. }
  5341. TEST(ServerStopTest, ListenFailure) {
  5342. Server svr;
  5343. auto t = thread([&]() {
  5344. auto ret = svr.listen("????", PORT);
  5345. EXPECT_FALSE(ret);
  5346. });
  5347. svr.wait_until_ready();
  5348. svr.stop();
  5349. t.join();
  5350. }
  5351. TEST(ServerStopTest, Decommision) {
  5352. Server svr;
  5353. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5354. for (int i = 0; i < 4; i++) {
  5355. auto is_even = !(i % 2);
  5356. std::thread t{[&] {
  5357. try {
  5358. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5359. if (is_even) {
  5360. throw std::runtime_error("Some thing that happens to go wrong.");
  5361. }
  5362. svr.listen(HOST, PORT);
  5363. } catch (...) { svr.decommission(); }
  5364. }};
  5365. svr.wait_until_ready();
  5366. // Server is up
  5367. {
  5368. Client cli(HOST, PORT);
  5369. auto res = cli.Get("/hi");
  5370. if (is_even) {
  5371. EXPECT_FALSE(res);
  5372. } else {
  5373. EXPECT_TRUE(res);
  5374. EXPECT_EQ("hi...", res->body);
  5375. }
  5376. }
  5377. svr.stop();
  5378. t.join();
  5379. // Server is down...
  5380. {
  5381. Client cli(HOST, PORT);
  5382. auto res = cli.Get("/hi");
  5383. EXPECT_FALSE(res);
  5384. }
  5385. }
  5386. }
  5387. // Helper function for string body upload progress tests
  5388. template <typename SetupHandler, typename ClientCall>
  5389. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5390. ClientCall &&client_call,
  5391. const string &body) {
  5392. Server svr;
  5393. setup_handler(svr);
  5394. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5395. auto se = detail::scope_exit([&] {
  5396. svr.stop();
  5397. t.join();
  5398. });
  5399. svr.wait_until_ready();
  5400. Client cli(HOST, PORT);
  5401. vector<uint64_t> progress_values;
  5402. bool progress_called = false;
  5403. auto res =
  5404. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5405. progress_values.push_back(current);
  5406. progress_called = true;
  5407. return true;
  5408. });
  5409. ASSERT_TRUE(res);
  5410. EXPECT_EQ(200, res->status);
  5411. EXPECT_TRUE(progress_called);
  5412. }
  5413. TEST(UploadProgressTest, PostStringBodyBasic) {
  5414. TestStringBodyUploadProgress(
  5415. [](Server &svr) {
  5416. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5417. res.set_content("received", "text/plain");
  5418. });
  5419. },
  5420. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5421. return cli.Post("/test", body, "text/plain", progress_callback);
  5422. },
  5423. "test data for upload progress");
  5424. }
  5425. TEST(UploadProgressTest, PutStringBodyBasic) {
  5426. TestStringBodyUploadProgress(
  5427. [](Server &svr) {
  5428. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5429. res.set_content("put received", "text/plain");
  5430. });
  5431. },
  5432. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5433. return cli.Put("/test", body, "text/plain", progress_callback);
  5434. },
  5435. "put test data for upload progress");
  5436. }
  5437. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5438. TestStringBodyUploadProgress(
  5439. [](Server &svr) {
  5440. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5441. res.set_content("patch received", "text/plain");
  5442. });
  5443. },
  5444. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5445. return cli.Patch("/test", body, "text/plain", progress_callback);
  5446. },
  5447. "patch test data for upload progress");
  5448. }
  5449. // Helper function for content provider upload progress tests
  5450. template <typename SetupHandler, typename ClientCall>
  5451. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5452. ClientCall &&client_call) {
  5453. Server svr;
  5454. setup_handler(svr);
  5455. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5456. auto se = detail::scope_exit([&] {
  5457. svr.stop();
  5458. t.join();
  5459. });
  5460. svr.wait_until_ready();
  5461. Client cli(HOST, PORT);
  5462. vector<uint64_t> progress_values;
  5463. auto res =
  5464. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5465. progress_values.push_back(current);
  5466. return true;
  5467. });
  5468. ASSERT_TRUE(res);
  5469. EXPECT_EQ(200, res->status);
  5470. EXPECT_FALSE(progress_values.empty());
  5471. }
  5472. TEST(UploadProgressTest, PostContentProviderProgress) {
  5473. TestContentProviderUploadProgress(
  5474. [](Server &svr) {
  5475. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5476. res.set_content("provider received", "text/plain");
  5477. });
  5478. },
  5479. [](Client &cli, UploadProgress progress_callback) {
  5480. return cli.Post(
  5481. "/test", 10,
  5482. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5483. sink.os << "test data";
  5484. return true;
  5485. },
  5486. "text/plain", progress_callback);
  5487. });
  5488. }
  5489. // Helper function for multipart upload progress tests
  5490. template <typename SetupHandler, typename ClientCall>
  5491. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5492. ClientCall &&client_call,
  5493. const string &endpoint) {
  5494. Server svr;
  5495. setup_handler(svr);
  5496. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5497. auto se = detail::scope_exit([&] {
  5498. svr.stop();
  5499. t.join();
  5500. });
  5501. svr.wait_until_ready();
  5502. Client cli(HOST, PORT);
  5503. vector<uint64_t> progress_values;
  5504. MultipartFormDataItemsForClientInput items = {
  5505. {"field1", "value1", "", ""},
  5506. {"field2", "longer value for progress tracking test", "", ""},
  5507. {"file1", "file content data for upload progress", "test.txt",
  5508. "text/plain"}};
  5509. auto res = client_call(cli, endpoint, items,
  5510. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5511. progress_values.push_back(current);
  5512. return true;
  5513. });
  5514. ASSERT_TRUE(res);
  5515. EXPECT_EQ(200, res->status);
  5516. EXPECT_FALSE(progress_values.empty());
  5517. }
  5518. TEST(UploadProgressTest, PostMultipartProgress) {
  5519. TestMultipartUploadProgress(
  5520. [](Server &svr) {
  5521. svr.Post("/multipart", [](const Request &req, Response &res) {
  5522. EXPECT_FALSE(req.files.empty());
  5523. res.set_content("multipart received", "text/plain");
  5524. });
  5525. },
  5526. [](Client &cli, const string &endpoint,
  5527. const MultipartFormDataItemsForClientInput &items,
  5528. UploadProgress progress_callback) {
  5529. return cli.Post(endpoint, items, progress_callback);
  5530. },
  5531. "/multipart");
  5532. }
  5533. // Helper function for basic download progress tests
  5534. template <typename SetupHandler, typename ClientCall>
  5535. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5536. ClientCall &&client_call, const string &endpoint,
  5537. size_t expected_content_size) {
  5538. Server svr;
  5539. setup_handler(svr);
  5540. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5541. auto se = detail::scope_exit([&] {
  5542. svr.stop();
  5543. t.join();
  5544. });
  5545. svr.wait_until_ready();
  5546. Client cli(HOST, PORT);
  5547. vector<uint64_t> progress_values;
  5548. auto res = client_call(cli, endpoint,
  5549. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5550. progress_values.push_back(current);
  5551. return true;
  5552. });
  5553. ASSERT_TRUE(res);
  5554. EXPECT_EQ(200, res->status);
  5555. EXPECT_FALSE(progress_values.empty());
  5556. EXPECT_EQ(expected_content_size, res->body.size());
  5557. }
  5558. TEST(DownloadProgressTest, GetBasic) {
  5559. TestBasicDownloadProgress(
  5560. [](Server &svr) {
  5561. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5562. string content(1000, 'D');
  5563. res.set_content(content, "text/plain");
  5564. });
  5565. },
  5566. [](Client &cli, const string &endpoint,
  5567. DownloadProgress progress_callback) {
  5568. return cli.Get(endpoint, progress_callback);
  5569. },
  5570. "/download", 1000u);
  5571. }
  5572. // Helper function for content receiver download progress tests
  5573. template <typename SetupHandler, typename ClientCall>
  5574. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5575. ClientCall &&client_call,
  5576. const string &endpoint,
  5577. size_t expected_content_size) {
  5578. Server svr;
  5579. setup_handler(svr);
  5580. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5581. auto se = detail::scope_exit([&] {
  5582. svr.stop();
  5583. t.join();
  5584. });
  5585. svr.wait_until_ready();
  5586. Client cli(HOST, PORT);
  5587. vector<uint64_t> progress_values;
  5588. string received_body;
  5589. auto res = client_call(
  5590. cli, endpoint,
  5591. [&](const char *data, size_t data_length) -> bool {
  5592. received_body.append(data, data_length);
  5593. return true;
  5594. },
  5595. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5596. progress_values.push_back(current);
  5597. return true;
  5598. });
  5599. ASSERT_TRUE(res);
  5600. EXPECT_EQ(200, res->status);
  5601. EXPECT_FALSE(progress_values.empty());
  5602. EXPECT_EQ(expected_content_size, received_body.size());
  5603. EXPECT_TRUE(res->body.empty());
  5604. }
  5605. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5606. TestContentReceiverDownloadProgress(
  5607. [](Server &svr) {
  5608. svr.Get("/download-receiver",
  5609. [](const Request & /*req*/, Response &res) {
  5610. string content(2000, 'R');
  5611. res.set_content(content, "text/plain");
  5612. });
  5613. },
  5614. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5615. DownloadProgress progress_callback) {
  5616. return cli.Get(endpoint, content_receiver, progress_callback);
  5617. },
  5618. "/download-receiver", 2000u);
  5619. }
  5620. TEST(StreamingTest, NoContentLengthStreaming) {
  5621. Server svr;
  5622. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5623. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5624. if (offset < 6) {
  5625. sink.os << (offset < 3 ? "a" : "b");
  5626. } else {
  5627. sink.done();
  5628. }
  5629. return true;
  5630. });
  5631. });
  5632. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5633. auto listen_se = detail::scope_exit([&] {
  5634. svr.stop();
  5635. listen_thread.join();
  5636. ASSERT_FALSE(svr.is_running());
  5637. });
  5638. svr.wait_until_ready();
  5639. Client client(HOST, PORT);
  5640. auto get_thread = std::thread([&client]() {
  5641. std::string s;
  5642. auto res =
  5643. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5644. s += std::string(data, len);
  5645. return true;
  5646. });
  5647. ASSERT_TRUE(res);
  5648. EXPECT_EQ(StatusCode::OK_200, res->status);
  5649. EXPECT_EQ("aaabbb", s);
  5650. });
  5651. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5652. // Give GET time to get a few messages.
  5653. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5654. }
  5655. TEST(MountTest, Unmount) {
  5656. Server svr;
  5657. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5658. auto se = detail::scope_exit([&] {
  5659. svr.stop();
  5660. listen_thread.join();
  5661. ASSERT_FALSE(svr.is_running());
  5662. });
  5663. svr.wait_until_ready();
  5664. Client cli("localhost", PORT);
  5665. svr.set_mount_point("/mount2", "./www2");
  5666. auto res = cli.Get("/");
  5667. ASSERT_TRUE(res);
  5668. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5669. res = cli.Get("/mount2/dir/test.html");
  5670. ASSERT_TRUE(res);
  5671. EXPECT_EQ(StatusCode::OK_200, res->status);
  5672. svr.set_mount_point("/", "./www");
  5673. res = cli.Get("/dir/");
  5674. ASSERT_TRUE(res);
  5675. EXPECT_EQ(StatusCode::OK_200, res->status);
  5676. svr.remove_mount_point("/");
  5677. res = cli.Get("/dir/");
  5678. ASSERT_TRUE(res);
  5679. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5680. svr.remove_mount_point("/mount2");
  5681. res = cli.Get("/mount2/dir/test.html");
  5682. ASSERT_TRUE(res);
  5683. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5684. }
  5685. TEST(MountTest, Redicect) {
  5686. Server svr;
  5687. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5688. auto se = detail::scope_exit([&] {
  5689. svr.stop();
  5690. listen_thread.join();
  5691. ASSERT_FALSE(svr.is_running());
  5692. });
  5693. svr.set_mount_point("/", "./www");
  5694. svr.wait_until_ready();
  5695. Client cli("localhost", PORT);
  5696. auto res = cli.Get("/dir/");
  5697. ASSERT_TRUE(res);
  5698. EXPECT_EQ(StatusCode::OK_200, res->status);
  5699. res = cli.Get("/dir");
  5700. ASSERT_TRUE(res);
  5701. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5702. res = cli.Get("/file");
  5703. ASSERT_TRUE(res);
  5704. EXPECT_EQ(StatusCode::OK_200, res->status);
  5705. res = cli.Get("/file/");
  5706. ASSERT_TRUE(res);
  5707. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5708. cli.set_follow_location(true);
  5709. res = cli.Get("/dir");
  5710. ASSERT_TRUE(res);
  5711. EXPECT_EQ(StatusCode::OK_200, res->status);
  5712. }
  5713. TEST(MountTest, MultibytesPathName) {
  5714. Server svr;
  5715. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5716. auto se = detail::scope_exit([&] {
  5717. svr.stop();
  5718. listen_thread.join();
  5719. ASSERT_FALSE(svr.is_running());
  5720. });
  5721. svr.set_mount_point("/", "./www");
  5722. svr.wait_until_ready();
  5723. Client cli("localhost", PORT);
  5724. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  5725. ASSERT_TRUE(res);
  5726. EXPECT_EQ(StatusCode::OK_200, res->status);
  5727. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  5728. }
  5729. TEST(KeepAliveTest, ReadTimeout) {
  5730. Server svr;
  5731. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5732. std::this_thread::sleep_for(std::chrono::seconds(2));
  5733. res.set_content("a", "text/plain");
  5734. });
  5735. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  5736. res.set_content("b", "text/plain");
  5737. });
  5738. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5739. auto se = detail::scope_exit([&] {
  5740. svr.stop();
  5741. listen_thread.join();
  5742. ASSERT_FALSE(svr.is_running());
  5743. });
  5744. svr.wait_until_ready();
  5745. Client cli("localhost", PORT);
  5746. cli.set_keep_alive(true);
  5747. cli.set_read_timeout(std::chrono::seconds(1));
  5748. auto resa = cli.Get("/a");
  5749. ASSERT_FALSE(resa);
  5750. EXPECT_EQ(Error::Read, resa.error());
  5751. auto resb = cli.Get("/b");
  5752. ASSERT_TRUE(resb);
  5753. EXPECT_EQ(StatusCode::OK_200, resb->status);
  5754. EXPECT_EQ("b", resb->body);
  5755. }
  5756. TEST(KeepAliveTest, MaxCount) {
  5757. size_t keep_alive_max_count = 3;
  5758. Server svr;
  5759. svr.set_keep_alive_max_count(keep_alive_max_count);
  5760. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5761. res.set_content("Hello World!", "text/plain");
  5762. });
  5763. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5764. auto se = detail::scope_exit([&] {
  5765. svr.stop();
  5766. listen_thread.join();
  5767. ASSERT_FALSE(svr.is_running());
  5768. });
  5769. svr.wait_until_ready();
  5770. Client cli(HOST, PORT);
  5771. cli.set_keep_alive(true);
  5772. for (size_t i = 0; i < 5; i++) {
  5773. auto result = cli.Get("/hi");
  5774. ASSERT_TRUE(result);
  5775. EXPECT_EQ(StatusCode::OK_200, result->status);
  5776. if (i == keep_alive_max_count - 1) {
  5777. EXPECT_EQ("close", result->get_header_value("Connection"));
  5778. } else {
  5779. EXPECT_FALSE(result->has_header("Connection"));
  5780. }
  5781. }
  5782. }
  5783. TEST(KeepAliveTest, Issue1041) {
  5784. Server svr;
  5785. svr.set_keep_alive_timeout(3);
  5786. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5787. res.set_content("Hello World!", "text/plain");
  5788. });
  5789. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5790. auto se = detail::scope_exit([&] {
  5791. svr.stop();
  5792. listen_thread.join();
  5793. ASSERT_FALSE(svr.is_running());
  5794. });
  5795. svr.wait_until_ready();
  5796. Client cli(HOST, PORT);
  5797. cli.set_keep_alive(true);
  5798. auto result = cli.Get("/hi");
  5799. ASSERT_TRUE(result);
  5800. EXPECT_EQ(StatusCode::OK_200, result->status);
  5801. std::this_thread::sleep_for(std::chrono::seconds(5));
  5802. result = cli.Get("/hi");
  5803. ASSERT_TRUE(result);
  5804. EXPECT_EQ(StatusCode::OK_200, result->status);
  5805. }
  5806. TEST(KeepAliveTest, Issue1959) {
  5807. Server svr;
  5808. svr.set_keep_alive_timeout(5);
  5809. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  5810. res.set_content("a", "text/plain");
  5811. });
  5812. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5813. auto se = detail::scope_exit([&] {
  5814. if (!svr.is_running()) return;
  5815. svr.stop();
  5816. listen_thread.join();
  5817. ASSERT_FALSE(svr.is_running());
  5818. });
  5819. svr.wait_until_ready();
  5820. Client cli("localhost", PORT);
  5821. cli.set_keep_alive(true);
  5822. using namespace std::chrono;
  5823. auto start = steady_clock::now();
  5824. cli.Get("/a");
  5825. svr.stop();
  5826. listen_thread.join();
  5827. auto end = steady_clock::now();
  5828. auto elapsed = duration_cast<milliseconds>(end - start).count();
  5829. EXPECT_LT(elapsed, 5000);
  5830. }
  5831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5832. TEST(KeepAliveTest, SSLClientReconnection) {
  5833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5834. ASSERT_TRUE(svr.is_valid());
  5835. svr.set_keep_alive_timeout(1);
  5836. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  5837. res.set_content("Hello World!", "text/plain");
  5838. });
  5839. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5840. auto se = detail::scope_exit([&] {
  5841. svr.stop();
  5842. listen_thread.join();
  5843. ASSERT_FALSE(svr.is_running());
  5844. });
  5845. svr.wait_until_ready();
  5846. SSLClient cli(HOST, PORT);
  5847. cli.enable_server_certificate_verification(false);
  5848. cli.set_keep_alive(true);
  5849. auto result = cli.Get("/hi");
  5850. ASSERT_TRUE(result);
  5851. EXPECT_EQ(StatusCode::OK_200, result->status);
  5852. result = cli.Get("/hi");
  5853. ASSERT_TRUE(result);
  5854. EXPECT_EQ(StatusCode::OK_200, result->status);
  5855. std::this_thread::sleep_for(std::chrono::seconds(2));
  5856. // Recoonect
  5857. result = cli.Get("/hi");
  5858. ASSERT_TRUE(result);
  5859. EXPECT_EQ(StatusCode::OK_200, result->status);
  5860. result = cli.Get("/hi");
  5861. ASSERT_TRUE(result);
  5862. EXPECT_EQ(StatusCode::OK_200, result->status);
  5863. }
  5864. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  5865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5866. ASSERT_TRUE(svr.is_valid());
  5867. svr.set_keep_alive_timeout(1);
  5868. std::string content = "reconnect";
  5869. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  5870. res.set_content("Hello World!", "text/plain");
  5871. });
  5872. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  5873. auto se = detail::scope_exit([&] {
  5874. svr.stop();
  5875. listen_thread.join();
  5876. ASSERT_FALSE(svr.is_running());
  5877. });
  5878. svr.wait_until_ready();
  5879. SSLClient cli(HOST, PORT);
  5880. cli.enable_server_certificate_verification(false);
  5881. cli.set_keep_alive(true);
  5882. auto result = cli.Post(
  5883. "/hi", content.size(),
  5884. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5885. sink.write(content.c_str(), content.size());
  5886. return true;
  5887. },
  5888. "text/plain");
  5889. ASSERT_TRUE(result);
  5890. EXPECT_EQ(200, result->status);
  5891. std::this_thread::sleep_for(std::chrono::seconds(2));
  5892. // Recoonect
  5893. result = cli.Post(
  5894. "/hi", content.size(),
  5895. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5896. sink.write(content.c_str(), content.size());
  5897. return true;
  5898. },
  5899. "text/plain");
  5900. ASSERT_TRUE(result);
  5901. EXPECT_EQ(200, result->status);
  5902. result = cli.Post(
  5903. "/hi", content.size(),
  5904. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5905. sink.write(content.c_str(), content.size());
  5906. return true;
  5907. },
  5908. "text/plain");
  5909. ASSERT_TRUE(result);
  5910. EXPECT_EQ(200, result->status);
  5911. }
  5912. #endif
  5913. TEST(ClientProblemDetectionTest, ContentProvider) {
  5914. Server svr;
  5915. size_t content_length = 1024 * 1024;
  5916. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5917. res.set_content_provider(
  5918. content_length, "text/plain",
  5919. [&](size_t offset, size_t length, DataSink &sink) {
  5920. auto out_len = std::min(length, static_cast<size_t>(1024));
  5921. std::string out(out_len, '@');
  5922. sink.write(out.data(), out_len);
  5923. return offset < 4096;
  5924. },
  5925. [](bool success) { ASSERT_FALSE(success); });
  5926. });
  5927. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  5928. res.set_content_provider(
  5929. 0, "text/plain",
  5930. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  5931. EXPECT_TRUE(false);
  5932. return true;
  5933. },
  5934. [](bool success) { ASSERT_FALSE(success); });
  5935. });
  5936. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5937. auto se = detail::scope_exit([&] {
  5938. svr.stop();
  5939. listen_thread.join();
  5940. ASSERT_FALSE(svr.is_running());
  5941. });
  5942. svr.wait_until_ready();
  5943. Client cli("localhost", PORT);
  5944. {
  5945. auto res = cli.Get("/hi", [&](const char * /*data*/,
  5946. size_t /*data_length*/) { return false; });
  5947. ASSERT_FALSE(res);
  5948. }
  5949. {
  5950. auto res = cli.Get("/empty", [&](const char * /*data*/,
  5951. size_t /*data_length*/) { return false; });
  5952. ASSERT_TRUE(res);
  5953. }
  5954. }
  5955. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  5956. Server svr;
  5957. svr.set_error_handler([](Request const &, Response &res) -> void {
  5958. res.set_chunked_content_provider(
  5959. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5960. sink.os << "hello";
  5961. sink.os << "world";
  5962. sink.done();
  5963. return true;
  5964. });
  5965. });
  5966. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5967. auto se = detail::scope_exit([&] {
  5968. svr.stop();
  5969. listen_thread.join();
  5970. ASSERT_FALSE(svr.is_running());
  5971. });
  5972. svr.wait_until_ready();
  5973. Client cli("localhost", PORT);
  5974. auto res = cli.Get("/");
  5975. ASSERT_TRUE(res);
  5976. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5977. EXPECT_EQ("helloworld", res->body);
  5978. }
  5979. TEST(LongPollingTest, ClientCloseDetection) {
  5980. Server svr;
  5981. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  5982. res.set_chunked_content_provider(
  5983. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  5984. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  5985. sink.os << "hello";
  5986. auto count = 10;
  5987. while (count > 0 && sink.is_writable()) {
  5988. this_thread::sleep_for(chrono::milliseconds(10));
  5989. count--;
  5990. }
  5991. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  5992. return true;
  5993. });
  5994. });
  5995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5996. auto se = detail::scope_exit([&] {
  5997. svr.stop();
  5998. listen_thread.join();
  5999. ASSERT_FALSE(svr.is_running());
  6000. });
  6001. svr.wait_until_ready();
  6002. Client cli("localhost", PORT);
  6003. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6004. EXPECT_EQ("hello", string(data, data_length));
  6005. return false; // close the socket immediately.
  6006. });
  6007. ASSERT_FALSE(res);
  6008. }
  6009. TEST(GetWithParametersTest, GetWithParameters) {
  6010. Server svr;
  6011. svr.Get("/", [&](const Request &req, Response &) {
  6012. EXPECT_EQ("world", req.get_param_value("hello"));
  6013. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6014. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6015. });
  6016. svr.Get("/params", [&](const Request &req, Response &) {
  6017. EXPECT_EQ("world", req.get_param_value("hello"));
  6018. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6019. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6020. });
  6021. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6022. EXPECT_EQ("resource-id", req.matches[1]);
  6023. EXPECT_EQ("foo", req.get_param_value("param1"));
  6024. EXPECT_EQ("bar", req.get_param_value("param2"));
  6025. });
  6026. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6027. EXPECT_EQ("user-id", req.path_params.at("id"));
  6028. EXPECT_EQ("foo", req.get_param_value("param1"));
  6029. EXPECT_EQ("bar", req.get_param_value("param2"));
  6030. });
  6031. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6032. auto se = detail::scope_exit([&] {
  6033. svr.stop();
  6034. listen_thread.join();
  6035. ASSERT_FALSE(svr.is_running());
  6036. });
  6037. svr.wait_until_ready();
  6038. {
  6039. Client cli(HOST, PORT);
  6040. Params params;
  6041. params.emplace("hello", "world");
  6042. params.emplace("hello2", "world2");
  6043. params.emplace("hello3", "world3");
  6044. auto res = cli.Get("/", params, Headers{});
  6045. ASSERT_TRUE(res);
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. }
  6048. {
  6049. Client cli(HOST, PORT);
  6050. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6051. ASSERT_TRUE(res);
  6052. EXPECT_EQ(StatusCode::OK_200, res->status);
  6053. }
  6054. {
  6055. Client cli(HOST, PORT);
  6056. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6057. ASSERT_TRUE(res);
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. }
  6060. {
  6061. Client cli(HOST, PORT);
  6062. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6063. ASSERT_TRUE(res);
  6064. EXPECT_EQ(StatusCode::OK_200, res->status);
  6065. }
  6066. }
  6067. TEST(GetWithParametersTest, GetWithParameters2) {
  6068. Server svr;
  6069. svr.Get("/", [&](const Request &req, Response &res) {
  6070. auto text = req.get_param_value("hello");
  6071. res.set_content(text, "text/plain");
  6072. });
  6073. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6074. auto se = detail::scope_exit([&] {
  6075. svr.stop();
  6076. listen_thread.join();
  6077. ASSERT_FALSE(svr.is_running());
  6078. });
  6079. svr.wait_until_ready();
  6080. Client cli("localhost", PORT);
  6081. Params params;
  6082. params.emplace("hello", "world");
  6083. std::string body;
  6084. auto res = cli.Get("/", params, Headers{},
  6085. [&](const char *data, size_t data_length) {
  6086. body.append(data, data_length);
  6087. return true;
  6088. });
  6089. ASSERT_TRUE(res);
  6090. EXPECT_EQ(StatusCode::OK_200, res->status);
  6091. EXPECT_EQ("world", body);
  6092. }
  6093. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6094. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6095. auto host = "httpbin.org";
  6096. auto path = std::string{"/range/32"};
  6097. #else
  6098. auto host = "nghttp2.org";
  6099. auto path = std::string{"/httpbin/range/32"};
  6100. #endif
  6101. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6102. SSLClient cli(host);
  6103. #else
  6104. Client cli(host);
  6105. #endif
  6106. cli.set_default_headers({make_range_header({{1, 10}})});
  6107. cli.set_connection_timeout(5);
  6108. {
  6109. auto res = cli.Get(path);
  6110. ASSERT_TRUE(res);
  6111. EXPECT_EQ("bcdefghijk", res->body);
  6112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6113. }
  6114. {
  6115. auto res = cli.Get(path);
  6116. ASSERT_TRUE(res);
  6117. EXPECT_EQ("bcdefghijk", res->body);
  6118. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6119. }
  6120. }
  6121. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6122. Server svr;
  6123. svr.set_default_headers({{"Hello", "World"}});
  6124. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6125. res.set_content("ok", "text/plain");
  6126. });
  6127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6128. auto se = detail::scope_exit([&] {
  6129. svr.stop();
  6130. listen_thread.join();
  6131. ASSERT_FALSE(svr.is_running());
  6132. });
  6133. svr.wait_until_ready();
  6134. Client cli("localhost", PORT);
  6135. auto res = cli.Get("/");
  6136. ASSERT_TRUE(res);
  6137. EXPECT_EQ(StatusCode::OK_200, res->status);
  6138. EXPECT_EQ("ok", res->body);
  6139. EXPECT_EQ("World", res->get_header_value("Hello"));
  6140. }
  6141. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6142. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6144. ASSERT_TRUE(svr.is_valid());
  6145. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6146. std::this_thread::sleep_for(std::chrono::seconds(2));
  6147. res.set_content("a", "text/plain");
  6148. });
  6149. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6150. res.set_content("b", "text/plain");
  6151. });
  6152. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6153. auto se = detail::scope_exit([&] {
  6154. svr.stop();
  6155. listen_thread.join();
  6156. ASSERT_FALSE(svr.is_running());
  6157. });
  6158. svr.wait_until_ready();
  6159. SSLClient cli("localhost", PORT);
  6160. cli.enable_server_certificate_verification(false);
  6161. cli.set_keep_alive(true);
  6162. cli.set_read_timeout(std::chrono::seconds(1));
  6163. auto resa = cli.Get("/a");
  6164. ASSERT_TRUE(!resa);
  6165. EXPECT_EQ(Error::Read, resa.error());
  6166. auto resb = cli.Get("/b");
  6167. ASSERT_TRUE(resb);
  6168. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6169. EXPECT_EQ("b", resb->body);
  6170. }
  6171. #endif
  6172. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6173. protected:
  6174. ServerTestWithAI_PASSIVE()
  6175. : cli_(HOST, PORT)
  6176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6177. ,
  6178. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6179. #endif
  6180. {
  6181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6182. cli_.enable_server_certificate_verification(false);
  6183. #endif
  6184. }
  6185. virtual void SetUp() {
  6186. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6187. res.set_content("Hello World!", "text/plain");
  6188. });
  6189. t_ = thread(
  6190. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6191. svr_.wait_until_ready();
  6192. }
  6193. virtual void TearDown() {
  6194. svr_.stop();
  6195. t_.join();
  6196. }
  6197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6198. SSLClient cli_;
  6199. SSLServer svr_;
  6200. #else
  6201. Client cli_;
  6202. Server svr_;
  6203. #endif
  6204. thread t_;
  6205. };
  6206. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6207. auto res = cli_.Get("/hi");
  6208. ASSERT_TRUE(res);
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6211. EXPECT_EQ("Hello World!", res->body);
  6212. }
  6213. class ServerUpDownTest : public ::testing::Test {
  6214. protected:
  6215. ServerUpDownTest() : cli_(HOST, PORT) {}
  6216. virtual void SetUp() {
  6217. t_ = thread([&]() {
  6218. svr_.bind_to_any_port(HOST);
  6219. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6220. ASSERT_TRUE(svr_.listen_after_bind());
  6221. });
  6222. svr_.wait_until_ready();
  6223. }
  6224. virtual void TearDown() {
  6225. svr_.stop();
  6226. t_.join();
  6227. }
  6228. Client cli_;
  6229. Server svr_;
  6230. thread t_;
  6231. };
  6232. TEST_F(ServerUpDownTest, QuickStartStop) {
  6233. // Should not crash, especially when run with
  6234. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6235. }
  6236. class PayloadMaxLengthTest : public ::testing::Test {
  6237. protected:
  6238. PayloadMaxLengthTest()
  6239. : cli_(HOST, PORT)
  6240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6241. ,
  6242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6243. #endif
  6244. {
  6245. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6246. cli_.enable_server_certificate_verification(false);
  6247. #endif
  6248. }
  6249. virtual void SetUp() {
  6250. svr_.set_payload_max_length(8);
  6251. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6252. res.set_content("test", "text/plain");
  6253. });
  6254. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6255. svr_.wait_until_ready();
  6256. }
  6257. virtual void TearDown() {
  6258. svr_.stop();
  6259. t_.join();
  6260. }
  6261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6262. SSLClient cli_;
  6263. SSLServer svr_;
  6264. #else
  6265. Client cli_;
  6266. Server svr_;
  6267. #endif
  6268. thread t_;
  6269. };
  6270. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6271. auto res = cli_.Post("/test", "123456789", "text/plain");
  6272. ASSERT_TRUE(res);
  6273. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6274. res = cli_.Post("/test", "12345678", "text/plain");
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. }
  6278. TEST(HostAndPortPropertiesTest, NoSSL) {
  6279. httplib::Client cli("www.google.com", 1234);
  6280. ASSERT_EQ("www.google.com", cli.host());
  6281. ASSERT_EQ(1234, cli.port());
  6282. }
  6283. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6284. httplib::Client cli("www.google.com:1234");
  6285. ASSERT_EQ("www.google.com", cli.host());
  6286. ASSERT_EQ(1234, cli.port());
  6287. }
  6288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6289. TEST(HostAndPortPropertiesTest, SSL) {
  6290. httplib::SSLClient cli("www.google.com");
  6291. ASSERT_EQ("www.google.com", cli.host());
  6292. ASSERT_EQ(443, cli.port());
  6293. }
  6294. #endif
  6295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6296. TEST(SSLClientTest, UpdateCAStore) {
  6297. httplib::SSLClient httplib_client("www.google.com");
  6298. auto ca_store_1 = X509_STORE_new();
  6299. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6300. nullptr);
  6301. httplib_client.set_ca_cert_store(ca_store_1);
  6302. auto ca_store_2 = X509_STORE_new();
  6303. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6304. nullptr);
  6305. httplib_client.set_ca_cert_store(ca_store_2);
  6306. }
  6307. TEST(SSLClientTest, ServerNameIndication_Online) {
  6308. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6309. auto host = "httpbin.org";
  6310. auto path = std::string{"/get"};
  6311. #else
  6312. auto host = "nghttp2.org";
  6313. auto path = std::string{"/httpbin/get"};
  6314. #endif
  6315. SSLClient cli(host, 443);
  6316. auto res = cli.Get(path);
  6317. ASSERT_TRUE(res);
  6318. ASSERT_EQ(StatusCode::OK_200, res->status);
  6319. }
  6320. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6321. // Use a site that will cause SSL verification failure due to self-signed cert
  6322. SSLClient cli("self-signed.badssl.com", 443);
  6323. cli.enable_server_certificate_verification(true);
  6324. auto res = cli.Get("/");
  6325. ASSERT_TRUE(!res);
  6326. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6327. // For SSL server verification errors, ssl_error should be 0, only
  6328. // ssl_openssl_error should be set
  6329. EXPECT_EQ(0, res.ssl_error());
  6330. // Verify OpenSSL error is captured for SSLServerVerification
  6331. // This occurs when SSL_get_verify_result() returns a verification failure
  6332. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6333. res.ssl_openssl_error());
  6334. }
  6335. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6336. // Use a site where hostname doesn't match the certificate
  6337. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6338. SSLClient cli("wrong.host.badssl.com", 443);
  6339. cli.enable_server_certificate_verification(true);
  6340. cli.enable_server_hostname_verification(true);
  6341. auto res = cli.Get("/");
  6342. ASSERT_TRUE(!res);
  6343. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6344. // For SSL hostname verification errors, ssl_error should be 0, only
  6345. // ssl_openssl_error should be set
  6346. EXPECT_EQ(0, res.ssl_error());
  6347. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6348. // This occurs when verify_host() fails due to hostname mismatch
  6349. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6350. res.ssl_openssl_error());
  6351. }
  6352. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6353. Client cli("https://google.com");
  6354. auto res = cli.Get("/");
  6355. ASSERT_TRUE(res);
  6356. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6357. }
  6358. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6359. SSLClient cli("google.com");
  6360. cli.set_ca_cert_path(CA_CERT_FILE);
  6361. auto res = cli.Get("/");
  6362. ASSERT_TRUE(res);
  6363. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6364. }
  6365. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6366. SSLClient cli("google.com");
  6367. cli.enable_server_certificate_verification(true);
  6368. cli.set_ca_cert_path("hello");
  6369. auto res = cli.Get("/");
  6370. ASSERT_TRUE(!res);
  6371. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6372. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6373. // should be set
  6374. EXPECT_EQ(0, res.ssl_error());
  6375. // Verify OpenSSL error is captured for SSLLoadingCerts
  6376. // This error occurs when SSL_CTX_load_verify_locations() fails
  6377. // > openssl errstr 0x80000002
  6378. // error:80000002:system library::No such file or directory
  6379. // > openssl errstr 0xA000126
  6380. // error:0A000126:SSL routines::unexpected eof while reading
  6381. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6382. res.ssl_openssl_error() == 0xA000126);
  6383. }
  6384. TEST(SSLClientTest, ServerCertificateVerification4) {
  6385. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6386. ASSERT_TRUE(svr.is_valid());
  6387. svr.Get("/test", [&](const Request &, Response &res) {
  6388. res.set_content("test", "text/plain");
  6389. svr.stop();
  6390. ASSERT_TRUE(true);
  6391. });
  6392. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6393. auto se = detail::scope_exit([&] {
  6394. t.join();
  6395. ASSERT_FALSE(svr.is_running());
  6396. });
  6397. svr.wait_until_ready();
  6398. SSLClient cli("127.0.0.1", PORT);
  6399. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6400. cli.enable_server_certificate_verification(true);
  6401. cli.set_connection_timeout(30);
  6402. auto res = cli.Get("/test");
  6403. ASSERT_TRUE(res);
  6404. ASSERT_EQ(StatusCode::OK_200, res->status);
  6405. }
  6406. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6407. std::string cert;
  6408. read_file(CA_CERT_FILE, cert);
  6409. SSLClient cli("google.com");
  6410. cli.load_ca_cert_store(cert.data(), cert.size());
  6411. const auto res = cli.Get("/");
  6412. ASSERT_TRUE(res);
  6413. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6414. }
  6415. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6416. // clang-format off
  6417. static constexpr char cert[] =
  6418. "GlobalSign Root CA\n"
  6419. "==================\n"
  6420. "-----BEGIN CERTIFICATE-----\n"
  6421. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6422. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6423. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6424. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6425. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6426. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6427. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6428. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6429. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6430. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6431. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6432. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6433. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6434. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6435. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6436. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6437. "-----END CERTIFICATE-----\n";
  6438. // clang-format on
  6439. SSLClient cli("google.com");
  6440. cli.load_ca_cert_store(cert, sizeof(cert));
  6441. const auto res = cli.Get("/");
  6442. ASSERT_TRUE(res);
  6443. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6444. }
  6445. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6446. SSLClient cli("www.youtube.com");
  6447. cli.set_ca_cert_path(CA_CERT_FILE);
  6448. cli.enable_server_certificate_verification(true);
  6449. cli.set_follow_location(true);
  6450. auto res = cli.Get("/");
  6451. ASSERT_TRUE(res);
  6452. ASSERT_EQ(StatusCode::OK_200, res->status);
  6453. }
  6454. TEST(SSLClientTest, Issue2004_Online) {
  6455. Client client("https://google.com");
  6456. client.set_follow_location(true);
  6457. auto res = client.Get("/");
  6458. ASSERT_TRUE(res);
  6459. ASSERT_EQ(StatusCode::OK_200, res->status);
  6460. auto body = res->body;
  6461. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6462. }
  6463. #if 0
  6464. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6465. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6466. ASSERT_TRUE(cli != nullptr);
  6467. cli->set_address_family(AF_INET6);
  6468. cli->set_interface("en0");
  6469. auto res = cli->Get("/get");
  6470. ASSERT_TRUE(res);
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. }
  6473. #endif
  6474. void ClientCertPresent(
  6475. const std::string &client_cert_file,
  6476. const std::string &client_private_key_file,
  6477. const std::string &client_encrypted_private_key_pass = std::string()) {
  6478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6479. CLIENT_CA_CERT_DIR);
  6480. ASSERT_TRUE(svr.is_valid());
  6481. svr.Get("/test", [&](const Request &req, Response &res) {
  6482. res.set_content("test", "text/plain");
  6483. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6484. ASSERT_TRUE(peer_cert != nullptr);
  6485. auto subject_name = X509_get_subject_name(peer_cert);
  6486. ASSERT_TRUE(subject_name != nullptr);
  6487. std::string common_name;
  6488. {
  6489. char name[BUFSIZ];
  6490. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6491. name, sizeof(name));
  6492. common_name.assign(name, static_cast<size_t>(name_len));
  6493. }
  6494. EXPECT_EQ("Common Name", common_name);
  6495. X509_free(peer_cert);
  6496. });
  6497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6498. auto se = detail::scope_exit([&] {
  6499. svr.stop();
  6500. t.join();
  6501. ASSERT_FALSE(svr.is_running());
  6502. });
  6503. svr.wait_until_ready();
  6504. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  6505. client_encrypted_private_key_pass);
  6506. cli.enable_server_certificate_verification(false);
  6507. cli.set_connection_timeout(30);
  6508. auto res = cli.Get("/test");
  6509. ASSERT_TRUE(res);
  6510. ASSERT_EQ(StatusCode::OK_200, res->status);
  6511. }
  6512. TEST(SSLClientServerTest, ClientCertPresent) {
  6513. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6514. }
  6515. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  6516. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6517. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6518. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6519. }
  6520. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  6521. void MemoryClientCertPresent(
  6522. const std::string &client_cert_file,
  6523. const std::string &client_private_key_file,
  6524. const std::string &client_encrypted_private_key_pass = std::string()) {
  6525. auto f = fopen(SERVER_CERT_FILE, "r+");
  6526. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6527. fclose(f);
  6528. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  6529. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  6530. fclose(f);
  6531. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  6532. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6533. auto client_ca_cert_store = X509_STORE_new();
  6534. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  6535. X509_free(client_cert);
  6536. fclose(f);
  6537. f = fopen(client_cert_file.c_str(), "r+");
  6538. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  6539. fclose(f);
  6540. f = fopen(client_private_key_file.c_str(), "r+");
  6541. auto client_private_key = PEM_read_PrivateKey(
  6542. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  6543. fclose(f);
  6544. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  6545. ASSERT_TRUE(svr.is_valid());
  6546. svr.Get("/test", [&](const Request &req, Response &res) {
  6547. res.set_content("test", "text/plain");
  6548. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6549. ASSERT_TRUE(peer_cert != nullptr);
  6550. auto subject_name = X509_get_subject_name(peer_cert);
  6551. ASSERT_TRUE(subject_name != nullptr);
  6552. std::string common_name;
  6553. {
  6554. char name[BUFSIZ];
  6555. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6556. name, sizeof(name));
  6557. common_name.assign(name, static_cast<size_t>(name_len));
  6558. }
  6559. EXPECT_EQ("Common Name", common_name);
  6560. X509_free(peer_cert);
  6561. });
  6562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6563. auto se = detail::scope_exit([&] {
  6564. svr.stop();
  6565. t.join();
  6566. ASSERT_FALSE(svr.is_running());
  6567. });
  6568. svr.wait_until_ready();
  6569. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  6570. client_encrypted_private_key_pass);
  6571. cli.enable_server_certificate_verification(false);
  6572. cli.set_connection_timeout(30);
  6573. auto res = cli.Get("/test");
  6574. ASSERT_TRUE(res);
  6575. ASSERT_EQ(StatusCode::OK_200, res->status);
  6576. X509_free(server_cert);
  6577. EVP_PKEY_free(server_private_key);
  6578. X509_free(client_cert);
  6579. EVP_PKEY_free(client_private_key);
  6580. }
  6581. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  6582. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6583. }
  6584. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  6585. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  6586. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  6587. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  6588. }
  6589. #endif
  6590. TEST(SSLClientServerTest, ClientCertMissing) {
  6591. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6592. CLIENT_CA_CERT_DIR);
  6593. ASSERT_TRUE(svr.is_valid());
  6594. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  6595. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6596. auto se = detail::scope_exit([&] {
  6597. svr.stop();
  6598. t.join();
  6599. ASSERT_FALSE(svr.is_running());
  6600. });
  6601. svr.wait_until_ready();
  6602. SSLClient cli(HOST, PORT);
  6603. cli.set_connection_timeout(30);
  6604. auto res = cli.Get("/test");
  6605. ASSERT_TRUE(!res);
  6606. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6607. // For SSL server verification errors, ssl_error should be 0, only
  6608. // ssl_openssl_error should be set
  6609. EXPECT_EQ(0, res.ssl_error());
  6610. // Verify OpenSSL error is captured for SSLServerVerification
  6611. // Note: This test may have different error codes depending on the exact
  6612. // verification failure
  6613. EXPECT_NE(0UL, res.ssl_openssl_error());
  6614. }
  6615. TEST(SSLClientServerTest, TrustDirOptional) {
  6616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  6617. ASSERT_TRUE(svr.is_valid());
  6618. svr.Get("/test", [&](const Request &, Response &res) {
  6619. res.set_content("test", "text/plain");
  6620. });
  6621. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6622. auto se = detail::scope_exit([&] {
  6623. svr.stop();
  6624. t.join();
  6625. ASSERT_FALSE(svr.is_running());
  6626. });
  6627. svr.wait_until_ready();
  6628. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6629. cli.enable_server_certificate_verification(false);
  6630. cli.set_connection_timeout(30);
  6631. auto res = cli.Get("/test");
  6632. ASSERT_TRUE(res);
  6633. ASSERT_EQ(StatusCode::OK_200, res->status);
  6634. }
  6635. TEST(SSLClientServerTest, SSLConnectTimeout) {
  6636. class NoListenSSLServer : public SSLServer {
  6637. public:
  6638. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  6639. const char *client_ca_cert_file_path,
  6640. const char *client_ca_cert_dir_path = nullptr)
  6641. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  6642. client_ca_cert_dir_path),
  6643. stop_(false) {}
  6644. std::atomic_bool stop_;
  6645. private:
  6646. bool process_and_close_socket(socket_t /*sock*/) override {
  6647. // Don't create SSL context
  6648. while (!stop_.load()) {
  6649. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6650. }
  6651. return true;
  6652. }
  6653. };
  6654. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  6655. CLIENT_CA_CERT_FILE);
  6656. ASSERT_TRUE(svr.is_valid());
  6657. svr.Get("/test", [&](const Request &, Response &res) {
  6658. res.set_content("test", "text/plain");
  6659. });
  6660. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6661. auto se = detail::scope_exit([&] {
  6662. svr.stop_ = true;
  6663. svr.stop();
  6664. t.join();
  6665. ASSERT_FALSE(svr.is_running());
  6666. });
  6667. svr.wait_until_ready();
  6668. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6669. cli.enable_server_certificate_verification(false);
  6670. cli.set_connection_timeout(1);
  6671. auto res = cli.Get("/test");
  6672. ASSERT_TRUE(!res);
  6673. EXPECT_EQ(Error::SSLConnection, res.error());
  6674. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  6675. }
  6676. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  6677. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  6678. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  6679. SSL_CTX_set_options(&ssl_ctx,
  6680. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  6681. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  6682. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  6683. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  6684. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  6685. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  6686. "ECDHE-DSS-AES128-SHA256:"
  6687. "ECDHE-RSA-AES256-SHA256:"
  6688. "ECDHE-DSS-AES256-SHA256:";
  6689. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  6690. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  6691. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  6692. SSL_FILETYPE_PEM) != 1) {
  6693. return false;
  6694. }
  6695. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  6696. CLIENT_CA_CERT_DIR);
  6697. SSL_CTX_set_verify(
  6698. &ssl_ctx,
  6699. SSL_VERIFY_PEER |
  6700. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  6701. nullptr);
  6702. return true;
  6703. };
  6704. SSLServer svr(setup_ssl_ctx_callback);
  6705. ASSERT_TRUE(svr.is_valid());
  6706. svr.Get("/test", [&](const Request &req, Response &res) {
  6707. res.set_content("test", "text/plain");
  6708. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6709. ASSERT_TRUE(peer_cert != nullptr);
  6710. auto subject_name = X509_get_subject_name(peer_cert);
  6711. ASSERT_TRUE(subject_name != nullptr);
  6712. std::string common_name;
  6713. {
  6714. char name[BUFSIZ];
  6715. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6716. name, sizeof(name));
  6717. common_name.assign(name, static_cast<size_t>(name_len));
  6718. }
  6719. EXPECT_EQ("Common Name", common_name);
  6720. X509_free(peer_cert);
  6721. });
  6722. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  6723. auto se = detail::scope_exit([&] {
  6724. svr.stop();
  6725. t.join();
  6726. ASSERT_FALSE(svr.is_running());
  6727. });
  6728. svr.wait_until_ready();
  6729. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  6730. cli.enable_server_certificate_verification(false);
  6731. cli.set_connection_timeout(30);
  6732. auto res = cli.Get("/test");
  6733. ASSERT_TRUE(res);
  6734. ASSERT_EQ(StatusCode::OK_200, res->status);
  6735. }
  6736. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  6737. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  6738. // prepare large data
  6739. std::random_device seed_gen;
  6740. std::mt19937 random(seed_gen());
  6741. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  6742. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  6743. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  6744. // server
  6745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6746. ASSERT_TRUE(svr.is_valid());
  6747. svr.Post("/binary", [&](const Request &req, Response &res) {
  6748. EXPECT_EQ(large_size_byte, req.body.size());
  6749. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  6750. res.set_content(req.body, "application/octet-stream");
  6751. });
  6752. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6753. auto se = detail::scope_exit([&] {
  6754. svr.stop();
  6755. listen_thread.join();
  6756. ASSERT_FALSE(svr.is_running());
  6757. });
  6758. svr.wait_until_ready();
  6759. // client POST
  6760. SSLClient cli("localhost", PORT);
  6761. cli.enable_server_certificate_verification(false);
  6762. cli.set_read_timeout(std::chrono::seconds(100));
  6763. cli.set_write_timeout(std::chrono::seconds(100));
  6764. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  6765. large_size_byte, "application/octet-stream");
  6766. // compare
  6767. EXPECT_EQ(StatusCode::OK_200, res->status);
  6768. EXPECT_EQ(large_size_byte, res->body.size());
  6769. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  6770. }
  6771. #endif
  6772. #ifdef _WIN32
  6773. TEST(CleanupTest, WSACleanup) {
  6774. int ret = WSACleanup();
  6775. ASSERT_EQ(0, ret);
  6776. }
  6777. #endif
  6778. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  6779. TEST(NoSSLSupport, SimpleInterface) {
  6780. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  6781. }
  6782. #endif
  6783. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6784. TEST(InvalidScheme, SimpleInterface) {
  6785. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  6786. }
  6787. #endif
  6788. TEST(NoScheme, SimpleInterface) {
  6789. Client cli("yahoo.com:80");
  6790. ASSERT_TRUE(cli.is_valid());
  6791. }
  6792. TEST(SendAPI, SimpleInterface_Online) {
  6793. Client cli("http://yahoo.com");
  6794. Request req;
  6795. req.method = "GET";
  6796. req.path = "/";
  6797. auto res = cli.send(req);
  6798. ASSERT_TRUE(res);
  6799. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6800. }
  6801. TEST(SendAPI, WithParamsInRequest) {
  6802. Server svr;
  6803. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  6804. EXPECT_TRUE(req.has_param("test"));
  6805. EXPECT_EQ("test_value", req.get_param_value("test"));
  6806. });
  6807. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  6808. auto se = detail::scope_exit([&] {
  6809. svr.stop();
  6810. t.join();
  6811. ASSERT_FALSE(svr.is_running());
  6812. });
  6813. svr.wait_until_ready();
  6814. Client cli(HOST, PORT);
  6815. {
  6816. Request req;
  6817. req.method = "GET";
  6818. req.path = "/";
  6819. req.params.emplace("test", "test_value");
  6820. auto res = cli.send(req);
  6821. ASSERT_TRUE(res);
  6822. }
  6823. {
  6824. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  6825. ASSERT_TRUE(res);
  6826. }
  6827. }
  6828. TEST(ClientImplMethods, GetSocketTest) {
  6829. httplib::Server svr;
  6830. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6831. res.status = StatusCode::OK_200;
  6832. });
  6833. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  6834. auto se = detail::scope_exit([&] {
  6835. svr.stop();
  6836. thread.join();
  6837. ASSERT_FALSE(svr.is_running());
  6838. });
  6839. svr.wait_until_ready();
  6840. {
  6841. httplib::Client cli("http://127.0.0.1:3333");
  6842. cli.set_keep_alive(true);
  6843. // Use the behavior of cpp-httplib of opening the connection
  6844. // only when the first request happens. If that changes,
  6845. // this test would be obsolete.
  6846. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  6847. // This also implicitly tests the server. But other tests would fail much
  6848. // earlier than this one to be considered.
  6849. auto res = cli.Get("/");
  6850. ASSERT_TRUE(res);
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  6853. }
  6854. }
  6855. // Disabled due to out-of-memory problem on GitHub Actions
  6856. #ifdef _WIN64
  6857. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  6858. // allocate content size larger than 2GB in memory
  6859. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  6860. char *content = (char *)malloc(content_size);
  6861. ASSERT_TRUE(content);
  6862. Server svr;
  6863. svr.Get("/foo",
  6864. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  6865. res.set_content(content, content_size, "application/octet-stream");
  6866. });
  6867. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6868. auto se = detail::scope_exit([&] {
  6869. svr.stop();
  6870. listen_thread.join();
  6871. if (content) free(content);
  6872. ASSERT_FALSE(svr.is_running());
  6873. });
  6874. svr.wait_until_ready();
  6875. Client cli(HOST, PORT);
  6876. auto res = cli.Get("/foo");
  6877. ASSERT_TRUE(res);
  6878. EXPECT_EQ(StatusCode::OK_200, res->status);
  6879. EXPECT_EQ(content_size, res->body.length());
  6880. }
  6881. #endif
  6882. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6883. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  6884. Client cli("http://yahoo.com");
  6885. auto res = cli.Get("/");
  6886. ASSERT_TRUE(res);
  6887. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6888. cli.set_follow_location(true);
  6889. res = cli.Get("/");
  6890. ASSERT_TRUE(res);
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6893. }
  6894. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  6895. Client cli("https://yahoo.com");
  6896. auto res = cli.Get("/");
  6897. ASSERT_TRUE(res);
  6898. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6899. cli.set_follow_location(true);
  6900. res = cli.Get("/");
  6901. ASSERT_TRUE(res);
  6902. EXPECT_EQ(StatusCode::OK_200, res->status);
  6903. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6904. }
  6905. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  6906. Client cli("https://yahoo.com");
  6907. auto res = cli.Get("/");
  6908. ASSERT_TRUE(res);
  6909. ASSERT_FALSE(!res);
  6910. ASSERT_TRUE(res);
  6911. ASSERT_FALSE(res == nullptr);
  6912. ASSERT_TRUE(res != nullptr);
  6913. EXPECT_EQ(Error::Success, res.error());
  6914. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  6915. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  6916. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6917. cli.set_follow_location(true);
  6918. res = cli.Get("/");
  6919. ASSERT_TRUE(res);
  6920. EXPECT_EQ(Error::Success, res.error());
  6921. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  6922. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("https://www.yahoo.com/", res->location);
  6925. }
  6926. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6927. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  6928. Client cli("https://cdnjs.cloudflare.com");
  6929. auto res =
  6930. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  6931. ASSERT_TRUE(res);
  6932. EXPECT_EQ(StatusCode::OK_200, res->status);
  6933. EXPECT_EQ(287630U, res->body.size());
  6934. EXPECT_EQ("application/javascript; charset=utf-8",
  6935. res->get_header_value("Content-Type"));
  6936. }
  6937. #endif
  6938. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  6939. #undef REDIR_HOST // Silence compiler warning
  6940. #define REDIR_HOST "https://httpbingo.org"
  6941. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  6942. Client cli(REDIR_HOST);
  6943. cli.set_follow_location(true);
  6944. auto res =
  6945. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  6946. ASSERT_TRUE(res);
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  6950. Client cli(REDIR_HOST);
  6951. cli.set_follow_location(true);
  6952. Params params;
  6953. params.emplace("url", "http://example.com");
  6954. params.emplace("status_code", "302");
  6955. auto res = cli.Get(REDIR_PATH, params, Headers{});
  6956. ASSERT_TRUE(res);
  6957. EXPECT_EQ(StatusCode::OK_200, res->status);
  6958. }
  6959. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  6960. Client cli(REDIR_HOST);
  6961. cli.set_follow_location(true);
  6962. Params params;
  6963. params.emplace("url", "http://example.com");
  6964. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  6965. ASSERT_TRUE(res);
  6966. EXPECT_EQ(StatusCode::OK_200, res->status);
  6967. }
  6968. TEST(HttpToHttpsRedirectTest, CertFile) {
  6969. Server svr;
  6970. ASSERT_TRUE(svr.is_valid());
  6971. svr.Get("/index", [&](const Request &, Response &res) {
  6972. res.set_redirect("https://127.0.0.1:1235/index");
  6973. svr.stop();
  6974. });
  6975. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6976. ASSERT_TRUE(ssl_svr.is_valid());
  6977. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  6978. res.set_content("test", "text/plain");
  6979. ssl_svr.stop();
  6980. });
  6981. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6982. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  6983. auto se = detail::scope_exit([&] {
  6984. t2.join();
  6985. t.join();
  6986. ASSERT_FALSE(svr.is_running());
  6987. });
  6988. svr.wait_until_ready();
  6989. ssl_svr.wait_until_ready();
  6990. Client cli("127.0.0.1", PORT);
  6991. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6992. cli.enable_server_certificate_verification(true);
  6993. cli.set_follow_location(true);
  6994. cli.set_connection_timeout(30);
  6995. auto res = cli.Get("/index");
  6996. ASSERT_TRUE(res);
  6997. ASSERT_EQ(StatusCode::OK_200, res->status);
  6998. }
  6999. TEST(MultipartFormDataTest, LargeData) {
  7000. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7001. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7002. const ContentReader &content_reader) {
  7003. if (req.is_multipart_form_data()) {
  7004. MultipartFormDataItems files;
  7005. content_reader(
  7006. [&](const MultipartFormData &file) {
  7007. files.push_back(file);
  7008. return true;
  7009. },
  7010. [&](const char *data, size_t data_length) {
  7011. files.back().content.append(data, data_length);
  7012. return true;
  7013. });
  7014. EXPECT_TRUE(std::string(files[0].name) == "document");
  7015. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7016. EXPECT_TRUE(files[0].filename == "2MB_data");
  7017. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7018. EXPECT_TRUE(files[1].name == "hello");
  7019. EXPECT_TRUE(files[1].content == "world");
  7020. EXPECT_TRUE(files[1].filename == "");
  7021. EXPECT_TRUE(files[1].content_type == "");
  7022. } else {
  7023. std::string body;
  7024. content_reader([&](const char *data, size_t data_length) {
  7025. body.append(data, data_length);
  7026. return true;
  7027. });
  7028. }
  7029. });
  7030. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7031. auto se = detail::scope_exit([&] {
  7032. svr.stop();
  7033. t.join();
  7034. ASSERT_FALSE(svr.is_running());
  7035. });
  7036. svr.wait_until_ready();
  7037. {
  7038. std::string data(1024 * 1024 * 2, '.');
  7039. std::stringstream buffer;
  7040. buffer << data;
  7041. Client cli("https://localhost:8080");
  7042. cli.enable_server_certificate_verification(false);
  7043. MultipartFormDataItemsForClientInput items{
  7044. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7045. {"hello", "world", "", ""},
  7046. };
  7047. auto res = cli.Post("/post", items);
  7048. ASSERT_TRUE(res);
  7049. ASSERT_EQ(StatusCode::OK_200, res->status);
  7050. }
  7051. }
  7052. TEST(MultipartFormDataTest, DataProviderItems) {
  7053. std::random_device seed_gen;
  7054. std::mt19937 random(seed_gen());
  7055. std::string rand1;
  7056. rand1.resize(1000);
  7057. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7058. std::string rand2;
  7059. rand2.resize(3000);
  7060. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7061. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7062. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7063. const ContentReader &content_reader) {
  7064. ASSERT_FALSE(req.is_multipart_form_data());
  7065. std::string body;
  7066. content_reader([&](const char *data, size_t data_length) {
  7067. body.append(data, data_length);
  7068. return true;
  7069. });
  7070. EXPECT_EQ(body, "");
  7071. });
  7072. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7073. const ContentReader &content_reader) {
  7074. ASSERT_TRUE(req.is_multipart_form_data());
  7075. MultipartFormDataItems files;
  7076. content_reader(
  7077. [&](const MultipartFormData &file) {
  7078. files.push_back(file);
  7079. return true;
  7080. },
  7081. [&](const char *data, size_t data_length) {
  7082. files.back().content.append(data, data_length);
  7083. return true;
  7084. });
  7085. ASSERT_TRUE(files.size() == 2);
  7086. EXPECT_EQ(std::string(files[0].name), "name1");
  7087. EXPECT_EQ(files[0].content, "Testing123");
  7088. EXPECT_EQ(files[0].filename, "filename1");
  7089. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7090. EXPECT_EQ(files[1].name, "name2");
  7091. EXPECT_EQ(files[1].content, "Testing456");
  7092. EXPECT_EQ(files[1].filename, "");
  7093. EXPECT_EQ(files[1].content_type, "");
  7094. });
  7095. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7096. const ContentReader &content_reader) {
  7097. ASSERT_TRUE(req.is_multipart_form_data());
  7098. MultipartFormDataItems files;
  7099. content_reader(
  7100. [&](const MultipartFormData &file) {
  7101. files.push_back(file);
  7102. return true;
  7103. },
  7104. [&](const char *data, size_t data_length) {
  7105. files.back().content.append(data, data_length);
  7106. return true;
  7107. });
  7108. ASSERT_TRUE(files.size() == 2);
  7109. EXPECT_EQ(files[0].name, "name3");
  7110. EXPECT_EQ(files[0].content, rand1);
  7111. EXPECT_EQ(files[0].filename, "filename3");
  7112. EXPECT_EQ(files[0].content_type, "");
  7113. EXPECT_EQ(files[1].name, "name4");
  7114. EXPECT_EQ(files[1].content, rand2);
  7115. EXPECT_EQ(files[1].filename, "filename4");
  7116. EXPECT_EQ(files[1].content_type, "");
  7117. });
  7118. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7119. const ContentReader &content_reader) {
  7120. ASSERT_TRUE(req.is_multipart_form_data());
  7121. MultipartFormDataItems files;
  7122. content_reader(
  7123. [&](const MultipartFormData &file) {
  7124. files.push_back(file);
  7125. return true;
  7126. },
  7127. [&](const char *data, size_t data_length) {
  7128. files.back().content.append(data, data_length);
  7129. return true;
  7130. });
  7131. ASSERT_TRUE(files.size() == 4);
  7132. EXPECT_EQ(std::string(files[0].name), "name1");
  7133. EXPECT_EQ(files[0].content, "Testing123");
  7134. EXPECT_EQ(files[0].filename, "filename1");
  7135. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  7136. EXPECT_EQ(files[1].name, "name2");
  7137. EXPECT_EQ(files[1].content, "Testing456");
  7138. EXPECT_EQ(files[1].filename, "");
  7139. EXPECT_EQ(files[1].content_type, "");
  7140. EXPECT_EQ(files[2].name, "name3");
  7141. EXPECT_EQ(files[2].content, rand1);
  7142. EXPECT_EQ(files[2].filename, "filename3");
  7143. EXPECT_EQ(files[2].content_type, "");
  7144. EXPECT_EQ(files[3].name, "name4");
  7145. EXPECT_EQ(files[3].content, rand2);
  7146. EXPECT_EQ(files[3].filename, "filename4");
  7147. EXPECT_EQ(files[3].content_type, "");
  7148. });
  7149. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7150. auto se = detail::scope_exit([&] {
  7151. svr.stop();
  7152. t.join();
  7153. ASSERT_FALSE(svr.is_running());
  7154. });
  7155. svr.wait_until_ready();
  7156. {
  7157. Client cli("https://localhost:8080");
  7158. cli.enable_server_certificate_verification(false);
  7159. MultipartFormDataItemsForClientInput items{
  7160. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7161. {"name2", "Testing456", "", ""}, // not a file
  7162. };
  7163. {
  7164. auto res = cli.Post("/post-none", {}, {}, {});
  7165. ASSERT_TRUE(res);
  7166. ASSERT_EQ(StatusCode::OK_200, res->status);
  7167. }
  7168. MultipartFormDataProviderItems providers;
  7169. {
  7170. auto res =
  7171. cli.Post("/post-items", {}, items, providers); // empty providers
  7172. ASSERT_TRUE(res);
  7173. ASSERT_EQ(StatusCode::OK_200, res->status);
  7174. }
  7175. providers.push_back({"name3",
  7176. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7177. // test the offset is given correctly at each step
  7178. if (!offset)
  7179. sink.os.write(rand1.data(), 30);
  7180. else if (offset == 30)
  7181. sink.os.write(rand1.data() + 30, 300);
  7182. else if (offset == 330)
  7183. sink.os.write(rand1.data() + 330, 670);
  7184. else if (offset == rand1.size())
  7185. sink.done();
  7186. return true;
  7187. },
  7188. "filename3",
  7189. {}});
  7190. providers.push_back({"name4",
  7191. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7192. // test the offset is given correctly at each step
  7193. if (!offset)
  7194. sink.os.write(rand2.data(), 2000);
  7195. else if (offset == 2000)
  7196. sink.os.write(rand2.data() + 2000, 1);
  7197. else if (offset == 2001)
  7198. sink.os.write(rand2.data() + 2001, 999);
  7199. else if (offset == rand2.size())
  7200. sink.done();
  7201. return true;
  7202. },
  7203. "filename4",
  7204. {}});
  7205. {
  7206. auto res = cli.Post("/post-providers", {}, {}, providers);
  7207. ASSERT_TRUE(res);
  7208. ASSERT_EQ(StatusCode::OK_200, res->status);
  7209. }
  7210. {
  7211. auto res = cli.Post("/post-both", {}, items, providers);
  7212. ASSERT_TRUE(res);
  7213. ASSERT_EQ(StatusCode::OK_200, res->status);
  7214. }
  7215. }
  7216. }
  7217. TEST(MultipartFormDataTest, BadHeader) {
  7218. Server svr;
  7219. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7220. res.set_content("ok", "text/plain");
  7221. });
  7222. thread t = thread([&] { svr.listen(HOST, PORT); });
  7223. auto se = detail::scope_exit([&] {
  7224. svr.stop();
  7225. t.join();
  7226. ASSERT_FALSE(svr.is_running());
  7227. });
  7228. svr.wait_until_ready();
  7229. const std::string body =
  7230. "This is the preamble. It is to be ignored, though it\r\n"
  7231. "is a handy place for composition agents to include an\r\n"
  7232. "explanatory note to non-MIME conformant readers.\r\n"
  7233. "\r\n"
  7234. "\r\n"
  7235. "--simple boundary\r\n"
  7236. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7237. ": BAD...\r\n"
  7238. "\r\n"
  7239. "value1\r\n"
  7240. "--simple boundary\r\n"
  7241. "Content-Disposition: form-data; name=\"field2\"; "
  7242. "filename=\"example.txt\"\r\n"
  7243. "\r\n"
  7244. "value2\r\n"
  7245. "--simple boundary--\r\n"
  7246. "This is the epilogue. It is also to be ignored.\r\n";
  7247. std::string content_type =
  7248. R"(multipart/form-data; boundary="simple boundary")";
  7249. Client cli(HOST, PORT);
  7250. auto res = cli.Post("/post", body, content_type.c_str());
  7251. ASSERT_TRUE(res);
  7252. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7253. }
  7254. TEST(MultipartFormDataTest, WithPreamble) {
  7255. Server svr;
  7256. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7257. res.set_content("ok", "text/plain");
  7258. });
  7259. thread t = thread([&] { svr.listen(HOST, PORT); });
  7260. auto se = detail::scope_exit([&] {
  7261. svr.stop();
  7262. t.join();
  7263. ASSERT_FALSE(svr.is_running());
  7264. });
  7265. svr.wait_until_ready();
  7266. const std::string body =
  7267. "This is the preamble. It is to be ignored, though it\r\n"
  7268. "is a handy place for composition agents to include an\r\n"
  7269. "explanatory note to non-MIME conformant readers.\r\n"
  7270. "\r\n"
  7271. "\r\n"
  7272. "--simple boundary\r\n"
  7273. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7274. "\r\n"
  7275. "value1\r\n"
  7276. "--simple boundary\r\n"
  7277. "Content-Disposition: form-data; name=\"field2\"; "
  7278. "filename=\"example.txt\"\r\n"
  7279. "\r\n"
  7280. "value2\r\n"
  7281. "--simple boundary--\r\n"
  7282. "This is the epilogue. It is also to be ignored.\r\n";
  7283. std::string content_type =
  7284. R"(multipart/form-data; boundary="simple boundary")";
  7285. Client cli(HOST, PORT);
  7286. auto res = cli.Post("/post", body, content_type.c_str());
  7287. ASSERT_TRUE(res);
  7288. EXPECT_EQ(StatusCode::OK_200, res->status);
  7289. }
  7290. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7292. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7293. const ContentReader &content_reader) {
  7294. if (req.is_multipart_form_data()) {
  7295. MultipartFormDataItems files;
  7296. content_reader(
  7297. [&](const MultipartFormData &file) {
  7298. files.push_back(file);
  7299. return true;
  7300. },
  7301. [&](const char *data, size_t data_length) {
  7302. files.back().content.append(data, data_length);
  7303. return true;
  7304. });
  7305. EXPECT_TRUE(std::string(files[0].name) == "document");
  7306. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7307. EXPECT_TRUE(files[0].filename == "2MB_data");
  7308. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7309. EXPECT_TRUE(files[1].name == "hello");
  7310. EXPECT_TRUE(files[1].content == "world");
  7311. EXPECT_TRUE(files[1].filename == "");
  7312. EXPECT_TRUE(files[1].content_type == "");
  7313. } else {
  7314. std::string body;
  7315. content_reader([&](const char *data, size_t data_length) {
  7316. body.append(data, data_length);
  7317. return true;
  7318. });
  7319. }
  7320. });
  7321. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7322. auto se = detail::scope_exit([&] {
  7323. svr.stop();
  7324. t.join();
  7325. ASSERT_FALSE(svr.is_running());
  7326. });
  7327. svr.wait_until_ready();
  7328. {
  7329. std::string data(1024 * 1024 * 2, '.');
  7330. std::stringstream buffer;
  7331. buffer << data;
  7332. Client cli("https://localhost:8080");
  7333. cli.enable_server_certificate_verification(false);
  7334. MultipartFormDataItemsForClientInput items{
  7335. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7336. {"hello", "world", "", ""},
  7337. };
  7338. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7339. ASSERT_TRUE(res);
  7340. ASSERT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. }
  7343. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7344. std::string data(1024 * 1024 * 2, '&');
  7345. std::stringstream buffer;
  7346. buffer << data;
  7347. Client cli("https://localhost:8080");
  7348. MultipartFormDataItemsForClientInput items{
  7349. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7350. {"hello", "world", "", ""},
  7351. };
  7352. for (const char &c : " \t\r\n") {
  7353. auto res =
  7354. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7355. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7356. ASSERT_FALSE(res);
  7357. }
  7358. }
  7359. TEST(MultipartFormDataTest, PutFormData) {
  7360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7361. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7362. const ContentReader &content_reader) {
  7363. if (req.is_multipart_form_data()) {
  7364. MultipartFormDataItems files;
  7365. content_reader(
  7366. [&](const MultipartFormData &file) {
  7367. files.push_back(file);
  7368. return true;
  7369. },
  7370. [&](const char *data, size_t data_length) {
  7371. files.back().content.append(data, data_length);
  7372. return true;
  7373. });
  7374. EXPECT_TRUE(std::string(files[0].name) == "document");
  7375. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7376. EXPECT_TRUE(files[0].filename == "2MB_data");
  7377. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7378. EXPECT_TRUE(files[1].name == "hello");
  7379. EXPECT_TRUE(files[1].content == "world");
  7380. EXPECT_TRUE(files[1].filename == "");
  7381. EXPECT_TRUE(files[1].content_type == "");
  7382. } else {
  7383. std::string body;
  7384. content_reader([&](const char *data, size_t data_length) {
  7385. body.append(data, data_length);
  7386. return true;
  7387. });
  7388. }
  7389. });
  7390. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7391. auto se = detail::scope_exit([&] {
  7392. svr.stop();
  7393. t.join();
  7394. ASSERT_FALSE(svr.is_running());
  7395. });
  7396. svr.wait_until_ready();
  7397. {
  7398. std::string data(1024 * 1024 * 2, '&');
  7399. std::stringstream buffer;
  7400. buffer << data;
  7401. Client cli("https://localhost:8080");
  7402. cli.enable_server_certificate_verification(false);
  7403. MultipartFormDataItemsForClientInput items{
  7404. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7405. {"hello", "world", "", ""},
  7406. };
  7407. auto res = cli.Put("/put", items);
  7408. ASSERT_TRUE(res);
  7409. ASSERT_EQ(StatusCode::OK_200, res->status);
  7410. }
  7411. }
  7412. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7413. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7414. svr.Put("/put_customboundary",
  7415. [&](const Request &req, const Response & /*res*/,
  7416. const ContentReader &content_reader) {
  7417. if (req.is_multipart_form_data()) {
  7418. MultipartFormDataItems files;
  7419. content_reader(
  7420. [&](const MultipartFormData &file) {
  7421. files.push_back(file);
  7422. return true;
  7423. },
  7424. [&](const char *data, size_t data_length) {
  7425. files.back().content.append(data, data_length);
  7426. return true;
  7427. });
  7428. EXPECT_TRUE(std::string(files[0].name) == "document");
  7429. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  7430. EXPECT_TRUE(files[0].filename == "2MB_data");
  7431. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  7432. EXPECT_TRUE(files[1].name == "hello");
  7433. EXPECT_TRUE(files[1].content == "world");
  7434. EXPECT_TRUE(files[1].filename == "");
  7435. EXPECT_TRUE(files[1].content_type == "");
  7436. } else {
  7437. std::string body;
  7438. content_reader([&](const char *data, size_t data_length) {
  7439. body.append(data, data_length);
  7440. return true;
  7441. });
  7442. }
  7443. });
  7444. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7445. auto se = detail::scope_exit([&] {
  7446. svr.stop();
  7447. t.join();
  7448. ASSERT_FALSE(svr.is_running());
  7449. });
  7450. svr.wait_until_ready();
  7451. {
  7452. std::string data(1024 * 1024 * 2, '&');
  7453. std::stringstream buffer;
  7454. buffer << data;
  7455. Client cli("https://localhost:8080");
  7456. cli.enable_server_certificate_verification(false);
  7457. MultipartFormDataItemsForClientInput items{
  7458. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7459. {"hello", "world", "", ""},
  7460. };
  7461. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7462. ASSERT_TRUE(res);
  7463. ASSERT_EQ(StatusCode::OK_200, res->status);
  7464. }
  7465. }
  7466. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7467. std::string data(1024 * 1024 * 2, '&');
  7468. std::stringstream buffer;
  7469. buffer << data;
  7470. Client cli("https://localhost:8080");
  7471. cli.enable_server_certificate_verification(false);
  7472. MultipartFormDataItemsForClientInput items{
  7473. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7474. {"hello", "world", "", ""},
  7475. };
  7476. for (const char &c : " \t\r\n") {
  7477. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7478. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7479. ASSERT_FALSE(res);
  7480. }
  7481. }
  7482. TEST(MultipartFormDataTest, AlternateFilename) {
  7483. auto handled = false;
  7484. Server svr;
  7485. svr.Post("/test", [&](const Request &req, Response &res) {
  7486. ASSERT_EQ(3u, req.files.size());
  7487. auto it = req.files.begin();
  7488. ASSERT_EQ("file1", it->second.name);
  7489. ASSERT_EQ("A.txt", it->second.filename);
  7490. ASSERT_EQ("text/plain", it->second.content_type);
  7491. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  7492. ++it;
  7493. ASSERT_EQ("file2", it->second.name);
  7494. ASSERT_EQ("a.html", it->second.filename);
  7495. ASSERT_EQ("text/html", it->second.content_type);
  7496. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  7497. it->second.content);
  7498. ++it;
  7499. ASSERT_EQ("text", it->second.name);
  7500. ASSERT_EQ("", it->second.filename);
  7501. ASSERT_EQ("", it->second.content_type);
  7502. ASSERT_EQ("text default", it->second.content);
  7503. res.set_content("ok", "text/plain");
  7504. handled = true;
  7505. });
  7506. thread t = thread([&] { svr.listen(HOST, PORT); });
  7507. auto se = detail::scope_exit([&] {
  7508. svr.stop();
  7509. t.join();
  7510. ASSERT_FALSE(svr.is_running());
  7511. ASSERT_TRUE(handled);
  7512. });
  7513. svr.wait_until_ready();
  7514. auto req = "POST /test HTTP/1.1\r\n"
  7515. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7516. "Content-Length: 399\r\n"
  7517. "\r\n"
  7518. "----------\r\n"
  7519. "Content-Disposition: form-data; name=\"text\"\r\n"
  7520. "\r\n"
  7521. "text default\r\n"
  7522. "----------\r\n"
  7523. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  7524. "filename=\"a.txt\"; name=\"file1\"\r\n"
  7525. "Content-Type: text/plain\r\n"
  7526. "\r\n"
  7527. "Content of a.txt.\r\n"
  7528. "\r\n"
  7529. "----------\r\n"
  7530. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  7531. "\"a.html\"\r\n"
  7532. "Content-Type: text/html\r\n"
  7533. "\r\n"
  7534. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  7535. "\r\n"
  7536. "------------\r\n";
  7537. ASSERT_TRUE(send_request(1, req));
  7538. }
  7539. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  7540. auto handled = false;
  7541. Server svr;
  7542. svr.Post("/test", [&](const Request &req, Response &) {
  7543. ASSERT_EQ(2u, req.files.size());
  7544. auto it = req.files.begin();
  7545. ASSERT_EQ("text1", it->second.name);
  7546. ASSERT_EQ("text1", it->second.content);
  7547. ++it;
  7548. ASSERT_EQ("text2", it->second.name);
  7549. ASSERT_EQ("text2", it->second.content);
  7550. handled = true;
  7551. });
  7552. thread t = thread([&] { svr.listen(HOST, PORT); });
  7553. auto se = detail::scope_exit([&] {
  7554. svr.stop();
  7555. t.join();
  7556. ASSERT_FALSE(svr.is_running());
  7557. ASSERT_TRUE(handled);
  7558. });
  7559. svr.wait_until_ready();
  7560. auto req = "POST /test HTTP/1.1\r\n"
  7561. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7562. "Content-Length: 146\r\n"
  7563. "\r\n----------\r\n"
  7564. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7565. "\r\n"
  7566. "text1"
  7567. "\r\n----------\r\n"
  7568. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7569. "\r\n"
  7570. "text2"
  7571. "\r\n------------";
  7572. std::string response;
  7573. ASSERT_TRUE(send_request(1, req, &response));
  7574. ASSERT_EQ("200", response.substr(9, 3));
  7575. }
  7576. TEST(MultipartFormDataTest, ContentLength) {
  7577. auto handled = false;
  7578. Server svr;
  7579. svr.Post("/test", [&](const Request &req, Response &) {
  7580. ASSERT_EQ(2u, req.files.size());
  7581. auto it = req.files.begin();
  7582. ASSERT_EQ("text1", it->second.name);
  7583. ASSERT_EQ("text1", it->second.content);
  7584. ++it;
  7585. ASSERT_EQ("text2", it->second.name);
  7586. ASSERT_EQ("text2", it->second.content);
  7587. handled = true;
  7588. });
  7589. thread t = thread([&] { svr.listen(HOST, PORT); });
  7590. auto se = detail::scope_exit([&] {
  7591. svr.stop();
  7592. t.join();
  7593. ASSERT_FALSE(svr.is_running());
  7594. ASSERT_TRUE(handled);
  7595. });
  7596. svr.wait_until_ready();
  7597. auto req = "POST /test HTTP/1.1\r\n"
  7598. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7599. "Content-Length: 167\r\n"
  7600. "\r\n----------\r\n"
  7601. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7602. "Content-Length: 5\r\n"
  7603. "\r\n"
  7604. "text1"
  7605. "\r\n----------\r\n"
  7606. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7607. "\r\n"
  7608. "text2"
  7609. "\r\n------------\r\n";
  7610. std::string response;
  7611. ASSERT_TRUE(send_request(1, req, &response));
  7612. ASSERT_EQ("200", response.substr(9, 3));
  7613. }
  7614. TEST(MultipartFormDataTest, AccessPartHeaders) {
  7615. auto handled = false;
  7616. Server svr;
  7617. svr.Post("/test", [&](const Request &req, Response &) {
  7618. ASSERT_EQ(2u, req.files.size());
  7619. auto it = req.files.begin();
  7620. ASSERT_EQ("text1", it->second.name);
  7621. ASSERT_EQ("text1", it->second.content);
  7622. ASSERT_EQ(1U, it->second.headers.count("Content-Length"));
  7623. auto content_length = it->second.headers.find("CONTENT-length");
  7624. ASSERT_EQ("5", content_length->second);
  7625. ASSERT_EQ(3U, it->second.headers.size());
  7626. ++it;
  7627. ASSERT_EQ("text2", it->second.name);
  7628. ASSERT_EQ("text2", it->second.content);
  7629. auto &headers = it->second.headers;
  7630. ASSERT_EQ(3U, headers.size());
  7631. auto custom_header = headers.find("x-whatever");
  7632. ASSERT_TRUE(custom_header != headers.end());
  7633. ASSERT_NE("customvalue", custom_header->second);
  7634. ASSERT_EQ("CustomValue", custom_header->second);
  7635. ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  7636. handled = true;
  7637. });
  7638. thread t = thread([&] { svr.listen(HOST, PORT); });
  7639. auto se = detail::scope_exit([&] {
  7640. svr.stop();
  7641. t.join();
  7642. ASSERT_FALSE(svr.is_running());
  7643. ASSERT_TRUE(handled);
  7644. });
  7645. svr.wait_until_ready();
  7646. auto req = "POST /test HTTP/1.1\r\n"
  7647. "Content-Type: multipart/form-data;boundary=--------\r\n"
  7648. "Content-Length: 232\r\n"
  7649. "\r\n----------\r\n"
  7650. "Content-Disposition: form-data; name=\"text1\"\r\n"
  7651. "Content-Length: 5\r\n"
  7652. "X-Test: 1\r\n"
  7653. "\r\n"
  7654. "text1"
  7655. "\r\n----------\r\n"
  7656. "Content-Disposition: form-data; name=\"text2\"\r\n"
  7657. "Content-Type: text/plain\r\n"
  7658. "X-Whatever: CustomValue\r\n"
  7659. "\r\n"
  7660. "text2"
  7661. "\r\n------------\r\n"
  7662. "That should be disregarded. Not even read";
  7663. std::string response;
  7664. ASSERT_TRUE(send_request(1, req, &response));
  7665. ASSERT_EQ("200", response.substr(9, 3));
  7666. }
  7667. #endif
  7668. TEST(MultipartFormDataTest, LargeHeader) {
  7669. auto handled = false;
  7670. Server svr;
  7671. svr.Post("/test", [&](const Request &req, Response &) {
  7672. ASSERT_EQ(1u, req.files.size());
  7673. auto it = req.files.begin();
  7674. ASSERT_EQ("name1", it->second.name);
  7675. ASSERT_EQ("text1", it->second.content);
  7676. handled = true;
  7677. });
  7678. thread t = thread([&] { svr.listen(HOST, PORT); });
  7679. auto se = detail::scope_exit([&] {
  7680. svr.stop();
  7681. t.join();
  7682. ASSERT_FALSE(svr.is_running());
  7683. ASSERT_TRUE(handled);
  7684. });
  7685. svr.wait_until_ready();
  7686. auto boundary = std::string("cpp-httplib-multipart-data");
  7687. std::string content = "--" + boundary +
  7688. "\r\n"
  7689. "Content-Disposition: form-data; name=\"name1\"\r\n"
  7690. "\r\n"
  7691. "text1\r\n"
  7692. "--" +
  7693. boundary + "--\r\n";
  7694. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  7695. "Content-Type: multipart/form-data;boundary=" +
  7696. boundary +
  7697. "\r\n"
  7698. "Content-Length: " +
  7699. std::to_string(content.size()) +
  7700. "\r\n"
  7701. "Dummy-Header: ";
  7702. std::string header_suffix = "\r\n"
  7703. "\r\n";
  7704. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  7705. size_t header_dummy_size =
  7706. read_buff_size -
  7707. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  7708. auto header_dummy = std::string(header_dummy_size, '@');
  7709. auto req = header_prefix + header_dummy + header_suffix + content;
  7710. std::string response;
  7711. ASSERT_TRUE(send_request(1, req, &response));
  7712. ASSERT_EQ("200", response.substr(9, 3));
  7713. }
  7714. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  7715. static constexpr unsigned int number_of_tasks{1000000};
  7716. std::atomic_uint count{0};
  7717. std::unique_ptr<TaskQueue> task_queue{
  7718. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  7719. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7720. auto queued = task_queue->enqueue(
  7721. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  7722. EXPECT_TRUE(queued);
  7723. }
  7724. EXPECT_NO_THROW(task_queue->shutdown());
  7725. EXPECT_EQ(number_of_tasks, count.load());
  7726. }
  7727. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  7728. static constexpr unsigned int number_of_tasks{1000000};
  7729. static constexpr unsigned int qlimit{2};
  7730. unsigned int queued_count{0};
  7731. std::atomic_uint count{0};
  7732. std::unique_ptr<TaskQueue> task_queue{
  7733. new ThreadPool{/*num_threads=*/1, qlimit}};
  7734. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  7735. if (task_queue->enqueue(
  7736. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  7737. queued_count++;
  7738. }
  7739. }
  7740. EXPECT_NO_THROW(task_queue->shutdown());
  7741. EXPECT_EQ(queued_count, count.load());
  7742. EXPECT_TRUE(queued_count <= number_of_tasks);
  7743. EXPECT_TRUE(queued_count >= qlimit);
  7744. }
  7745. TEST(TaskQueueTest, MaxQueuedRequests) {
  7746. static constexpr unsigned int qlimit{3};
  7747. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  7748. std::condition_variable sem_cv;
  7749. std::mutex sem_mtx;
  7750. int credits = 0;
  7751. bool queued;
  7752. /* Fill up the queue with tasks that will block until we give them credits to
  7753. * complete. */
  7754. for (unsigned int n = 0; n <= qlimit;) {
  7755. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  7756. std::unique_lock<std::mutex> lock(sem_mtx);
  7757. while (credits <= 0) {
  7758. sem_cv.wait(lock);
  7759. }
  7760. /* Consume the credit and signal the test code if they are all gone. */
  7761. if (--credits == 0) { sem_cv.notify_one(); }
  7762. });
  7763. if (n < qlimit) {
  7764. /* The first qlimit enqueues must succeed. */
  7765. EXPECT_TRUE(queued);
  7766. } else {
  7767. /* The last one will succeed only when the worker thread
  7768. * starts and dequeues the first blocking task. Although
  7769. * not necessary for the correctness of this test, we sleep for
  7770. * a short while to avoid busy waiting. */
  7771. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7772. }
  7773. if (queued) { n++; }
  7774. }
  7775. /* Further enqueues must fail since the queue is full. */
  7776. for (auto i = 0; i < 4; i++) {
  7777. queued = task_queue->enqueue([] {});
  7778. EXPECT_FALSE(queued);
  7779. }
  7780. /* Give the credits to allow the previous tasks to complete. */
  7781. {
  7782. std::unique_lock<std::mutex> lock(sem_mtx);
  7783. credits += qlimit + 1;
  7784. }
  7785. sem_cv.notify_all();
  7786. /* Wait for all the credits to be consumed. */
  7787. {
  7788. std::unique_lock<std::mutex> lock(sem_mtx);
  7789. while (credits > 0) {
  7790. sem_cv.wait(lock);
  7791. }
  7792. }
  7793. /* Check that we are able again to enqueue at least qlimit tasks. */
  7794. for (unsigned int i = 0; i < qlimit; i++) {
  7795. queued = task_queue->enqueue([] {});
  7796. EXPECT_TRUE(queued);
  7797. }
  7798. EXPECT_NO_THROW(task_queue->shutdown());
  7799. }
  7800. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  7801. Server svr;
  7802. svr.Get("/", [](const Request & /*req*/, Response &res) {
  7803. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  7804. });
  7805. svr.Get("/hello", [](const Request &req, Response &res) {
  7806. res.set_content(req.get_param_value("key"), "text/plain");
  7807. });
  7808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7809. auto se = detail::scope_exit([&] {
  7810. svr.stop();
  7811. thread.join();
  7812. ASSERT_FALSE(svr.is_running());
  7813. });
  7814. svr.wait_until_ready();
  7815. {
  7816. Client cli(HOST, PORT);
  7817. cli.set_follow_location(true);
  7818. auto res = cli.Get("/");
  7819. ASSERT_TRUE(res);
  7820. EXPECT_EQ(StatusCode::OK_200, res->status);
  7821. EXPECT_EQ("val&key2=val2", res->body);
  7822. }
  7823. }
  7824. TEST(VulnerabilityTest, CRLFInjection) {
  7825. Server svr;
  7826. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  7827. res.set_content("Hello 1", "text/plain");
  7828. });
  7829. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  7830. res.set_content("Hello 2", "text/plain");
  7831. });
  7832. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  7833. res.set_content("Hello 3", "text/plain");
  7834. });
  7835. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  7836. res.set_content("Hello 4", "text/plain");
  7837. });
  7838. svr.set_logger([](const Request &req, const Response & /*res*/) {
  7839. for (const auto &x : req.headers) {
  7840. auto key = x.first;
  7841. EXPECT_STRNE("evil", key.c_str());
  7842. }
  7843. });
  7844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7845. auto se = detail::scope_exit([&] {
  7846. svr.stop();
  7847. thread.join();
  7848. ASSERT_FALSE(svr.is_running());
  7849. });
  7850. svr.wait_until_ready();
  7851. {
  7852. Client cli(HOST, PORT);
  7853. cli.Post("/test1", "A=B",
  7854. "application/x-www-form-urlencoded\r\nevil: hello1");
  7855. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  7856. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  7857. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  7858. }
  7859. }
  7860. TEST(PathParamsTest, StaticMatch) {
  7861. const auto pattern = "/users/all";
  7862. detail::PathParamsMatcher matcher(pattern);
  7863. Request request;
  7864. request.path = "/users/all";
  7865. ASSERT_TRUE(matcher.match(request));
  7866. std::unordered_map<std::string, std::string> expected_params = {};
  7867. EXPECT_EQ(request.path_params, expected_params);
  7868. }
  7869. TEST(PathParamsTest, StaticMismatch) {
  7870. const auto pattern = "/users/all";
  7871. detail::PathParamsMatcher matcher(pattern);
  7872. Request request;
  7873. request.path = "/users/1";
  7874. ASSERT_FALSE(matcher.match(request));
  7875. }
  7876. TEST(PathParamsTest, SingleParamInTheMiddle) {
  7877. const auto pattern = "/users/:id/subscriptions";
  7878. detail::PathParamsMatcher matcher(pattern);
  7879. Request request;
  7880. request.path = "/users/42/subscriptions";
  7881. ASSERT_TRUE(matcher.match(request));
  7882. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7883. EXPECT_EQ(request.path_params, expected_params);
  7884. }
  7885. TEST(PathParamsTest, SingleParamInTheEnd) {
  7886. const auto pattern = "/users/:id";
  7887. detail::PathParamsMatcher matcher(pattern);
  7888. Request request;
  7889. request.path = "/users/24";
  7890. ASSERT_TRUE(matcher.match(request));
  7891. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  7892. EXPECT_EQ(request.path_params, expected_params);
  7893. }
  7894. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  7895. const auto pattern = "/users/:id/";
  7896. detail::PathParamsMatcher matcher(pattern);
  7897. Request request;
  7898. request.path = "/users/42/";
  7899. ASSERT_TRUE(matcher.match(request));
  7900. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  7901. EXPECT_EQ(request.path_params, expected_params);
  7902. }
  7903. TEST(PathParamsTest, EmptyParam) {
  7904. const auto pattern = "/users/:id/";
  7905. detail::PathParamsMatcher matcher(pattern);
  7906. Request request;
  7907. request.path = "/users//";
  7908. ASSERT_TRUE(matcher.match(request));
  7909. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  7910. EXPECT_EQ(request.path_params, expected_params);
  7911. }
  7912. TEST(PathParamsTest, FragmentMismatch) {
  7913. const auto pattern = "/users/:id/";
  7914. detail::PathParamsMatcher matcher(pattern);
  7915. Request request;
  7916. request.path = "/admins/24/";
  7917. ASSERT_FALSE(matcher.match(request));
  7918. }
  7919. TEST(PathParamsTest, ExtraFragments) {
  7920. const auto pattern = "/users/:id";
  7921. detail::PathParamsMatcher matcher(pattern);
  7922. Request request;
  7923. request.path = "/users/42/subscriptions";
  7924. ASSERT_FALSE(matcher.match(request));
  7925. }
  7926. TEST(PathParamsTest, MissingTrailingParam) {
  7927. const auto pattern = "/users/:id";
  7928. detail::PathParamsMatcher matcher(pattern);
  7929. Request request;
  7930. request.path = "/users";
  7931. ASSERT_FALSE(matcher.match(request));
  7932. }
  7933. TEST(PathParamsTest, MissingParamInTheMiddle) {
  7934. const auto pattern = "/users/:id/subscriptions";
  7935. detail::PathParamsMatcher matcher(pattern);
  7936. Request request;
  7937. request.path = "/users/subscriptions";
  7938. ASSERT_FALSE(matcher.match(request));
  7939. }
  7940. TEST(PathParamsTest, MultipleParams) {
  7941. const auto pattern = "/users/:userid/subscriptions/:subid";
  7942. detail::PathParamsMatcher matcher(pattern);
  7943. Request request;
  7944. request.path = "/users/42/subscriptions/2";
  7945. ASSERT_TRUE(matcher.match(request));
  7946. std::unordered_map<std::string, std::string> expected_params = {
  7947. {"userid", "42"}, {"subid", "2"}};
  7948. EXPECT_EQ(request.path_params, expected_params);
  7949. }
  7950. TEST(PathParamsTest, SequenceOfParams) {
  7951. const auto pattern = "/values/:x/:y/:z";
  7952. detail::PathParamsMatcher matcher(pattern);
  7953. Request request;
  7954. request.path = "/values/1/2/3";
  7955. ASSERT_TRUE(matcher.match(request));
  7956. std::unordered_map<std::string, std::string> expected_params = {
  7957. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  7958. EXPECT_EQ(request.path_params, expected_params);
  7959. }
  7960. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  7961. const auto pattern = "/prefix:suffix";
  7962. detail::PathParamsMatcher matcher(pattern);
  7963. Request request;
  7964. request.path = "/prefix:suffix";
  7965. ASSERT_TRUE(matcher.match(request));
  7966. const std::unordered_map<std::string, std::string> expected_params = {};
  7967. EXPECT_EQ(request.path_params, expected_params);
  7968. }
  7969. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  7970. // If ipv6 regex working, regex match codepath is taken.
  7971. // else port will default to 80 in Client impl
  7972. int clientImplMagicPort = 80;
  7973. int port = 4321;
  7974. // above ports must be different to avoid false negative
  7975. EXPECT_NE(clientImplMagicPort, port);
  7976. std::string ipV6TestURL = "http://[ff06::c3]";
  7977. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  7978. CLIENT_PRIVATE_KEY_FILE);
  7979. EXPECT_EQ(cli.port(), port);
  7980. }
  7981. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  7982. auto file_path = "./www/dir/index.html";
  7983. auto dir_path = "./www/dir";
  7984. detail::FileStat stat_file(file_path);
  7985. EXPECT_TRUE(stat_file.is_file());
  7986. EXPECT_FALSE(stat_file.is_dir());
  7987. detail::FileStat stat_dir(dir_path);
  7988. EXPECT_FALSE(stat_dir.is_file());
  7989. EXPECT_TRUE(stat_dir.is_dir());
  7990. }
  7991. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  7992. Server svr;
  7993. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7994. EXPECT_EQ(res.status, 400);
  7995. });
  7996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  7997. auto se = detail::scope_exit([&] {
  7998. svr.stop();
  7999. thread.join();
  8000. ASSERT_FALSE(svr.is_running());
  8001. });
  8002. svr.wait_until_ready();
  8003. Client cli(HOST, PORT);
  8004. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8005. }
  8006. TEST(InvalidHeaderCharsTest, is_field_name) {
  8007. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8008. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8009. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8010. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8011. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8012. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8013. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8014. EXPECT_FALSE(detail::fields::is_field_name(""));
  8015. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8016. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8017. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8018. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8019. }
  8020. TEST(InvalidHeaderCharsTest, is_field_value) {
  8021. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8022. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8023. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8024. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8025. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8026. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8027. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8028. EXPECT_TRUE(detail::fields::is_field_value(""));
  8029. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8030. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8031. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8032. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8033. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8034. }
  8035. TEST(InvalidHeaderCharsTest, OnServer) {
  8036. Server svr;
  8037. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8038. std::string header = "Not Set";
  8039. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8040. res.set_header(header, "value");
  8041. res.set_content("Page Content Page Content", "text/plain");
  8042. });
  8043. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8044. std::string header = "Not Set";
  8045. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8046. res.set_header("X-Test", header);
  8047. res.set_content("Page Content Page Content", "text/plain");
  8048. });
  8049. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8050. auto se = detail::scope_exit([&] {
  8051. svr.stop();
  8052. thread.join();
  8053. ASSERT_FALSE(svr.is_running());
  8054. });
  8055. svr.wait_until_ready();
  8056. Client cli(HOST, PORT);
  8057. {
  8058. auto res = cli.Get(
  8059. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8060. ASSERT_TRUE(res);
  8061. EXPECT_EQ("Page Content Page Content", res->body);
  8062. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8063. }
  8064. {
  8065. auto res = cli.Get(
  8066. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8067. ASSERT_TRUE(res);
  8068. EXPECT_EQ("Page Content Page Content", res->body);
  8069. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8070. }
  8071. }
  8072. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8073. auto handled = false;
  8074. Server svr;
  8075. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8076. thread t = thread([&] { svr.listen(HOST, PORT); });
  8077. auto se = detail::scope_exit([&] {
  8078. svr.stop();
  8079. t.join();
  8080. ASSERT_FALSE(svr.is_running());
  8081. ASSERT_FALSE(handled);
  8082. });
  8083. svr.wait_until_ready();
  8084. auto req = "POST /test HTTP/1.1\r\n"
  8085. "Content-Length: x\r\n"
  8086. "\r\n";
  8087. std::string response;
  8088. ASSERT_TRUE(send_request(1, req, &response));
  8089. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8090. response.substr(0, response.find("\r\n")));
  8091. }
  8092. #ifndef _WIN32
  8093. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8094. static constexpr char reject[] = "Unauthorized";
  8095. static constexpr char accept[] = "Upload accepted";
  8096. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8097. Server svr;
  8098. svr.set_expect_100_continue_handler(
  8099. [](const Request & /*req*/, Response &res) {
  8100. res.status = StatusCode::Unauthorized_401;
  8101. res.set_content(reject, "text/plain");
  8102. return res.status;
  8103. });
  8104. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8105. res.set_content(accept, "text/plain");
  8106. });
  8107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8108. auto se = detail::scope_exit([&] {
  8109. svr.stop();
  8110. thread.join();
  8111. ASSERT_FALSE(svr.is_running());
  8112. });
  8113. svr.wait_until_ready();
  8114. {
  8115. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8116. curl_easy_init(), &curl_easy_cleanup};
  8117. ASSERT_NE(curl, nullptr);
  8118. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8119. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8120. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8121. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8122. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8123. &curl_slist_free_all};
  8124. ASSERT_NE(list, nullptr);
  8125. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8126. struct read_data {
  8127. size_t read_size;
  8128. size_t total_size;
  8129. } data = {0, total_size};
  8130. using read_callback_t =
  8131. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8132. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8133. void *userdata) -> size_t {
  8134. read_data *data = (read_data *)userdata;
  8135. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8136. std::fill_n(ptr, size * nmemb, 'A');
  8137. data->read_size += size * nmemb;
  8138. return size * nmemb;
  8139. };
  8140. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8141. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8142. std::vector<char> buffer;
  8143. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8144. using write_callback_t =
  8145. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8146. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8147. void *userdata) -> size_t {
  8148. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8149. buffer->reserve(buffer->size() + size * nmemb + 1);
  8150. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8151. return size * nmemb;
  8152. };
  8153. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8154. {
  8155. const auto res = curl_easy_perform(curl.get());
  8156. ASSERT_EQ(res, CURLE_OK);
  8157. }
  8158. {
  8159. auto response_code = long{};
  8160. const auto res =
  8161. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8162. ASSERT_EQ(res, CURLE_OK);
  8163. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8164. }
  8165. {
  8166. auto dl = curl_off_t{};
  8167. const auto res =
  8168. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8169. ASSERT_EQ(res, CURLE_OK);
  8170. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8171. }
  8172. {
  8173. buffer.push_back('\0');
  8174. ASSERT_STRCASEEQ(buffer.data(), reject);
  8175. }
  8176. }
  8177. }
  8178. #endif
  8179. template <typename S, typename C>
  8180. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8181. svr.Get("/stream", [&](const Request &, Response &res) {
  8182. auto data = new std::string("01234567890123456789");
  8183. res.set_content_provider(
  8184. data->size(), "text/plain",
  8185. [&, data](size_t offset, size_t length, DataSink &sink) {
  8186. const size_t DATA_CHUNK_SIZE = 4;
  8187. const auto &d = *data;
  8188. std::this_thread::sleep_for(std::chrono::seconds(1));
  8189. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8190. return true;
  8191. },
  8192. [data](bool success) {
  8193. EXPECT_FALSE(success);
  8194. delete data;
  8195. });
  8196. });
  8197. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8198. auto i = new size_t(0);
  8199. res.set_content_provider(
  8200. "text/plain",
  8201. [i](size_t, DataSink &sink) {
  8202. if (*i < 5) {
  8203. std::this_thread::sleep_for(std::chrono::seconds(1));
  8204. sink.write("abcd", 4);
  8205. (*i)++;
  8206. } else {
  8207. sink.done();
  8208. }
  8209. return true;
  8210. },
  8211. [i](bool success) {
  8212. EXPECT_FALSE(success);
  8213. delete i;
  8214. });
  8215. });
  8216. svr.Get("/chunked", [&](const Request &, Response &res) {
  8217. auto i = new size_t(0);
  8218. res.set_chunked_content_provider(
  8219. "text/plain",
  8220. [i](size_t, DataSink &sink) {
  8221. if (*i < 5) {
  8222. std::this_thread::sleep_for(std::chrono::seconds(1));
  8223. sink.os << "abcd";
  8224. (*i)++;
  8225. } else {
  8226. sink.done();
  8227. }
  8228. return true;
  8229. },
  8230. [i](bool success) {
  8231. EXPECT_FALSE(success);
  8232. delete i;
  8233. });
  8234. });
  8235. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8236. auto se = detail::scope_exit([&] {
  8237. svr.stop();
  8238. listen_thread.join();
  8239. ASSERT_FALSE(svr.is_running());
  8240. });
  8241. svr.wait_until_ready();
  8242. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8243. {
  8244. auto start = std::chrono::steady_clock::now();
  8245. auto res = cli.Get("/stream");
  8246. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8247. std::chrono::steady_clock::now() - start)
  8248. .count();
  8249. ASSERT_FALSE(res);
  8250. EXPECT_EQ(Error::Read, res.error());
  8251. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8252. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8253. }
  8254. {
  8255. auto start = std::chrono::steady_clock::now();
  8256. auto res = cli.Get("/stream_without_length");
  8257. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8258. std::chrono::steady_clock::now() - start)
  8259. .count();
  8260. ASSERT_FALSE(res);
  8261. EXPECT_EQ(Error::Read, res.error());
  8262. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8263. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8264. }
  8265. {
  8266. auto start = std::chrono::steady_clock::now();
  8267. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8268. EXPECT_EQ("abcd", string(data, data_length));
  8269. return true;
  8270. });
  8271. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8272. std::chrono::steady_clock::now() - start)
  8273. .count();
  8274. ASSERT_FALSE(res);
  8275. EXPECT_EQ(Error::Read, res.error());
  8276. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8277. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8278. }
  8279. }
  8280. TEST(MaxTimeoutTest, ContentStream) {
  8281. time_t timeout = 2000;
  8282. time_t threshold = 200;
  8283. Server svr;
  8284. Client cli("localhost", PORT);
  8285. max_timeout_test(svr, cli, timeout, threshold);
  8286. }
  8287. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8288. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8289. time_t timeout = 2000;
  8290. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8292. SSLClient cli("localhost", PORT);
  8293. cli.enable_server_certificate_verification(false);
  8294. max_timeout_test(svr, cli, timeout, threshold);
  8295. }
  8296. #endif
  8297. class EventDispatcher {
  8298. public:
  8299. EventDispatcher() {}
  8300. void wait_event(DataSink *sink) {
  8301. unique_lock<mutex> lk(m_);
  8302. int id = id_;
  8303. cv_.wait(lk, [&] { return cid_ == id; });
  8304. sink->write(message_.data(), message_.size());
  8305. }
  8306. void send_event(const string &message) {
  8307. lock_guard<mutex> lk(m_);
  8308. cid_ = id_++;
  8309. message_ = message;
  8310. cv_.notify_all();
  8311. }
  8312. private:
  8313. mutex m_;
  8314. condition_variable cv_;
  8315. atomic_int id_{0};
  8316. atomic_int cid_{-1};
  8317. string message_;
  8318. };
  8319. TEST(ClientInThreadTest, Issue2068) {
  8320. EventDispatcher ed;
  8321. Server svr;
  8322. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8323. res.set_chunked_content_provider("text/event-stream",
  8324. [&](size_t /*offset*/, DataSink &sink) {
  8325. ed.wait_event(&sink);
  8326. return true;
  8327. });
  8328. });
  8329. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8330. svr.wait_until_ready();
  8331. thread event_thread([&] {
  8332. int id = 0;
  8333. while (svr.is_running()) {
  8334. this_thread::sleep_for(chrono::milliseconds(500));
  8335. std::stringstream ss;
  8336. ss << "data: " << id << "\n\n";
  8337. ed.send_event(ss.str());
  8338. id++;
  8339. }
  8340. });
  8341. auto se = detail::scope_exit([&] {
  8342. svr.stop();
  8343. listen_thread.join();
  8344. event_thread.join();
  8345. ASSERT_FALSE(svr.is_running());
  8346. });
  8347. {
  8348. auto client = detail::make_unique<Client>(HOST, PORT);
  8349. client->set_read_timeout(std::chrono::minutes(10));
  8350. std::atomic<bool> stop{false};
  8351. std::thread t([&] {
  8352. client->Get("/event1",
  8353. [&](const char *, size_t) -> bool { return !stop; });
  8354. });
  8355. std::this_thread::sleep_for(std::chrono::seconds(2));
  8356. stop = true;
  8357. client->stop();
  8358. client.reset();
  8359. t.join();
  8360. }
  8361. }