test.cc 253 KB

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