1
0

test.cc 273 KB

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