test.cc 246 KB

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