test.cc 253 KB

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