test.cc 254 KB

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