1
0

test.cc 328 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <fstream>
  15. #include <future>
  16. #include <limits>
  17. #include <memory>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <thread>
  21. #include <type_traits>
  22. #include <vector>
  23. #define SERVER_CERT_FILE "./cert.pem"
  24. #define SERVER_CERT2_FILE "./cert2.pem"
  25. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  26. #define CA_CERT_FILE "./ca-bundle.crt"
  27. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  28. #define CLIENT_CA_CERT_DIR "."
  29. #define CLIENT_CERT_FILE "./client.cert.pem"
  30. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  31. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  32. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  34. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  35. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  37. using namespace std;
  38. using namespace httplib;
  39. const char *HOST = "localhost";
  40. const int PORT = 1234;
  41. const string LONG_QUERY_VALUE = string(25000, '@');
  42. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  43. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  44. const string TOO_LONG_QUERY_URL =
  45. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  46. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  47. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  48. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  49. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  50. return file.name == key;
  51. });
  52. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  53. return *it;
  54. #else
  55. if (it != items.end()) { return *it; }
  56. throw std::runtime_error("invalid multipart form data name error");
  57. #endif
  58. }
  59. static void read_file(const std::string &path, std::string &out) {
  60. std::ifstream fs(path, std::ios_base::binary);
  61. if (!fs) throw std::runtime_error("File not found: " + path);
  62. fs.seekg(0, std::ios_base::end);
  63. auto size = fs.tellg();
  64. fs.seekg(0);
  65. out.resize(static_cast<size_t>(size));
  66. fs.read(&out[0], static_cast<std::streamsize>(size));
  67. }
  68. class UnixSocketTest : public ::testing::Test {
  69. protected:
  70. void TearDown() override { std::remove(pathname_.c_str()); }
  71. void client_GET(const std::string &addr) {
  72. httplib::Client cli{addr};
  73. cli.set_address_family(AF_UNIX);
  74. ASSERT_TRUE(cli.is_valid());
  75. const auto &result = cli.Get(pattern_);
  76. ASSERT_TRUE(result) << "error: " << result.error();
  77. const auto &resp = result.value();
  78. EXPECT_EQ(resp.status, StatusCode::OK_200);
  79. EXPECT_EQ(resp.body, content_);
  80. }
  81. const std::string pathname_{"./httplib-server.sock"};
  82. const std::string pattern_{"/hi"};
  83. const std::string content_{"Hello World!"};
  84. };
  85. TEST_F(UnixSocketTest, pathname) {
  86. httplib::Server svr;
  87. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. });
  90. std::thread t{[&] {
  91. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  92. }};
  93. auto se = detail::scope_exit([&] {
  94. svr.stop();
  95. t.join();
  96. ASSERT_FALSE(svr.is_running());
  97. });
  98. svr.wait_until_ready();
  99. ASSERT_TRUE(svr.is_running());
  100. client_GET(pathname_);
  101. }
  102. #if defined(__linux__) || \
  103. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  104. TEST_F(UnixSocketTest, PeerPid) {
  105. httplib::Server svr;
  106. std::string remote_port_val;
  107. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  108. res.set_content(content_, "text/plain");
  109. remote_port_val = req.get_header_value("REMOTE_PORT");
  110. });
  111. std::thread t{[&] {
  112. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  113. }};
  114. auto se = detail::scope_exit([&] {
  115. svr.stop();
  116. t.join();
  117. ASSERT_FALSE(svr.is_running());
  118. });
  119. svr.wait_until_ready();
  120. ASSERT_TRUE(svr.is_running());
  121. client_GET(pathname_);
  122. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  123. }
  124. #endif
  125. #ifdef __linux__
  126. TEST_F(UnixSocketTest, abstract) {
  127. constexpr char svr_path[]{"\x00httplib-server.sock"};
  128. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  129. httplib::Server svr;
  130. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  131. res.set_content(content_, "text/plain");
  132. });
  133. std::thread t{[&] {
  134. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  135. }};
  136. auto se = detail::scope_exit([&] {
  137. svr.stop();
  138. t.join();
  139. ASSERT_FALSE(svr.is_running());
  140. });
  141. svr.wait_until_ready();
  142. ASSERT_TRUE(svr.is_running());
  143. client_GET(abstract_addr);
  144. }
  145. #endif
  146. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  147. httplib::Server svr;
  148. std::string received_host_header;
  149. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  150. // Capture the Host header sent by the client
  151. auto host_iter = req.headers.find("Host");
  152. if (host_iter != req.headers.end()) {
  153. received_host_header = host_iter->second;
  154. }
  155. res.set_content(content_, "text/plain");
  156. });
  157. std::thread t{[&] {
  158. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  159. }};
  160. auto se = detail::scope_exit([&] {
  161. svr.stop();
  162. t.join();
  163. ASSERT_FALSE(svr.is_running());
  164. });
  165. svr.wait_until_ready();
  166. ASSERT_TRUE(svr.is_running());
  167. // Test that Host header is automatically set to "localhost" for Unix socket
  168. // connections
  169. httplib::Client cli{pathname_};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. // Verify that Host header was automatically set to "localhost"
  178. EXPECT_EQ(received_host_header, "localhost");
  179. }
  180. #ifndef _WIN32
  181. TEST(SocketStream, wait_writable_UNIX) {
  182. int fds[2];
  183. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  184. const auto asSocketStream = [&](socket_t fd,
  185. std::function<bool(Stream &)> func) {
  186. return detail::process_client_socket(
  187. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  188. };
  189. asSocketStream(fds[0], [&](Stream &s0) {
  190. EXPECT_EQ(s0.socket(), fds[0]);
  191. EXPECT_TRUE(s0.wait_writable());
  192. EXPECT_EQ(0, close(fds[1]));
  193. EXPECT_FALSE(s0.wait_writable());
  194. return true;
  195. });
  196. EXPECT_EQ(0, close(fds[0]));
  197. }
  198. TEST(SocketStream, wait_writable_INET) {
  199. sockaddr_in addr;
  200. memset(&addr, 0, sizeof(addr));
  201. addr.sin_family = AF_INET;
  202. addr.sin_port = htons(PORT + 1);
  203. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  204. int disconnected_svr_sock = -1;
  205. std::thread svr{[&] {
  206. const int s = socket(AF_INET, SOCK_STREAM, 0);
  207. ASSERT_LE(0, s);
  208. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  209. ASSERT_EQ(0, listen(s, 1));
  210. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  211. ASSERT_EQ(0, close(s));
  212. }};
  213. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  214. std::thread cli{[&] {
  215. const int s = socket(AF_INET, SOCK_STREAM, 0);
  216. ASSERT_LE(0, s);
  217. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  218. ASSERT_EQ(0, close(s));
  219. }};
  220. cli.join();
  221. svr.join();
  222. ASSERT_NE(disconnected_svr_sock, -1);
  223. const auto asSocketStream = [&](socket_t fd,
  224. std::function<bool(Stream &)> func) {
  225. return detail::process_client_socket(
  226. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  227. };
  228. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  229. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  230. EXPECT_FALSE(ss.wait_writable());
  231. return true;
  232. });
  233. ASSERT_EQ(0, close(disconnected_svr_sock));
  234. }
  235. #endif // #ifndef _WIN32
  236. TEST(ClientTest, MoveConstructible) {
  237. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  238. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  239. }
  240. TEST(ClientTest, MoveAssignable) {
  241. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  242. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  243. }
  244. #ifdef _WIN32
  245. TEST(StartupTest, WSAStartup) {
  246. WSADATA wsaData;
  247. int ret = WSAStartup(0x0002, &wsaData);
  248. ASSERT_EQ(0, ret);
  249. }
  250. #endif
  251. TEST(DecodePathTest, PercentCharacter) {
  252. EXPECT_EQ(
  253. decode_path_component(
  254. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  255. u8"descrip=Gastos áéíóúñÑ 6");
  256. }
  257. TEST(DecodePathTest, PercentCharacterNUL) {
  258. string expected;
  259. expected.push_back('x');
  260. expected.push_back('\0');
  261. expected.push_back('x');
  262. EXPECT_EQ(decode_path_component("x%00x"), expected);
  263. }
  264. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  265. string unescapedCharacters = "-_.!~*'()";
  266. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  267. }
  268. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  269. string reservedCharacters = ";,/?:@&=+$";
  270. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  271. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  272. }
  273. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  274. string chineseCharacters = u8"中国語";
  275. string russianCharacters = u8"дом";
  276. string brazilianCharacters = u8"óculos";
  277. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  278. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  279. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  280. "%D0%B4%D0%BE%D0%BC");
  281. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  282. }
  283. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  284. string unescapedCharacters = "-_.!~*'()";
  285. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  286. }
  287. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  288. string reservedCharacters = ";,/?:@&=+$";
  289. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  290. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  291. }
  292. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  293. string chineseCharacters = u8"中国語";
  294. string russianCharacters = u8"дом";
  295. string brazilianCharacters = u8"óculos";
  296. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  297. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  298. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  299. "%D0%B4%D0%BE%D0%BC");
  300. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  301. }
  302. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  303. // Issue #2082 use case: encoding path component with ampersand
  304. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  305. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  306. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  307. }
  308. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  309. string unescapedCharacters = "-_.!~*'()";
  310. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  311. }
  312. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  313. string reservedCharacters = ";,/?:@&=+$#";
  314. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  315. }
  316. TEST(EncodeUriTest, TestUTF8Characters) {
  317. string chineseCharacters = u8"中国語";
  318. string russianCharacters = u8"дом";
  319. string brazilianCharacters = u8"óculos";
  320. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  321. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  322. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  323. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  324. }
  325. TEST(EncodeUriTest, TestCompleteUri) {
  326. string uri =
  327. "https://example.com/path/to/resource?query=value&param=test#fragment";
  328. EXPECT_EQ(
  329. httplib::encode_uri(uri),
  330. "https://example.com/path/to/resource?query=value&param=test#fragment");
  331. }
  332. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  333. string uri =
  334. "https://example.com/path with spaces/file name.html?q=hello world";
  335. EXPECT_EQ(httplib::encode_uri(uri),
  336. "https://example.com/path%20with%20spaces/"
  337. "file%20name.html?q=hello%20world");
  338. }
  339. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  340. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  341. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  342. }
  343. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  344. string unescapedCharacters = "-_.!~*'()";
  345. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  346. }
  347. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  348. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  349. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  350. string encodedBrazilian = "%C3%B3culos";
  351. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  352. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  354. }
  355. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  356. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  357. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  358. "Piri Tommy Villiers - on & on");
  359. }
  360. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  361. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  362. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  363. }
  364. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  365. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  366. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  367. }
  368. TEST(DecodeUriTest, TestUTF8Characters) {
  369. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  370. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  371. string encodedBrazilian = "%C3%B3culos";
  372. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  373. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  374. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  375. }
  376. TEST(DecodeUriTest, TestCompleteUri) {
  377. string encodedUri = "https://example.com/path%20with%20spaces/"
  378. "file%20name.html?q=hello%20world";
  379. EXPECT_EQ(
  380. httplib::decode_uri(encodedUri),
  381. "https://example.com/path with spaces/file name.html?q=hello world");
  382. }
  383. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  384. string original =
  385. "https://example.com/path with spaces/file name.html?q=hello world";
  386. string encoded = httplib::encode_uri(original);
  387. string decoded = httplib::decode_uri(encoded);
  388. EXPECT_EQ(decoded, original);
  389. }
  390. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  391. string original = "Piri Tommy Villiers - on & on";
  392. string encoded = httplib::encode_uri_component(original);
  393. string decoded = httplib::decode_uri_component(encoded);
  394. EXPECT_EQ(decoded, original);
  395. }
  396. TEST(TrimTests, TrimStringTests) {
  397. EXPECT_EQ("abc", detail::trim_copy("abc"));
  398. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  399. EXPECT_TRUE(detail::trim_copy("").empty());
  400. }
  401. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  402. // Simple case without quality values
  403. std::vector<std::string> result1;
  404. EXPECT_TRUE(detail::parse_accept_header(
  405. "text/html,application/json,text/plain", result1));
  406. EXPECT_EQ(result1.size(), 3U);
  407. EXPECT_EQ(result1[0], "text/html");
  408. EXPECT_EQ(result1[1], "application/json");
  409. EXPECT_EQ(result1[2], "text/plain");
  410. // With quality values
  411. std::vector<std::string> result2;
  412. EXPECT_TRUE(detail::parse_accept_header(
  413. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  414. EXPECT_EQ(result2.size(), 3U);
  415. EXPECT_EQ(result2[0], "application/json"); // highest q value
  416. EXPECT_EQ(result2[1], "text/html");
  417. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  418. }
  419. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  420. // Mixed with and without quality values
  421. std::vector<std::string> result;
  422. EXPECT_TRUE(detail::parse_accept_header(
  423. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  424. EXPECT_EQ(result.size(), 3U);
  425. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  426. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  427. EXPECT_EQ(result[2], "application/json"); // q=0.5
  428. }
  429. TEST(ParseAcceptHeaderTest, EdgeCases) {
  430. // Empty header
  431. std::vector<std::string> empty_result;
  432. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  433. EXPECT_TRUE(empty_result.empty());
  434. // Single type
  435. std::vector<std::string> single_result;
  436. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  437. EXPECT_EQ(single_result.size(), 1U);
  438. EXPECT_EQ(single_result[0], "application/json");
  439. // Wildcard types
  440. std::vector<std::string> wildcard_result;
  441. EXPECT_TRUE(detail::parse_accept_header(
  442. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  443. EXPECT_EQ(wildcard_result.size(), 3U);
  444. EXPECT_EQ(wildcard_result[0], "application/json");
  445. EXPECT_EQ(wildcard_result[1], "text/*");
  446. EXPECT_EQ(wildcard_result[2], "*/*");
  447. }
  448. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  449. // Common browser Accept header
  450. std::vector<std::string> browser_result;
  451. EXPECT_TRUE(
  452. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  453. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  454. browser_result));
  455. EXPECT_EQ(browser_result.size(), 6U);
  456. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  457. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  461. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  462. // API client header
  463. std::vector<std::string> api_result;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  466. api_result));
  467. EXPECT_EQ(api_result.size(), 3U);
  468. EXPECT_EQ(api_result[0], "application/json");
  469. EXPECT_EQ(api_result[1], "application/xml");
  470. EXPECT_EQ(api_result[2], "text/plain");
  471. }
  472. TEST(ParseAcceptHeaderTest, SpecialCases) {
  473. // Quality value with 3 decimal places
  474. std::vector<std::string> decimal_result;
  475. EXPECT_TRUE(detail::parse_accept_header(
  476. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  477. EXPECT_EQ(decimal_result.size(), 2U);
  478. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  479. EXPECT_EQ(decimal_result[1], "text/html");
  480. // Zero quality (should still be included but with lowest priority)
  481. std::vector<std::string> zero_q_result;
  482. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  483. zero_q_result));
  484. EXPECT_EQ(zero_q_result.size(), 2U);
  485. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  486. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  487. // No spaces around commas
  488. std::vector<std::string> no_space_result;
  489. EXPECT_TRUE(detail::parse_accept_header(
  490. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  491. no_space_result));
  492. EXPECT_EQ(no_space_result.size(), 3U);
  493. EXPECT_EQ(no_space_result[0], "text/html");
  494. EXPECT_EQ(no_space_result[1], "application/json");
  495. EXPECT_EQ(no_space_result[2], "text/plain");
  496. }
  497. TEST(ParseAcceptHeaderTest, InvalidCases) {
  498. std::vector<std::string> result;
  499. // Invalid quality value (> 1.0)
  500. EXPECT_FALSE(
  501. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  502. // Invalid quality value (< 0.0)
  503. EXPECT_FALSE(
  504. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  505. // Invalid quality value (not a number)
  506. EXPECT_FALSE(detail::parse_accept_header(
  507. "text/html;q=invalid,application/json", result));
  508. // Empty quality value
  509. EXPECT_FALSE(
  510. detail::parse_accept_header("text/html;q=,application/json", result));
  511. // Invalid media type format (no slash and not wildcard)
  512. EXPECT_FALSE(
  513. detail::parse_accept_header("invalidtype,application/json", result));
  514. // Empty media type
  515. result.clear();
  516. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  517. // Only commas
  518. result.clear();
  519. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  520. // Valid cases should still work
  521. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  522. EXPECT_EQ(result.size(), 1U);
  523. EXPECT_EQ(result[0], "*/*");
  524. EXPECT_TRUE(detail::parse_accept_header("*", result));
  525. EXPECT_EQ(result.size(), 1U);
  526. EXPECT_EQ(result[0], "*");
  527. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  528. EXPECT_EQ(result.size(), 1U);
  529. EXPECT_EQ(result[0], "text/*");
  530. }
  531. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  532. Server svr;
  533. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  534. EXPECT_EQ(req.accept_content_types.size(), 3U);
  535. EXPECT_EQ(req.accept_content_types[0], "application/json");
  536. EXPECT_EQ(req.accept_content_types[1], "text/html");
  537. EXPECT_EQ(req.accept_content_types[2], "*/*");
  538. res.set_content("ok", "text/plain");
  539. });
  540. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  541. EXPECT_TRUE(false);
  542. res.set_content("bad request", "text/plain");
  543. });
  544. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  545. auto se = detail::scope_exit([&] {
  546. svr.stop();
  547. listen_thread.join();
  548. ASSERT_FALSE(svr.is_running());
  549. });
  550. svr.wait_until_ready();
  551. Client cli("localhost", PORT);
  552. {
  553. auto res =
  554. cli.Get("/accept_ok",
  555. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  556. ASSERT_TRUE(res);
  557. EXPECT_EQ(StatusCode::OK_200, res->status);
  558. }
  559. {
  560. auto res = cli.Get("/accept_bad_request",
  561. {{"Accept", "text/html;q=abc,application/json"}});
  562. ASSERT_TRUE(res);
  563. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  564. }
  565. }
  566. TEST(DivideTest, DivideStringTests) {
  567. auto divide = [](const std::string &str, char d) {
  568. std::string lhs;
  569. std::string rhs;
  570. detail::divide(str, d,
  571. [&](const char *lhs_data, std::size_t lhs_size,
  572. const char *rhs_data, std::size_t rhs_size) {
  573. lhs.assign(lhs_data, lhs_size);
  574. rhs.assign(rhs_data, rhs_size);
  575. });
  576. return std::make_pair(std::move(lhs), std::move(rhs));
  577. };
  578. {
  579. const auto res = divide("", '=');
  580. EXPECT_EQ(res.first, "");
  581. EXPECT_EQ(res.second, "");
  582. }
  583. {
  584. const auto res = divide("=", '=');
  585. EXPECT_EQ(res.first, "");
  586. EXPECT_EQ(res.second, "");
  587. }
  588. {
  589. const auto res = divide(" ", '=');
  590. EXPECT_EQ(res.first, " ");
  591. EXPECT_EQ(res.second, "");
  592. }
  593. {
  594. const auto res = divide("a", '=');
  595. EXPECT_EQ(res.first, "a");
  596. EXPECT_EQ(res.second, "");
  597. }
  598. {
  599. const auto res = divide("a=", '=');
  600. EXPECT_EQ(res.first, "a");
  601. EXPECT_EQ(res.second, "");
  602. }
  603. {
  604. const auto res = divide("=b", '=');
  605. EXPECT_EQ(res.first, "");
  606. EXPECT_EQ(res.second, "b");
  607. }
  608. {
  609. const auto res = divide("a=b", '=');
  610. EXPECT_EQ(res.first, "a");
  611. EXPECT_EQ(res.second, "b");
  612. }
  613. {
  614. const auto res = divide("a=b=", '=');
  615. EXPECT_EQ(res.first, "a");
  616. EXPECT_EQ(res.second, "b=");
  617. }
  618. {
  619. const auto res = divide("a=b=c", '=');
  620. EXPECT_EQ(res.first, "a");
  621. EXPECT_EQ(res.second, "b=c");
  622. }
  623. }
  624. TEST(SplitTest, ParseQueryString) {
  625. string s = "key1=val1&key2=val2&key3=val3";
  626. Params dic;
  627. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  628. [&](const char *b, const char *e) {
  629. string key, val;
  630. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  631. if (key.empty()) {
  632. key.assign(b2, e2);
  633. } else {
  634. val.assign(b2, e2);
  635. }
  636. });
  637. dic.emplace(key, val);
  638. });
  639. EXPECT_EQ("val1", dic.find("key1")->second);
  640. EXPECT_EQ("val2", dic.find("key2")->second);
  641. EXPECT_EQ("val3", dic.find("key3")->second);
  642. }
  643. TEST(SplitTest, ParseInvalidQueryTests) {
  644. {
  645. string s = " ";
  646. Params dict;
  647. detail::parse_query_text(s, dict);
  648. EXPECT_TRUE(dict.empty());
  649. }
  650. {
  651. string s = " = =";
  652. Params dict;
  653. detail::parse_query_text(s, dict);
  654. EXPECT_TRUE(dict.empty());
  655. }
  656. }
  657. TEST(ParseQueryTest, ParseQueryString) {
  658. {
  659. std::string s = "key1=val1&key2=val2&key3=val3";
  660. Params dic;
  661. detail::parse_query_text(s, dic);
  662. EXPECT_EQ("val1", dic.find("key1")->second);
  663. EXPECT_EQ("val2", dic.find("key2")->second);
  664. EXPECT_EQ("val3", dic.find("key3")->second);
  665. }
  666. {
  667. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  668. Params dic;
  669. detail::parse_query_text(s, dic);
  670. EXPECT_EQ("", dic.find("key1")->second);
  671. EXPECT_EQ("val1", dic.find("key2")->second);
  672. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  673. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  674. }
  675. }
  676. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  677. Params dic;
  678. EXPECT_EQ(detail::params_to_query_str(dic), "");
  679. dic.emplace("key1", "val1");
  680. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  681. dic.emplace("key2", "val2");
  682. dic.emplace("key3", "val3");
  683. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  684. }
  685. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  686. string content_type = "multipart/form-data; boundary=something";
  687. string boundary;
  688. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  689. EXPECT_TRUE(ret);
  690. EXPECT_EQ(boundary, "something");
  691. }
  692. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  693. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  694. string boundary;
  695. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  696. EXPECT_TRUE(ret);
  697. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  698. }
  699. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  700. string content_type =
  701. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  702. string boundary;
  703. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  704. EXPECT_TRUE(ret);
  705. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  706. }
  707. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  708. string content_type =
  709. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  710. string boundary;
  711. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  712. EXPECT_TRUE(ret);
  713. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  714. }
  715. TEST(GetHeaderValueTest, DefaultValue) {
  716. Headers headers = {{"Dummy", "Dummy"}};
  717. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  718. EXPECT_STREQ("text/plain", val);
  719. }
  720. TEST(GetHeaderValueTest, DefaultValueInt) {
  721. Headers headers = {{"Dummy", "Dummy"}};
  722. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  723. EXPECT_EQ(100ull, val);
  724. }
  725. TEST(GetHeaderValueTest, RegularValue) {
  726. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  727. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  728. EXPECT_STREQ("text/html", val);
  729. }
  730. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  731. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  732. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  733. EXPECT_STREQ("text/html", val);
  734. }
  735. TEST(GetHeaderValueTest, SetContent) {
  736. Response res;
  737. res.set_content("html", "text/html");
  738. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  739. res.set_content("text", "text/plain");
  740. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  741. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  742. }
  743. TEST(GetHeaderValueTest, RegularValueInt) {
  744. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  745. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  746. EXPECT_EQ(100ull, val);
  747. }
  748. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  749. Headers headers = {{"Content-Length", "x"}};
  750. auto is_invalid_value = false;
  751. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  752. is_invalid_value);
  753. EXPECT_EQ(0ull, val);
  754. EXPECT_TRUE(is_invalid_value);
  755. }
  756. TEST(GetHeaderValueTest, Range) {
  757. {
  758. Headers headers = {make_range_header({{1, -1}})};
  759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  760. EXPECT_STREQ("bytes=1-", val);
  761. }
  762. {
  763. Headers headers = {make_range_header({{-1, 1}})};
  764. auto val = detail::get_header_value(headers, "Range", 0, 0);
  765. EXPECT_STREQ("bytes=-1", val);
  766. }
  767. {
  768. Headers headers = {make_range_header({{1, 10}})};
  769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  770. EXPECT_STREQ("bytes=1-10", val);
  771. }
  772. {
  773. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  775. EXPECT_STREQ("bytes=1-10, 100-", val);
  776. }
  777. {
  778. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  780. EXPECT_STREQ("bytes=1-10, 100-200", val);
  781. }
  782. {
  783. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  785. EXPECT_STREQ("bytes=0-0, -1", val);
  786. }
  787. }
  788. TEST(ParseHeaderValueTest, Range) {
  789. {
  790. Ranges ranges;
  791. auto ret = detail::parse_range_header("bytes=1-", ranges);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(1u, ranges.size());
  794. EXPECT_EQ(1u, ranges[0].first);
  795. EXPECT_EQ(-1, ranges[0].second);
  796. }
  797. {
  798. Ranges ranges;
  799. auto ret = detail::parse_range_header("bytes=-1", ranges);
  800. EXPECT_TRUE(ret);
  801. EXPECT_EQ(1u, ranges.size());
  802. EXPECT_EQ(-1, ranges[0].first);
  803. EXPECT_EQ(1u, ranges[0].second);
  804. }
  805. {
  806. Ranges ranges;
  807. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  808. EXPECT_TRUE(ret);
  809. EXPECT_EQ(1u, ranges.size());
  810. EXPECT_EQ(1u, ranges[0].first);
  811. EXPECT_EQ(10u, ranges[0].second);
  812. }
  813. {
  814. Ranges ranges;
  815. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  816. EXPECT_FALSE(ret);
  817. }
  818. {
  819. Ranges ranges;
  820. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  821. EXPECT_TRUE(ret);
  822. EXPECT_EQ(2u, ranges.size());
  823. EXPECT_EQ(1u, ranges[0].first);
  824. EXPECT_EQ(10u, ranges[0].second);
  825. EXPECT_EQ(100u, ranges[1].first);
  826. EXPECT_EQ(-1, ranges[1].second);
  827. }
  828. {
  829. Ranges ranges;
  830. auto ret =
  831. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  832. EXPECT_TRUE(ret);
  833. EXPECT_EQ(3u, ranges.size());
  834. EXPECT_EQ(1u, ranges[0].first);
  835. EXPECT_EQ(10u, ranges[0].second);
  836. EXPECT_EQ(100u, ranges[1].first);
  837. EXPECT_EQ(200u, ranges[1].second);
  838. EXPECT_EQ(300u, ranges[2].first);
  839. EXPECT_EQ(400u, ranges[2].second);
  840. }
  841. {
  842. Ranges ranges;
  843. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  844. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  856. EXPECT_TRUE(ranges.empty());
  857. }
  858. }
  859. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  860. Request req;
  861. req.set_header("Accept-Encoding", "gzip");
  862. Response res;
  863. res.set_header("Content-Type", "text/plain");
  864. auto ret = detail::encoding_type(req, res);
  865. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  866. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  867. #else
  868. EXPECT_TRUE(ret == detail::EncodingType::None);
  869. #endif
  870. }
  871. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  872. Request req;
  873. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  874. Response res;
  875. res.set_header("Content-Type", "text/plain");
  876. auto ret = detail::encoding_type(req, res);
  877. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  878. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  879. #elif CPPHTTPLIB_ZLIB_SUPPORT
  880. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  881. #elif CPPHTTPLIB_ZSTD_SUPPORT
  882. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  883. #else
  884. EXPECT_TRUE(ret == detail::EncodingType::None);
  885. #endif
  886. }
  887. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  888. Request req;
  889. req.set_header("Accept-Encoding",
  890. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  891. Response res;
  892. res.set_header("Content-Type", "text/plain");
  893. auto ret = detail::encoding_type(req, res);
  894. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  895. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  896. #elif CPPHTTPLIB_ZLIB_SUPPORT
  897. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  898. #elif CPPHTTPLIB_ZSTD_SUPPORT
  899. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  900. #else
  901. EXPECT_TRUE(ret == detail::EncodingType::None);
  902. #endif
  903. }
  904. TEST(BufferStreamTest, read) {
  905. detail::BufferStream strm1;
  906. Stream &strm = strm1;
  907. EXPECT_EQ(5, strm.write("hello"));
  908. char buf[512];
  909. EXPECT_EQ(2, strm.read(buf, 2));
  910. EXPECT_EQ('h', buf[0]);
  911. EXPECT_EQ('e', buf[1]);
  912. EXPECT_EQ(2, strm.read(buf, 2));
  913. EXPECT_EQ('l', buf[0]);
  914. EXPECT_EQ('l', buf[1]);
  915. EXPECT_EQ(1, strm.read(buf, 1));
  916. EXPECT_EQ('o', buf[0]);
  917. EXPECT_EQ(0, strm.read(buf, 1));
  918. }
  919. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  920. auto host = "www.httpwatch.com";
  921. auto ip = hosted_at(host);
  922. EXPECT_EQ("23.96.13.243", ip);
  923. std::vector<std::string> addrs;
  924. hosted_at(host, addrs);
  925. EXPECT_EQ(1u, addrs.size());
  926. }
  927. #if 0 // It depends on each test environment...
  928. TEST(HostnameToIPConversionTest, YouTube_Online) {
  929. auto host = "www.youtube.com";
  930. std::vector<std::string> addrs;
  931. hosted_at(host, addrs);
  932. EXPECT_EQ(20u, addrs.size());
  933. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  934. EXPECT_TRUE(it != addrs.end());
  935. }
  936. #endif
  937. class ChunkedEncodingTest : public ::testing::Test {
  938. protected:
  939. ChunkedEncodingTest()
  940. : cli_(HOST, PORT)
  941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  942. ,
  943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  944. #endif
  945. {
  946. cli_.set_connection_timeout(2);
  947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  948. cli_.enable_server_certificate_verification(false);
  949. #endif
  950. }
  951. virtual void SetUp() {
  952. read_file("./image.jpg", image_data_);
  953. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  954. res.set_content("Hello World!", "text/plain");
  955. });
  956. svr_.Get(
  957. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  958. res.set_chunked_content_provider(
  959. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  960. size_t remaining = image_data_.size() - offset;
  961. if (remaining == 0) {
  962. sink.done();
  963. } else {
  964. constexpr size_t CHUNK_SIZE = 1024;
  965. size_t send_size = std::min(CHUNK_SIZE, remaining);
  966. sink.write(&image_data_[offset], send_size);
  967. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  968. }
  969. return true;
  970. });
  971. });
  972. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  973. svr_.wait_until_ready();
  974. }
  975. virtual void TearDown() {
  976. svr_.stop();
  977. if (!request_threads_.empty()) {
  978. std::this_thread::sleep_for(std::chrono::seconds(1));
  979. for (auto &t : request_threads_) {
  980. t.join();
  981. }
  982. }
  983. t_.join();
  984. }
  985. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  986. SSLClient cli_;
  987. SSLServer svr_;
  988. #else
  989. Client cli_;
  990. Server svr_;
  991. #endif
  992. thread t_;
  993. std::vector<thread> request_threads_;
  994. std::string image_data_;
  995. };
  996. TEST_F(ChunkedEncodingTest, NormalGet) {
  997. auto res = cli_.Get("/chunked");
  998. ASSERT_TRUE(res);
  999. std::string out;
  1000. read_file("./image.jpg", out);
  1001. EXPECT_EQ(StatusCode::OK_200, res->status);
  1002. EXPECT_EQ(out, res->body);
  1003. }
  1004. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1005. std::string body;
  1006. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1007. body.append(data, data_length);
  1008. return true;
  1009. });
  1010. ASSERT_TRUE(res);
  1011. std::string out;
  1012. read_file("./image.jpg", out);
  1013. EXPECT_EQ(StatusCode::OK_200, res->status);
  1014. EXPECT_EQ(out, body);
  1015. }
  1016. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1017. std::string body;
  1018. auto res = cli_.Get(
  1019. "/chunked",
  1020. [&](const Response &response) {
  1021. EXPECT_EQ(StatusCode::OK_200, response.status);
  1022. return true;
  1023. },
  1024. [&](const char *data, size_t data_length) {
  1025. body.append(data, data_length);
  1026. return true;
  1027. });
  1028. ASSERT_TRUE(res);
  1029. std::string out;
  1030. read_file("./image.jpg", out);
  1031. EXPECT_EQ(StatusCode::OK_200, res->status);
  1032. EXPECT_EQ(out, body);
  1033. }
  1034. TEST(RangeTest, FromHTTPBin_Online) {
  1035. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1036. auto host = "httpbin.org";
  1037. auto path = std::string{"/range/32"};
  1038. #else
  1039. auto host = "nghttp2.org";
  1040. auto path = std::string{"/httpbin/range/32"};
  1041. #endif
  1042. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1043. auto port = 443;
  1044. SSLClient cli(host, port);
  1045. #else
  1046. auto port = 80;
  1047. Client cli(host, port);
  1048. #endif
  1049. cli.set_connection_timeout(5);
  1050. {
  1051. auto res = cli.Get(path);
  1052. ASSERT_TRUE(res);
  1053. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1054. EXPECT_EQ(StatusCode::OK_200, res->status);
  1055. }
  1056. {
  1057. Headers headers = {make_range_header({{1, -1}})};
  1058. auto res = cli.Get(path, headers);
  1059. ASSERT_TRUE(res);
  1060. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1062. }
  1063. {
  1064. Headers headers = {make_range_header({{1, 10}})};
  1065. auto res = cli.Get(path, headers);
  1066. ASSERT_TRUE(res);
  1067. EXPECT_EQ("bcdefghijk", res->body);
  1068. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1069. }
  1070. {
  1071. Headers headers = {make_range_header({{0, 31}})};
  1072. auto res = cli.Get(path, headers);
  1073. ASSERT_TRUE(res);
  1074. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1075. EXPECT_EQ(StatusCode::OK_200, res->status);
  1076. }
  1077. {
  1078. Headers headers = {make_range_header({{0, -1}})};
  1079. auto res = cli.Get(path, headers);
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1082. EXPECT_EQ(StatusCode::OK_200, res->status);
  1083. }
  1084. {
  1085. Headers headers = {make_range_header({{0, 32}})};
  1086. auto res = cli.Get(path, headers);
  1087. ASSERT_TRUE(res);
  1088. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1089. }
  1090. }
  1091. TEST(ConnectionErrorTest, InvalidHost) {
  1092. auto host = "-abcde.com";
  1093. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1094. auto port = 443;
  1095. SSLClient cli(host, port);
  1096. #else
  1097. auto port = 80;
  1098. Client cli(host, port);
  1099. #endif
  1100. cli.set_connection_timeout(std::chrono::seconds(2));
  1101. auto res = cli.Get("/");
  1102. ASSERT_TRUE(!res);
  1103. EXPECT_EQ(Error::Connection, res.error());
  1104. }
  1105. TEST(ConnectionErrorTest, InvalidHost2) {
  1106. auto host = "httpbin.org/";
  1107. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1108. SSLClient cli(host);
  1109. #else
  1110. Client cli(host);
  1111. #endif
  1112. cli.set_connection_timeout(std::chrono::seconds(2));
  1113. auto res = cli.Get("/");
  1114. ASSERT_TRUE(!res);
  1115. EXPECT_EQ(Error::Connection, res.error());
  1116. }
  1117. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1118. auto host = "httpbin.org/";
  1119. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1120. SSLClient cli(host);
  1121. #else
  1122. Client cli(host);
  1123. #endif
  1124. cli.set_connection_timeout(std::chrono::seconds(2));
  1125. auto res = cli.Get("/");
  1126. ASSERT_TRUE(!res);
  1127. stringstream s;
  1128. s << "error code: " << res.error();
  1129. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1130. }
  1131. TEST(ConnectionErrorTest, InvalidPort) {
  1132. auto host = "localhost";
  1133. auto port = 44380;
  1134. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1135. SSLClient cli(host, port);
  1136. #else
  1137. Client cli(host, port);
  1138. #endif
  1139. cli.set_connection_timeout(std::chrono::seconds(2));
  1140. auto res = cli.Get("/");
  1141. ASSERT_TRUE(!res);
  1142. EXPECT_TRUE(Error::Connection == res.error() ||
  1143. Error::ConnectionTimeout == res.error());
  1144. }
  1145. TEST(ConnectionErrorTest, Timeout_Online) {
  1146. auto host = "google.com";
  1147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1148. auto port = 44380;
  1149. SSLClient cli(host, port);
  1150. #else
  1151. auto port = 8080;
  1152. Client cli(host, port);
  1153. #endif
  1154. cli.set_connection_timeout(std::chrono::seconds(2));
  1155. // only probe one address type so that the error reason
  1156. // correlates to the timed-out IPv4, not the unsupported
  1157. // IPv6 connection attempt
  1158. cli.set_address_family(AF_INET);
  1159. auto res = cli.Get("/");
  1160. ASSERT_TRUE(!res);
  1161. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1162. }
  1163. TEST(CancelTest, NoCancel_Online) {
  1164. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1165. auto host = "httpbin.org";
  1166. auto path = std::string{"/range/32"};
  1167. #else
  1168. auto host = "nghttp2.org";
  1169. auto path = std::string{"/httpbin/range/32"};
  1170. #endif
  1171. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1172. auto port = 443;
  1173. SSLClient cli(host, port);
  1174. #else
  1175. auto port = 80;
  1176. Client cli(host, port);
  1177. #endif
  1178. cli.set_connection_timeout(std::chrono::seconds(5));
  1179. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1180. ASSERT_TRUE(res);
  1181. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1182. EXPECT_EQ(StatusCode::OK_200, res->status);
  1183. }
  1184. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1185. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1186. auto host = "httpbin.org";
  1187. auto path = std::string{"/range/32"};
  1188. #else
  1189. auto host = "nghttp2.org";
  1190. auto path = std::string{"/httpbin/range/32"};
  1191. #endif
  1192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1193. auto port = 443;
  1194. SSLClient cli(host, port);
  1195. #else
  1196. auto port = 80;
  1197. Client cli(host, port);
  1198. #endif
  1199. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1200. cli.set_connection_timeout(std::chrono::seconds(5));
  1201. ASSERT_TRUE(!res);
  1202. EXPECT_EQ(Error::Canceled, res.error());
  1203. }
  1204. TEST(CancelTest, WithCancelLargePayload_Online) {
  1205. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1206. auto host = "httpbin.org";
  1207. auto path = std::string{"/range/65536"};
  1208. #else
  1209. auto host = "nghttp2.org";
  1210. auto path = std::string{"/httpbin/range/65536"};
  1211. #endif
  1212. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1213. auto port = 443;
  1214. SSLClient cli(host, port);
  1215. #else
  1216. auto port = 80;
  1217. Client cli(host, port);
  1218. #endif
  1219. cli.set_connection_timeout(std::chrono::seconds(5));
  1220. uint32_t count = 0;
  1221. auto res =
  1222. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1223. ASSERT_TRUE(!res);
  1224. EXPECT_EQ(Error::Canceled, res.error());
  1225. }
  1226. TEST(CancelTest, NoCancelPost) {
  1227. Server svr;
  1228. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1229. res.set_content("Hello World!", "text/plain");
  1230. });
  1231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1232. auto se = detail::scope_exit([&] {
  1233. svr.stop();
  1234. thread.join();
  1235. ASSERT_FALSE(svr.is_running());
  1236. });
  1237. svr.wait_until_ready();
  1238. Client cli(HOST, PORT);
  1239. cli.set_connection_timeout(std::chrono::seconds(5));
  1240. auto res =
  1241. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1242. "application/json", [](uint64_t, uint64_t) { return true; });
  1243. ASSERT_TRUE(res);
  1244. EXPECT_EQ("Hello World!", res->body);
  1245. EXPECT_EQ(StatusCode::OK_200, res->status);
  1246. }
  1247. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1248. Server svr;
  1249. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1250. res.set_content("Hello World!", "text/plain");
  1251. });
  1252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1253. auto se = detail::scope_exit([&] {
  1254. svr.stop();
  1255. thread.join();
  1256. ASSERT_FALSE(svr.is_running());
  1257. });
  1258. svr.wait_until_ready();
  1259. Client cli(HOST, PORT);
  1260. cli.set_connection_timeout(std::chrono::seconds(5));
  1261. auto res =
  1262. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1263. "application/json", [](uint64_t, uint64_t) { return false; });
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::Canceled, res.error());
  1266. }
  1267. TEST(CancelTest, WithCancelLargePayloadPost) {
  1268. Server svr;
  1269. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1270. res.set_content(LARGE_DATA, "text/plain");
  1271. });
  1272. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1273. auto se = detail::scope_exit([&] {
  1274. svr.stop();
  1275. thread.join();
  1276. ASSERT_FALSE(svr.is_running());
  1277. });
  1278. svr.wait_until_ready();
  1279. Client cli(HOST, PORT);
  1280. cli.set_connection_timeout(std::chrono::seconds(5));
  1281. auto res =
  1282. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1283. "application/json", [](uint64_t, uint64_t) { return false; });
  1284. ASSERT_TRUE(!res);
  1285. EXPECT_EQ(Error::Canceled, res.error());
  1286. }
  1287. TEST(CancelTest, NoCancelPut) {
  1288. Server svr;
  1289. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1290. res.set_content("Hello World!", "text/plain");
  1291. });
  1292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1293. auto se = detail::scope_exit([&] {
  1294. svr.stop();
  1295. thread.join();
  1296. ASSERT_FALSE(svr.is_running());
  1297. });
  1298. svr.wait_until_ready();
  1299. Client cli(HOST, PORT);
  1300. cli.set_connection_timeout(std::chrono::seconds(5));
  1301. auto res =
  1302. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1303. "application/json", [](uint64_t, uint64_t) { return true; });
  1304. ASSERT_TRUE(res);
  1305. EXPECT_EQ("Hello World!", res->body);
  1306. EXPECT_EQ(StatusCode::OK_200, res->status);
  1307. }
  1308. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1309. Server svr;
  1310. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1311. res.set_content("Hello World!", "text/plain");
  1312. });
  1313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1314. auto se = detail::scope_exit([&] {
  1315. svr.stop();
  1316. thread.join();
  1317. ASSERT_FALSE(svr.is_running());
  1318. });
  1319. svr.wait_until_ready();
  1320. Client cli(HOST, PORT);
  1321. cli.set_connection_timeout(std::chrono::seconds(5));
  1322. auto res =
  1323. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1324. "application/json", [](uint64_t, uint64_t) { return false; });
  1325. ASSERT_TRUE(!res);
  1326. EXPECT_EQ(Error::Canceled, res.error());
  1327. }
  1328. TEST(CancelTest, WithCancelLargePayloadPut) {
  1329. Server svr;
  1330. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1331. res.set_content(LARGE_DATA, "text/plain");
  1332. });
  1333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1334. auto se = detail::scope_exit([&] {
  1335. svr.stop();
  1336. thread.join();
  1337. ASSERT_FALSE(svr.is_running());
  1338. });
  1339. svr.wait_until_ready();
  1340. Client cli(HOST, PORT);
  1341. cli.set_connection_timeout(std::chrono::seconds(5));
  1342. auto res =
  1343. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1344. "application/json", [](uint64_t, uint64_t) { return false; });
  1345. ASSERT_TRUE(!res);
  1346. EXPECT_EQ(Error::Canceled, res.error());
  1347. }
  1348. TEST(CancelTest, NoCancelPatch) {
  1349. Server svr;
  1350. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1351. res.set_content("Hello World!", "text/plain");
  1352. });
  1353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1354. auto se = detail::scope_exit([&] {
  1355. svr.stop();
  1356. thread.join();
  1357. ASSERT_FALSE(svr.is_running());
  1358. });
  1359. svr.wait_until_ready();
  1360. Client cli(HOST, PORT);
  1361. cli.set_connection_timeout(std::chrono::seconds(5));
  1362. auto res =
  1363. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1364. "application/json", [](uint64_t, uint64_t) { return true; });
  1365. ASSERT_TRUE(res);
  1366. EXPECT_EQ("Hello World!", res->body);
  1367. EXPECT_EQ(StatusCode::OK_200, res->status);
  1368. }
  1369. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1370. Server svr;
  1371. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1372. res.set_content("Hello World!", "text/plain");
  1373. });
  1374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1375. auto se = detail::scope_exit([&] {
  1376. svr.stop();
  1377. thread.join();
  1378. ASSERT_FALSE(svr.is_running());
  1379. });
  1380. svr.wait_until_ready();
  1381. Client cli(HOST, PORT);
  1382. cli.set_connection_timeout(std::chrono::seconds(5));
  1383. auto res =
  1384. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1385. "application/json", [](uint64_t, uint64_t) { return false; });
  1386. ASSERT_TRUE(!res);
  1387. EXPECT_EQ(Error::Canceled, res.error());
  1388. }
  1389. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1390. Server svr;
  1391. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1392. res.set_content(LARGE_DATA, "text/plain");
  1393. });
  1394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1395. auto se = detail::scope_exit([&] {
  1396. svr.stop();
  1397. thread.join();
  1398. ASSERT_FALSE(svr.is_running());
  1399. });
  1400. svr.wait_until_ready();
  1401. Client cli(HOST, PORT);
  1402. cli.set_connection_timeout(std::chrono::seconds(5));
  1403. auto res =
  1404. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1405. "application/json", [](uint64_t, uint64_t) { return false; });
  1406. ASSERT_TRUE(!res);
  1407. EXPECT_EQ(Error::Canceled, res.error());
  1408. }
  1409. TEST(CancelTest, NoCancelDelete) {
  1410. Server svr;
  1411. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1412. res.set_content("Hello World!", "text/plain");
  1413. });
  1414. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1415. auto se = detail::scope_exit([&] {
  1416. svr.stop();
  1417. thread.join();
  1418. ASSERT_FALSE(svr.is_running());
  1419. });
  1420. svr.wait_until_ready();
  1421. Client cli(HOST, PORT);
  1422. cli.set_connection_timeout(std::chrono::seconds(5));
  1423. auto res =
  1424. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1425. "application/json", [](uint64_t, uint64_t) { return true; });
  1426. ASSERT_TRUE(res);
  1427. EXPECT_EQ("Hello World!", res->body);
  1428. EXPECT_EQ(StatusCode::OK_200, res->status);
  1429. }
  1430. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1431. Server svr;
  1432. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1433. res.set_content("Hello World!", "text/plain");
  1434. });
  1435. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1436. auto se = detail::scope_exit([&] {
  1437. svr.stop();
  1438. thread.join();
  1439. ASSERT_FALSE(svr.is_running());
  1440. });
  1441. svr.wait_until_ready();
  1442. Client cli(HOST, PORT);
  1443. cli.set_connection_timeout(std::chrono::seconds(5));
  1444. auto res =
  1445. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1446. "application/json", [](uint64_t, uint64_t) { return false; });
  1447. ASSERT_TRUE(!res);
  1448. EXPECT_EQ(Error::Canceled, res.error());
  1449. }
  1450. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1451. Server svr;
  1452. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1453. res.set_content(LARGE_DATA, "text/plain");
  1454. });
  1455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. thread.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. Client cli(HOST, PORT);
  1463. cli.set_connection_timeout(std::chrono::seconds(5));
  1464. auto res =
  1465. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1466. "application/json", [](uint64_t, uint64_t) { return false; });
  1467. ASSERT_TRUE(!res);
  1468. EXPECT_EQ(Error::Canceled, res.error());
  1469. }
  1470. static std::string remove_whitespace(const std::string &input) {
  1471. std::string output;
  1472. output.reserve(input.size());
  1473. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1474. [](unsigned char c) { return !std::isspace(c); });
  1475. return output;
  1476. }
  1477. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1478. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1479. auto host = "httpbin.org";
  1480. auto path = std::string{"/basic-auth/hello/world"};
  1481. #else
  1482. auto host = "nghttp2.org";
  1483. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1484. #endif
  1485. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1486. auto port = 443;
  1487. SSLClient cli(host, port);
  1488. #else
  1489. auto port = 80;
  1490. Client cli(host, port);
  1491. #endif
  1492. {
  1493. auto res = cli.Get(path);
  1494. ASSERT_TRUE(res);
  1495. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1496. }
  1497. {
  1498. auto res =
  1499. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1502. remove_whitespace(res->body));
  1503. EXPECT_EQ(StatusCode::OK_200, res->status);
  1504. }
  1505. {
  1506. cli.set_basic_auth("hello", "world");
  1507. auto res = cli.Get(path);
  1508. ASSERT_TRUE(res);
  1509. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1510. remove_whitespace(res->body));
  1511. EXPECT_EQ(StatusCode::OK_200, res->status);
  1512. }
  1513. {
  1514. cli.set_basic_auth("hello", "bad");
  1515. auto res = cli.Get(path);
  1516. ASSERT_TRUE(res);
  1517. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1518. }
  1519. {
  1520. cli.set_basic_auth("bad", "world");
  1521. auto res = cli.Get(path);
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1524. }
  1525. }
  1526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1527. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1528. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1529. auto host = "httpbin.org";
  1530. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1531. auto paths = std::vector<std::string>{
  1532. "/digest-auth/auth/hello/world/MD5",
  1533. "/digest-auth/auth/hello/world/SHA-256",
  1534. "/digest-auth/auth/hello/world/SHA-512",
  1535. "/digest-auth/auth-int/hello/world/MD5",
  1536. };
  1537. #else
  1538. auto host = "nghttp2.org";
  1539. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1540. auto paths = std::vector<std::string>{
  1541. "/httpbin/digest-auth/auth/hello/world/MD5",
  1542. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1543. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1544. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1545. };
  1546. #endif
  1547. auto port = 443;
  1548. SSLClient cli(host, port);
  1549. {
  1550. auto res = cli.Get(unauth_path);
  1551. ASSERT_TRUE(res);
  1552. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1553. }
  1554. {
  1555. cli.set_digest_auth("hello", "world");
  1556. for (const auto &path : paths) {
  1557. auto res = cli.Get(path.c_str());
  1558. ASSERT_TRUE(res);
  1559. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1560. remove_whitespace(res->body));
  1561. EXPECT_EQ(StatusCode::OK_200, res->status);
  1562. }
  1563. cli.set_digest_auth("hello", "bad");
  1564. for (const auto &path : paths) {
  1565. auto res = cli.Get(path.c_str());
  1566. ASSERT_TRUE(res);
  1567. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1568. }
  1569. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1570. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1571. // cli.set_digest_auth("bad", "world");
  1572. // for (const auto& path : paths) {
  1573. // auto res = cli.Get(path.c_str());
  1574. // ASSERT_TRUE(res);
  1575. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1576. // }
  1577. }
  1578. }
  1579. #endif
  1580. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1581. auto host = "google.com";
  1582. auto another_host = "example.com";
  1583. auto wrong_ip = "0.0.0.0";
  1584. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1585. SSLClient cli(host);
  1586. #else
  1587. Client cli(host);
  1588. #endif
  1589. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1590. auto res = cli.Get("/");
  1591. ASSERT_TRUE(res);
  1592. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1593. }
  1594. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1595. auto host = "google.com";
  1596. auto wrong_ip = "0.0.0.0";
  1597. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1598. SSLClient cli(host);
  1599. #else
  1600. Client cli(host);
  1601. #endif
  1602. cli.set_hostname_addr_map({{host, wrong_ip}});
  1603. auto res = cli.Get("/");
  1604. ASSERT_TRUE(!res);
  1605. EXPECT_EQ(Error::Connection, res.error());
  1606. }
  1607. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1608. auto host = "nghttp2.org";
  1609. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1610. SSLClient cli(host);
  1611. #else
  1612. Client cli(host);
  1613. #endif
  1614. cli.set_follow_location(true);
  1615. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1616. ASSERT_TRUE(res);
  1617. EXPECT_EQ(StatusCode::OK_200, res->status);
  1618. }
  1619. TEST(RedirectTest, Redirect_Online) {
  1620. auto host = "nghttp2.org";
  1621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1622. SSLClient cli(host);
  1623. #else
  1624. Client cli(host);
  1625. #endif
  1626. cli.set_follow_location(true);
  1627. auto res = cli.Get("/httpbin/redirect/3");
  1628. ASSERT_TRUE(res);
  1629. EXPECT_EQ(StatusCode::OK_200, res->status);
  1630. }
  1631. TEST(RelativeRedirectTest, Redirect_Online) {
  1632. auto host = "nghttp2.org";
  1633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1634. SSLClient cli(host);
  1635. #else
  1636. Client cli(host);
  1637. #endif
  1638. cli.set_follow_location(true);
  1639. auto res = cli.Get("/httpbin/relative-redirect/3");
  1640. ASSERT_TRUE(res);
  1641. EXPECT_EQ(StatusCode::OK_200, res->status);
  1642. }
  1643. TEST(TooManyRedirectTest, Redirect_Online) {
  1644. auto host = "nghttp2.org";
  1645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1646. SSLClient cli(host);
  1647. #else
  1648. Client cli(host);
  1649. #endif
  1650. cli.set_follow_location(true);
  1651. auto res = cli.Get("/httpbin/redirect/21");
  1652. ASSERT_TRUE(!res);
  1653. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1654. }
  1655. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1656. TEST(YahooRedirectTest, Redirect_Online) {
  1657. Client cli("yahoo.com");
  1658. auto res = cli.Get("/");
  1659. ASSERT_TRUE(res);
  1660. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1661. cli.set_follow_location(true);
  1662. res = cli.Get("/");
  1663. ASSERT_TRUE(res);
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1666. }
  1667. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1668. #define REDIR_HOST "httpbingo.org"
  1669. #define REDIR_PATH "/redirect-to"
  1670. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1671. SSLClient cli(REDIR_HOST);
  1672. cli.set_follow_location(true);
  1673. auto res =
  1674. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1675. ASSERT_TRUE(res);
  1676. EXPECT_EQ(StatusCode::OK_200, res->status);
  1677. }
  1678. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1679. SSLClient cli(REDIR_HOST);
  1680. cli.set_follow_location(true);
  1681. Params params;
  1682. params.emplace("url", "http://example.com");
  1683. params.emplace("status_code", "302");
  1684. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1689. SSLClient cli(REDIR_HOST);
  1690. cli.set_follow_location(true);
  1691. Params params;
  1692. params.emplace("url", "http://example.com");
  1693. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1694. ASSERT_TRUE(res);
  1695. EXPECT_EQ(StatusCode::OK_200, res->status);
  1696. }
  1697. TEST(UrlWithSpace, Redirect_Online) {
  1698. SSLClient cli("edge.forgecdn.net");
  1699. cli.set_follow_location(true);
  1700. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1701. ASSERT_TRUE(res);
  1702. EXPECT_EQ(StatusCode::OK_200, res->status);
  1703. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1704. }
  1705. #endif
  1706. #if !defined(_WIN32) && !defined(_WIN64)
  1707. TEST(ReceiveSignals, Signal) {
  1708. auto setupSignalHandlers = []() {
  1709. struct sigaction act;
  1710. sigemptyset(&act.sa_mask);
  1711. act.sa_flags = SA_SIGINFO;
  1712. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1713. switch (sig) {
  1714. case SIGINT:
  1715. default: break;
  1716. }
  1717. };
  1718. ::sigaction(SIGINT, &act, nullptr);
  1719. };
  1720. Server svr;
  1721. int port = 0;
  1722. auto thread = std::thread([&]() {
  1723. setupSignalHandlers();
  1724. port = svr.bind_to_any_port("localhost");
  1725. svr.listen_after_bind();
  1726. });
  1727. auto se = detail::scope_exit([&] {
  1728. svr.stop();
  1729. thread.join();
  1730. ASSERT_FALSE(svr.is_running());
  1731. });
  1732. svr.wait_until_ready();
  1733. ASSERT_TRUE(svr.is_running());
  1734. pthread_kill(thread.native_handle(), SIGINT);
  1735. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1736. ASSERT_TRUE(svr.is_running());
  1737. }
  1738. #endif
  1739. TEST(RedirectToDifferentPort, Redirect) {
  1740. Server svr1;
  1741. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1742. res.set_content("Hello World!", "text/plain");
  1743. });
  1744. int svr1_port = 0;
  1745. auto thread1 = std::thread([&]() {
  1746. svr1_port = svr1.bind_to_any_port("localhost");
  1747. svr1.listen_after_bind();
  1748. });
  1749. Server svr2;
  1750. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1751. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1752. });
  1753. int svr2_port = 0;
  1754. auto thread2 = std::thread([&]() {
  1755. svr2_port = svr2.bind_to_any_port("localhost");
  1756. svr2.listen_after_bind();
  1757. });
  1758. auto se = detail::scope_exit([&] {
  1759. svr2.stop();
  1760. thread2.join();
  1761. svr1.stop();
  1762. thread1.join();
  1763. ASSERT_FALSE(svr2.is_running());
  1764. ASSERT_FALSE(svr1.is_running());
  1765. });
  1766. svr1.wait_until_ready();
  1767. svr2.wait_until_ready();
  1768. Client cli("localhost", svr2_port);
  1769. cli.set_follow_location(true);
  1770. auto res = cli.Get("/2");
  1771. ASSERT_TRUE(res);
  1772. EXPECT_EQ(StatusCode::OK_200, res->status);
  1773. EXPECT_EQ("Hello World!", res->body);
  1774. }
  1775. TEST(RedirectFromPageWithContent, Redirect) {
  1776. Server svr;
  1777. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1778. res.set_content("___", "text/plain");
  1779. res.set_redirect("/2");
  1780. });
  1781. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1782. res.set_content("Hello World!", "text/plain");
  1783. });
  1784. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1785. auto se = detail::scope_exit([&] {
  1786. svr.stop();
  1787. th.join();
  1788. ASSERT_FALSE(svr.is_running());
  1789. });
  1790. svr.wait_until_ready();
  1791. {
  1792. Client cli("localhost", PORT);
  1793. cli.set_follow_location(true);
  1794. std::string body;
  1795. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1796. body.append(data, data_length);
  1797. return true;
  1798. });
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. EXPECT_EQ("Hello World!", body);
  1802. }
  1803. {
  1804. Client cli("localhost", PORT);
  1805. std::string body;
  1806. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1807. body.append(data, data_length);
  1808. return true;
  1809. });
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::Found_302, res->status);
  1812. EXPECT_EQ("___", body);
  1813. }
  1814. }
  1815. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1816. Server svr;
  1817. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1818. res.set_content("___", "text/plain");
  1819. // res.set_redirect("/2");
  1820. res.set_redirect("http://[::1]:1234/2");
  1821. });
  1822. svr.Get("/2", [&](const Request &req, Response &res) {
  1823. auto host_header = req.headers.find("Host");
  1824. ASSERT_TRUE(host_header != req.headers.end());
  1825. EXPECT_EQ("[::1]:1234", host_header->second);
  1826. res.set_content("Hello World!", "text/plain");
  1827. });
  1828. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1829. auto se = detail::scope_exit([&] {
  1830. svr.stop();
  1831. th.join();
  1832. ASSERT_FALSE(svr.is_running());
  1833. });
  1834. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1835. // actually starts anything, so the condition !svr.is_running() will
  1836. // always remain true, and the loop never stops.
  1837. // This basically counts how many milliseconds have passed since the
  1838. // call to svr.listen(), and if after 5 seconds nothing started yet
  1839. // aborts the test.
  1840. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1841. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1842. ASSERT_LT(milliseconds, 5000U);
  1843. }
  1844. {
  1845. Client cli("http://[::1]:1234");
  1846. cli.set_follow_location(true);
  1847. std::string body;
  1848. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1849. body.append(data, data_length);
  1850. return true;
  1851. });
  1852. ASSERT_TRUE(res);
  1853. EXPECT_EQ(StatusCode::OK_200, res->status);
  1854. EXPECT_EQ("Hello World!", body);
  1855. }
  1856. {
  1857. Client cli("http://[::1]:1234");
  1858. std::string body;
  1859. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1860. body.append(data, data_length);
  1861. return true;
  1862. });
  1863. ASSERT_TRUE(res);
  1864. EXPECT_EQ(StatusCode::Found_302, res->status);
  1865. EXPECT_EQ("___", body);
  1866. }
  1867. }
  1868. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1869. Server svr;
  1870. svr.Get("/foo", [](const Request &req, Response &res) {
  1871. auto a = req.params.find("a");
  1872. if (a != req.params.end()) {
  1873. res.set_content((*a).second, "text/plain");
  1874. res.status = StatusCode::OK_200;
  1875. } else {
  1876. res.status = StatusCode::BadRequest_400;
  1877. }
  1878. });
  1879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1880. auto se = detail::scope_exit([&] {
  1881. svr.stop();
  1882. thread.join();
  1883. ASSERT_FALSE(svr.is_running());
  1884. });
  1885. svr.wait_until_ready();
  1886. {
  1887. Client cli(HOST, PORT);
  1888. cli.set_path_encode(false);
  1889. auto res = cli.Get("/foo?a=explicitly+encoded");
  1890. ASSERT_TRUE(res);
  1891. EXPECT_EQ(StatusCode::OK_200, res->status);
  1892. // This expects it back with a space, as the `+` won't have been
  1893. // url-encoded, and server-side the params get decoded turning `+`
  1894. // into spaces.
  1895. EXPECT_EQ("explicitly encoded", res->body);
  1896. }
  1897. }
  1898. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1899. Server svr;
  1900. svr.Get("/", [](const Request &req, Response &) {
  1901. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1902. });
  1903. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1904. auto se = detail::scope_exit([&] {
  1905. svr.stop();
  1906. thread.join();
  1907. ASSERT_FALSE(svr.is_running());
  1908. });
  1909. svr.wait_until_ready();
  1910. {
  1911. Client cli(HOST, PORT);
  1912. cli.set_path_encode(false);
  1913. auto res = cli.Get("/?something=%0A");
  1914. ASSERT_TRUE(res);
  1915. EXPECT_EQ(StatusCode::OK_200, res->status);
  1916. }
  1917. }
  1918. TEST(BindServerTest, DISABLED_BindDualStack) {
  1919. Server svr;
  1920. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1921. res.set_content("Hello World!", "text/plain");
  1922. });
  1923. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1924. auto se = detail::scope_exit([&] {
  1925. svr.stop();
  1926. thread.join();
  1927. ASSERT_FALSE(svr.is_running());
  1928. });
  1929. svr.wait_until_ready();
  1930. {
  1931. Client cli("127.0.0.1", PORT);
  1932. auto res = cli.Get("/1");
  1933. ASSERT_TRUE(res);
  1934. EXPECT_EQ(StatusCode::OK_200, res->status);
  1935. EXPECT_EQ("Hello World!", res->body);
  1936. }
  1937. {
  1938. Client cli("::1", PORT);
  1939. auto res = cli.Get("/1");
  1940. ASSERT_TRUE(res);
  1941. EXPECT_EQ(StatusCode::OK_200, res->status);
  1942. EXPECT_EQ("Hello World!", res->body);
  1943. }
  1944. }
  1945. TEST(BindServerTest, BindAndListenSeparately) {
  1946. Server svr;
  1947. int port = svr.bind_to_any_port("0.0.0.0");
  1948. ASSERT_TRUE(svr.is_valid());
  1949. ASSERT_TRUE(port > 0);
  1950. svr.stop();
  1951. }
  1952. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1953. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1955. CLIENT_CA_CERT_DIR);
  1956. int port = svr.bind_to_any_port("0.0.0.0");
  1957. ASSERT_TRUE(svr.is_valid());
  1958. ASSERT_TRUE(port > 0);
  1959. svr.stop();
  1960. }
  1961. #endif
  1962. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1963. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1964. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1965. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1966. int port = svr.bind_to_any_port("0.0.0.0");
  1967. ASSERT_TRUE(svr.is_valid());
  1968. ASSERT_TRUE(port > 0);
  1969. svr.stop();
  1970. }
  1971. #endif
  1972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1973. X509 *readCertificate(const std::string &strFileName) {
  1974. std::ifstream inStream(strFileName);
  1975. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1976. std::istreambuf_iterator<char>());
  1977. if (strCertPEM.empty()) return (nullptr);
  1978. BIO *pbCert = BIO_new(BIO_s_mem());
  1979. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1980. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1981. BIO_free(pbCert);
  1982. return (pCert);
  1983. }
  1984. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1985. std::ifstream inStream(strFileName);
  1986. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1987. std::istreambuf_iterator<char>());
  1988. if (strPrivateKeyPEM.empty()) return (nullptr);
  1989. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1990. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1991. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1992. BIO_free(pbPrivKey);
  1993. return (pPrivateKey);
  1994. }
  1995. TEST(BindServerTest, UpdateCerts) {
  1996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1997. int port = svr.bind_to_any_port("0.0.0.0");
  1998. ASSERT_TRUE(svr.is_valid());
  1999. ASSERT_TRUE(port > 0);
  2000. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2001. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2002. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2003. ASSERT_TRUE(cert != nullptr);
  2004. ASSERT_TRUE(ca_cert != nullptr);
  2005. ASSERT_TRUE(key != nullptr);
  2006. X509_STORE *cert_store = X509_STORE_new();
  2007. X509_STORE_add_cert(cert_store, ca_cert);
  2008. svr.update_certs(cert, key, cert_store);
  2009. ASSERT_TRUE(svr.is_valid());
  2010. svr.stop();
  2011. X509_free(cert);
  2012. X509_free(ca_cert);
  2013. EVP_PKEY_free(key);
  2014. }
  2015. #endif
  2016. TEST(ErrorHandlerTest, ContentLength) {
  2017. Server svr;
  2018. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2019. res.status = StatusCode::OK_200;
  2020. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2021. "text/html"); // <= Content-Length still 13
  2022. });
  2023. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2024. res.set_content("Hello World!\n", "text/plain");
  2025. res.status = 524;
  2026. });
  2027. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2028. auto se = detail::scope_exit([&] {
  2029. svr.stop();
  2030. thread.join();
  2031. ASSERT_FALSE(svr.is_running());
  2032. });
  2033. svr.wait_until_ready();
  2034. {
  2035. Client cli(HOST, PORT);
  2036. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2042. }
  2043. }
  2044. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2045. TEST(ExceptionTest, WithoutExceptionHandler) {
  2046. Server svr;
  2047. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2048. throw std::runtime_error("exception...");
  2049. });
  2050. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2051. throw std::runtime_error("exception\r\n...");
  2052. });
  2053. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2054. auto se = detail::scope_exit([&] {
  2055. svr.stop();
  2056. listen_thread.join();
  2057. ASSERT_FALSE(svr.is_running());
  2058. });
  2059. svr.wait_until_ready();
  2060. Client cli("localhost", PORT);
  2061. {
  2062. auto res = cli.Get("/exception");
  2063. ASSERT_TRUE(res);
  2064. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2065. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2066. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2067. }
  2068. {
  2069. auto res = cli.Get("/unknown");
  2070. ASSERT_TRUE(res);
  2071. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2072. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2073. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2074. }
  2075. }
  2076. TEST(ExceptionTest, WithExceptionHandler) {
  2077. Server svr;
  2078. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2079. std::exception_ptr ep) {
  2080. EXPECT_FALSE(ep == nullptr);
  2081. try {
  2082. std::rethrow_exception(ep);
  2083. } catch (std::exception &e) {
  2084. EXPECT_EQ("abc", std::string(e.what()));
  2085. } catch (...) {}
  2086. res.status = StatusCode::InternalServerError_500;
  2087. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2088. "text/html"); // <= Content-Length still 13 at this point
  2089. });
  2090. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2091. res.set_content("Hello World!\n", "text/plain");
  2092. throw std::runtime_error("abc");
  2093. });
  2094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2095. auto se = detail::scope_exit([&] {
  2096. svr.stop();
  2097. thread.join();
  2098. ASSERT_FALSE(svr.is_running());
  2099. });
  2100. svr.wait_until_ready();
  2101. for (size_t i = 0; i < 10; i++) {
  2102. Client cli(HOST, PORT);
  2103. for (size_t j = 0; j < 100; j++) {
  2104. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2105. ASSERT_TRUE(res);
  2106. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2107. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2108. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2109. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2110. }
  2111. cli.set_keep_alive(true);
  2112. for (size_t j = 0; j < 100; j++) {
  2113. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2114. ASSERT_TRUE(res);
  2115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2118. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2119. }
  2120. }
  2121. }
  2122. TEST(ExceptionTest, AndErrorHandler) {
  2123. Server svr;
  2124. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2125. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2126. });
  2127. svr.set_exception_handler(
  2128. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2129. EXPECT_FALSE(ep == nullptr);
  2130. try {
  2131. std::rethrow_exception(ep);
  2132. } catch (std::exception &e) {
  2133. res.set_content(e.what(), "text/html");
  2134. } catch (...) {}
  2135. res.status = StatusCode::InternalServerError_500;
  2136. });
  2137. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2138. throw std::runtime_error("EXCEPTION");
  2139. });
  2140. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2141. res.set_content("ERROR", "text/html");
  2142. res.status = StatusCode::InternalServerError_500;
  2143. });
  2144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2145. auto se = detail::scope_exit([&] {
  2146. svr.stop();
  2147. thread.join();
  2148. ASSERT_FALSE(svr.is_running());
  2149. });
  2150. svr.wait_until_ready();
  2151. Client cli(HOST, PORT);
  2152. {
  2153. auto res = cli.Get("/exception");
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2156. EXPECT_EQ("EXCEPTION", res->body);
  2157. }
  2158. {
  2159. auto res = cli.Get("/error");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. EXPECT_EQ("ERROR", res->body);
  2163. }
  2164. {
  2165. auto res = cli.Get("/invalid");
  2166. ASSERT_TRUE(res);
  2167. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2168. EXPECT_EQ("NOT_FOUND", res->body);
  2169. }
  2170. }
  2171. #endif
  2172. TEST(NoContentTest, ContentLength) {
  2173. Server svr;
  2174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2175. res.status = StatusCode::NoContent_204;
  2176. });
  2177. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2178. auto se = detail::scope_exit([&] {
  2179. svr.stop();
  2180. thread.join();
  2181. ASSERT_FALSE(svr.is_running());
  2182. });
  2183. svr.wait_until_ready();
  2184. {
  2185. Client cli(HOST, PORT);
  2186. auto res = cli.Get("/hi");
  2187. ASSERT_TRUE(res);
  2188. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2189. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2190. }
  2191. }
  2192. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2193. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2195. ASSERT_TRUE(svr.is_valid());
  2196. #else
  2197. Server svr;
  2198. #endif
  2199. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2200. if (req.path == "/routing_handler") {
  2201. res.set_header("PRE_ROUTING", "on");
  2202. res.set_content("Routing Handler", "text/plain");
  2203. return httplib::Server::HandlerResponse::Handled;
  2204. }
  2205. return httplib::Server::HandlerResponse::Unhandled;
  2206. });
  2207. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2208. res.set_content("Error", "text/html");
  2209. });
  2210. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2211. if (req.path == "/routing_handler") {
  2212. res.set_header("POST_ROUTING", "on");
  2213. }
  2214. });
  2215. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2216. res.set_content("Hello World!\n", "text/plain");
  2217. });
  2218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2219. auto se = detail::scope_exit([&] {
  2220. svr.stop();
  2221. thread.join();
  2222. ASSERT_FALSE(svr.is_running());
  2223. });
  2224. svr.wait_until_ready();
  2225. {
  2226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2227. SSLClient cli(HOST, PORT);
  2228. cli.enable_server_certificate_verification(false);
  2229. #else
  2230. Client cli(HOST, PORT);
  2231. #endif
  2232. auto res = cli.Get("/routing_handler");
  2233. ASSERT_TRUE(res);
  2234. EXPECT_EQ(StatusCode::OK_200, res->status);
  2235. EXPECT_EQ("Routing Handler", res->body);
  2236. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2237. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2238. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2239. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2240. }
  2241. {
  2242. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2243. SSLClient cli(HOST, PORT);
  2244. cli.enable_server_certificate_verification(false);
  2245. #else
  2246. Client cli(HOST, PORT);
  2247. #endif
  2248. auto res = cli.Get("/hi");
  2249. ASSERT_TRUE(res);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ("Hello World!\n", res->body);
  2252. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2253. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2254. }
  2255. {
  2256. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2257. SSLClient cli(HOST, PORT);
  2258. cli.enable_server_certificate_verification(false);
  2259. #else
  2260. Client cli(HOST, PORT);
  2261. #endif
  2262. auto res = cli.Get("/aaa");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("Error", res->body);
  2266. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2267. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2268. }
  2269. }
  2270. TEST(RequestHandlerTest, PreRequestHandler) {
  2271. auto route_path = "/user/:user";
  2272. Server svr;
  2273. svr.Get("/hi", [](const Request &, Response &res) {
  2274. res.set_content("hi", "text/plain");
  2275. });
  2276. svr.Get(route_path, [](const Request &req, Response &res) {
  2277. res.set_content(req.path_params.at("user"), "text/plain");
  2278. });
  2279. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2280. if (req.matched_route == route_path) {
  2281. auto user = req.path_params.at("user");
  2282. if (user != "john") {
  2283. res.status = StatusCode::Forbidden_403;
  2284. res.set_content("error", "text/html");
  2285. return Server::HandlerResponse::Handled;
  2286. }
  2287. }
  2288. return Server::HandlerResponse::Unhandled;
  2289. });
  2290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2291. auto se = detail::scope_exit([&] {
  2292. svr.stop();
  2293. thread.join();
  2294. ASSERT_FALSE(svr.is_running());
  2295. });
  2296. svr.wait_until_ready();
  2297. Client cli(HOST, PORT);
  2298. {
  2299. auto res = cli.Get("/hi");
  2300. ASSERT_TRUE(res);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. EXPECT_EQ("hi", res->body);
  2303. }
  2304. {
  2305. auto res = cli.Get("/user/john");
  2306. ASSERT_TRUE(res);
  2307. EXPECT_EQ(StatusCode::OK_200, res->status);
  2308. EXPECT_EQ("john", res->body);
  2309. }
  2310. {
  2311. auto res = cli.Get("/user/invalid-user");
  2312. ASSERT_TRUE(res);
  2313. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2314. EXPECT_EQ("error", res->body);
  2315. }
  2316. }
  2317. TEST(InvalidFormatTest, StatusCode) {
  2318. Server svr;
  2319. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2320. res.set_content("Hello World!\n", "text/plain");
  2321. res.status = 9999; // Status should be a three-digit code...
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. Client cli(HOST, PORT);
  2332. auto res = cli.Get("/hi");
  2333. ASSERT_FALSE(res);
  2334. }
  2335. }
  2336. TEST(URLFragmentTest, WithFragment) {
  2337. Server svr;
  2338. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2339. EXPECT_TRUE(req.target == "/hi");
  2340. });
  2341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2342. auto se = detail::scope_exit([&] {
  2343. svr.stop();
  2344. thread.join();
  2345. ASSERT_FALSE(svr.is_running());
  2346. });
  2347. svr.wait_until_ready();
  2348. {
  2349. Client cli(HOST, PORT);
  2350. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2351. EXPECT_TRUE(res);
  2352. EXPECT_EQ(StatusCode::OK_200, res->status);
  2353. res = cli.Get("/hi%23key1=val1=key2=val2");
  2354. EXPECT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2356. }
  2357. }
  2358. TEST(HeaderWriter, SetHeaderWriter) {
  2359. Server svr;
  2360. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2361. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2362. return detail::write_headers(strm, hdrs);
  2363. });
  2364. svr.Get("/hi", [](const Request &req, Response &res) {
  2365. auto it = req.headers.find("CustomClientHeader");
  2366. EXPECT_TRUE(it != req.headers.end());
  2367. EXPECT_EQ(it->second, "CustomClientValue");
  2368. res.set_content("Hello World!\n", "text/plain");
  2369. });
  2370. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2371. auto se = detail::scope_exit([&] {
  2372. svr.stop();
  2373. thread.join();
  2374. ASSERT_FALSE(svr.is_running());
  2375. });
  2376. svr.wait_until_ready();
  2377. {
  2378. Client cli(HOST, PORT);
  2379. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2380. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2381. return detail::write_headers(strm, hdrs);
  2382. });
  2383. auto res = cli.Get("/hi");
  2384. EXPECT_TRUE(res);
  2385. EXPECT_EQ(StatusCode::OK_200, res->status);
  2386. auto it = res->headers.find("CustomServerHeader");
  2387. EXPECT_TRUE(it != res->headers.end());
  2388. EXPECT_EQ(it->second, "CustomServerValue");
  2389. }
  2390. }
  2391. class ServerTest : public ::testing::Test {
  2392. protected:
  2393. ServerTest()
  2394. : cli_(HOST, PORT)
  2395. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2396. ,
  2397. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2398. #endif
  2399. {
  2400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2401. cli_.enable_server_certificate_verification(false);
  2402. #endif
  2403. }
  2404. virtual void SetUp() {
  2405. svr_.set_mount_point("/", "./www");
  2406. svr_.set_mount_point("/mount", "./www2");
  2407. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2408. svr_.Get("/hi",
  2409. [&](const Request & /*req*/, Response &res) {
  2410. res.set_content("Hello World!", "text/plain");
  2411. })
  2412. .Get("/file_content",
  2413. [&](const Request & /*req*/, Response &res) {
  2414. res.set_file_content("./www/dir/test.html");
  2415. })
  2416. .Get("/file_content_with_content_type",
  2417. [&](const Request & /*req*/, Response &res) {
  2418. res.set_file_content("./www/file", "text/plain");
  2419. })
  2420. .Get("/invalid_file_content",
  2421. [&](const Request & /*req*/, Response &res) {
  2422. res.set_file_content("./www/dir/invalid_file_path");
  2423. })
  2424. .Get("/http_response_splitting",
  2425. [&](const Request & /*req*/, Response &res) {
  2426. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2427. EXPECT_EQ(0U, res.headers.size());
  2428. EXPECT_FALSE(res.has_header("a"));
  2429. res.set_header("a", "1\nSet-Cookie: a=1");
  2430. EXPECT_EQ(0U, res.headers.size());
  2431. EXPECT_FALSE(res.has_header("a"));
  2432. res.set_header("a", "1\rSet-Cookie: a=1");
  2433. EXPECT_EQ(0U, res.headers.size());
  2434. EXPECT_FALSE(res.has_header("a"));
  2435. res.set_header("a\r\nb", "0");
  2436. EXPECT_EQ(0U, res.headers.size());
  2437. EXPECT_FALSE(res.has_header("a"));
  2438. res.set_header("a\rb", "0");
  2439. EXPECT_EQ(0U, res.headers.size());
  2440. EXPECT_FALSE(res.has_header("a"));
  2441. res.set_header("a\nb", "0");
  2442. EXPECT_EQ(0U, res.headers.size());
  2443. EXPECT_FALSE(res.has_header("a"));
  2444. res.set_redirect("1\r\nSet-Cookie: a=1");
  2445. EXPECT_EQ(0U, res.headers.size());
  2446. EXPECT_FALSE(res.has_header("Location"));
  2447. })
  2448. .Get("/slow",
  2449. [&](const Request & /*req*/, Response &res) {
  2450. std::this_thread::sleep_for(std::chrono::seconds(2));
  2451. res.set_content("slow", "text/plain");
  2452. })
  2453. #if 0
  2454. .Post("/slowpost",
  2455. [&](const Request & /*req*/, Response &res) {
  2456. std::this_thread::sleep_for(std::chrono::seconds(2));
  2457. res.set_content("slow", "text/plain");
  2458. })
  2459. #endif
  2460. .Get("/remote_addr",
  2461. [&](const Request &req, Response &res) {
  2462. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2463. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2464. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2465. EXPECT_EQ(req.remote_port,
  2466. std::stoi(req.get_header_value("REMOTE_PORT")));
  2467. res.set_content(remote_addr.c_str(), "text/plain");
  2468. })
  2469. .Get("/local_addr",
  2470. [&](const Request &req, Response &res) {
  2471. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2472. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2473. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2474. auto local_port = req.get_header_value("LOCAL_PORT");
  2475. EXPECT_EQ(req.local_addr, local_addr);
  2476. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2477. res.set_content(local_addr.append(":").append(local_port),
  2478. "text/plain");
  2479. })
  2480. .Get("/endwith%",
  2481. [&](const Request & /*req*/, Response &res) {
  2482. res.set_content("Hello World!", "text/plain");
  2483. })
  2484. .Get("/a\\+\\+b",
  2485. [&](const Request &req, Response &res) {
  2486. ASSERT_TRUE(req.has_param("a +b"));
  2487. auto val = req.get_param_value("a +b");
  2488. res.set_content(val, "text/plain");
  2489. })
  2490. .Get("/", [&](const Request & /*req*/,
  2491. Response &res) { res.set_redirect("/hi"); })
  2492. .Post("/1",
  2493. [](const Request & /*req*/, Response &res) {
  2494. res.set_redirect("/2", StatusCode::SeeOther_303);
  2495. })
  2496. .Get("/2",
  2497. [](const Request & /*req*/, Response &res) {
  2498. res.set_content("redirected.", "text/plain");
  2499. res.status = StatusCode::OK_200;
  2500. })
  2501. .Post("/person",
  2502. [&](const Request &req, Response &res) {
  2503. if (req.has_param("name") && req.has_param("note")) {
  2504. persons_[req.get_param_value("name")] =
  2505. req.get_param_value("note");
  2506. } else {
  2507. res.status = StatusCode::BadRequest_400;
  2508. }
  2509. })
  2510. .Put("/person",
  2511. [&](const Request &req, Response &res) {
  2512. if (req.has_param("name") && req.has_param("note")) {
  2513. persons_[req.get_param_value("name")] =
  2514. req.get_param_value("note");
  2515. } else {
  2516. res.status = StatusCode::BadRequest_400;
  2517. }
  2518. })
  2519. .Get("/person/(.*)",
  2520. [&](const Request &req, Response &res) {
  2521. string name = req.matches[1];
  2522. if (persons_.find(name) != persons_.end()) {
  2523. auto note = persons_[name];
  2524. res.set_content(note, "text/plain");
  2525. } else {
  2526. res.status = StatusCode::NotFound_404;
  2527. }
  2528. })
  2529. .Delete("/person",
  2530. [&](const Request &req, Response &res) {
  2531. if (req.has_param("name")) {
  2532. string name = req.get_param_value("name");
  2533. if (persons_.find(name) != persons_.end()) {
  2534. persons_.erase(name);
  2535. res.set_content("DELETED", "text/plain");
  2536. } else {
  2537. res.status = StatusCode::NotFound_404;
  2538. }
  2539. } else {
  2540. res.status = StatusCode::BadRequest_400;
  2541. }
  2542. })
  2543. .Post("/x-www-form-urlencoded-json",
  2544. [&](const Request &req, Response &res) {
  2545. auto json = req.get_param_value("json");
  2546. ASSERT_EQ(JSON_DATA, json);
  2547. res.set_content(json, "appliation/json");
  2548. res.status = StatusCode::OK_200;
  2549. })
  2550. .Get("/streamed-chunked",
  2551. [&](const Request & /*req*/, Response &res) {
  2552. res.set_chunked_content_provider(
  2553. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2554. sink.os << "123";
  2555. sink.os << "456";
  2556. sink.os << "789";
  2557. sink.done();
  2558. return true;
  2559. });
  2560. })
  2561. .Get("/streamed-chunked2",
  2562. [&](const Request & /*req*/, Response &res) {
  2563. auto i = new int(0);
  2564. res.set_chunked_content_provider(
  2565. "text/plain",
  2566. [i](size_t /*offset*/, DataSink &sink) {
  2567. switch (*i) {
  2568. case 0: sink.os << "123"; break;
  2569. case 1: sink.os << "456"; break;
  2570. case 2: sink.os << "789"; break;
  2571. case 3: sink.done(); break;
  2572. }
  2573. (*i)++;
  2574. return true;
  2575. },
  2576. [i](bool success) {
  2577. EXPECT_TRUE(success);
  2578. delete i;
  2579. });
  2580. })
  2581. .Get("/streamed-chunked-with-trailer",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. auto i = new int(0);
  2584. res.set_header("Trailer", "Dummy1, Dummy2");
  2585. res.set_chunked_content_provider(
  2586. "text/plain",
  2587. [i](size_t /*offset*/, DataSink &sink) {
  2588. switch (*i) {
  2589. case 0: sink.os << "123"; break;
  2590. case 1: sink.os << "456"; break;
  2591. case 2: sink.os << "789"; break;
  2592. case 3: {
  2593. sink.done_with_trailer(
  2594. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2595. } break;
  2596. }
  2597. (*i)++;
  2598. return true;
  2599. },
  2600. [i](bool success) {
  2601. EXPECT_TRUE(success);
  2602. delete i;
  2603. });
  2604. })
  2605. .Get("/streamed",
  2606. [&](const Request & /*req*/, Response &res) {
  2607. res.set_content_provider(
  2608. 6, "text/plain",
  2609. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2610. sink.os << (offset < 3 ? "a" : "b");
  2611. return true;
  2612. });
  2613. })
  2614. .Get("/streamed-with-range",
  2615. [&](const Request &req, Response &res) {
  2616. auto data = new std::string("abcdefg");
  2617. res.set_content_provider(
  2618. data->size(), "text/plain",
  2619. [data](size_t offset, size_t length, DataSink &sink) {
  2620. size_t DATA_CHUNK_SIZE = 4;
  2621. const auto &d = *data;
  2622. auto out_len =
  2623. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2624. auto ret =
  2625. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2626. EXPECT_TRUE(ret);
  2627. return true;
  2628. },
  2629. [data, &req](bool success) {
  2630. EXPECT_EQ(success, !req.has_param("error"));
  2631. delete data;
  2632. });
  2633. })
  2634. .Get("/streamed-cancel",
  2635. [&](const Request & /*req*/, Response &res) {
  2636. res.set_content_provider(
  2637. size_t(-1), "text/plain",
  2638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2639. sink.os << "data_chunk";
  2640. return true;
  2641. });
  2642. })
  2643. .Get("/regex-with-delimiter",
  2644. [&](const Request &req, Response & /*res*/) {
  2645. ASSERT_TRUE(req.has_param("key"));
  2646. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2647. })
  2648. .Get("/with-range",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_content("abcdefg", "text/plain");
  2651. })
  2652. .Get("/with-range-customized-response",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.status = StatusCode::BadRequest_400;
  2655. res.set_content(JSON_DATA, "application/json");
  2656. })
  2657. .Post("/chunked",
  2658. [&](const Request &req, Response & /*res*/) {
  2659. EXPECT_EQ(req.body, "dechunked post body");
  2660. })
  2661. .Post("/large-chunked",
  2662. [&](const Request &req, Response & /*res*/) {
  2663. std::string expected(6 * 30 * 1024u, 'a');
  2664. EXPECT_EQ(req.body, expected);
  2665. })
  2666. .Post("/multipart",
  2667. [&](const Request &req, Response & /*res*/) {
  2668. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2669. req.form.get_field_count("text2") +
  2670. req.form.get_field_count("file3") +
  2671. req.form.get_field_count("file4"));
  2672. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2673. req.form.get_file_count("file2"));
  2674. ASSERT_TRUE(!req.form.has_file("???"));
  2675. ASSERT_TRUE(!req.form.has_field("???"));
  2676. ASSERT_TRUE(req.body.empty());
  2677. {
  2678. const auto &text = req.form.get_field("text1");
  2679. EXPECT_EQ("text default", text);
  2680. }
  2681. {
  2682. const auto &text = req.form.get_field("text2");
  2683. EXPECT_EQ("aωb", text);
  2684. }
  2685. {
  2686. const auto &file = req.form.get_file("file1");
  2687. EXPECT_EQ("hello.txt", file.filename);
  2688. EXPECT_EQ("text/plain", file.content_type);
  2689. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2690. }
  2691. {
  2692. const auto &file = req.form.get_file("file2");
  2693. EXPECT_EQ("world.json", file.filename);
  2694. EXPECT_EQ("application/json", file.content_type);
  2695. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2696. }
  2697. {
  2698. const auto &text = req.form.get_field("file3");
  2699. EXPECT_EQ(0u, text.size());
  2700. }
  2701. {
  2702. const auto &text = req.form.get_field("file4");
  2703. EXPECT_EQ(0u, text.size());
  2704. }
  2705. })
  2706. .Post("/multipart/multi_file_values",
  2707. [&](const Request &req, Response & /*res*/) {
  2708. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2709. req.form.get_field_count("multi_text1"));
  2710. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2711. ASSERT_TRUE(!req.form.has_file("???"));
  2712. ASSERT_TRUE(!req.form.has_field("???"));
  2713. ASSERT_TRUE(req.body.empty());
  2714. {
  2715. const auto &text = req.form.get_field("text");
  2716. EXPECT_EQ("default text", text);
  2717. }
  2718. {
  2719. const auto &text1_values = req.form.get_fields("multi_text1");
  2720. EXPECT_EQ(2u, text1_values.size());
  2721. EXPECT_EQ("aaaaa", text1_values[0]);
  2722. EXPECT_EQ("bbbbb", text1_values[1]);
  2723. }
  2724. {
  2725. const auto &file1_values = req.form.get_files("multi_file1");
  2726. EXPECT_EQ(2u, file1_values.size());
  2727. auto file1 = file1_values[0];
  2728. EXPECT_EQ(file1.filename, "hello.txt");
  2729. EXPECT_EQ(file1.content_type, "text/plain");
  2730. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2731. auto file2 = file1_values[1];
  2732. EXPECT_EQ(file2.filename, "world.json");
  2733. EXPECT_EQ(file2.content_type, "application/json");
  2734. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2735. }
  2736. })
  2737. .Post("/empty",
  2738. [&](const Request &req, Response &res) {
  2739. EXPECT_EQ(req.body, "");
  2740. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2741. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2742. res.set_content("empty", "text/plain");
  2743. })
  2744. .Post("/empty-no-content-type",
  2745. [&](const Request &req, Response &res) {
  2746. EXPECT_EQ(req.body, "");
  2747. EXPECT_FALSE(req.has_header("Content-Type"));
  2748. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2749. res.set_content("empty-no-content-type", "text/plain");
  2750. })
  2751. .Post("/path-only",
  2752. [&](const Request &req, Response &res) {
  2753. EXPECT_EQ(req.body, "");
  2754. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2755. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2756. res.set_content("path-only", "text/plain");
  2757. })
  2758. .Post("/path-headers-only",
  2759. [&](const Request &req, Response &res) {
  2760. EXPECT_EQ(req.body, "");
  2761. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2762. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2763. EXPECT_EQ("world", req.get_header_value("hello"));
  2764. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2765. res.set_content("path-headers-only", "text/plain");
  2766. })
  2767. .Post("/post-large",
  2768. [&](const Request &req, Response &res) {
  2769. EXPECT_EQ(req.body, LARGE_DATA);
  2770. res.set_content(req.body, "text/plain");
  2771. })
  2772. .Put("/empty-no-content-type",
  2773. [&](const Request &req, Response &res) {
  2774. EXPECT_EQ(req.body, "");
  2775. EXPECT_FALSE(req.has_header("Content-Type"));
  2776. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2777. res.set_content("empty-no-content-type", "text/plain");
  2778. })
  2779. .Put("/put",
  2780. [&](const Request &req, Response &res) {
  2781. EXPECT_EQ(req.body, "PUT");
  2782. res.set_content(req.body, "text/plain");
  2783. })
  2784. .Put("/put-large",
  2785. [&](const Request &req, Response &res) {
  2786. EXPECT_EQ(req.body, LARGE_DATA);
  2787. res.set_content(req.body, "text/plain");
  2788. })
  2789. .Patch("/patch",
  2790. [&](const Request &req, Response &res) {
  2791. EXPECT_EQ(req.body, "PATCH");
  2792. res.set_content(req.body, "text/plain");
  2793. })
  2794. .Delete("/delete",
  2795. [&](const Request & /*req*/, Response &res) {
  2796. res.set_content("DELETE", "text/plain");
  2797. })
  2798. .Delete("/delete-body",
  2799. [&](const Request &req, Response &res) {
  2800. EXPECT_EQ(req.body, "content");
  2801. res.set_content(req.body, "text/plain");
  2802. })
  2803. .Options(R"(\*)",
  2804. [&](const Request & /*req*/, Response &res) {
  2805. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2806. })
  2807. .Get("/request-target",
  2808. [&](const Request &req, Response & /*res*/) {
  2809. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2810. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2811. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2812. })
  2813. .Get("/long-query-value",
  2814. [&](const Request &req, Response & /*res*/) {
  2815. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2816. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2817. })
  2818. .Get("/too-long-query-value",
  2819. [&](const Request &req, Response & /*res*/) {
  2820. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2821. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2822. })
  2823. .Get("/array-param",
  2824. [&](const Request &req, Response & /*res*/) {
  2825. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2826. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2827. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2828. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2829. })
  2830. .Post("/validate-no-multiple-headers",
  2831. [&](const Request &req, Response & /*res*/) {
  2832. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2833. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2834. })
  2835. .Post("/content_receiver",
  2836. [&](const Request &req, Response &res,
  2837. const ContentReader &content_reader) {
  2838. if (req.is_multipart_form_data()) {
  2839. std::vector<FormData> items;
  2840. content_reader(
  2841. [&](const FormData &file) {
  2842. items.push_back(file);
  2843. return true;
  2844. },
  2845. [&](const char *data, size_t data_length) {
  2846. items.back().content.append(data, data_length);
  2847. return true;
  2848. });
  2849. EXPECT_EQ(5u, items.size());
  2850. {
  2851. const auto &file = get_file_value(items, "text1");
  2852. EXPECT_TRUE(file.filename.empty());
  2853. EXPECT_EQ("text default", file.content);
  2854. }
  2855. {
  2856. const auto &file = get_file_value(items, "text2");
  2857. EXPECT_TRUE(file.filename.empty());
  2858. EXPECT_EQ("aωb", file.content);
  2859. }
  2860. {
  2861. const auto &file = get_file_value(items, "file1");
  2862. EXPECT_EQ("hello.txt", file.filename);
  2863. EXPECT_EQ("text/plain", file.content_type);
  2864. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2865. }
  2866. {
  2867. const auto &file = get_file_value(items, "file2");
  2868. EXPECT_EQ("world.json", file.filename);
  2869. EXPECT_EQ("application/json", file.content_type);
  2870. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2871. }
  2872. {
  2873. const auto &file = get_file_value(items, "file3");
  2874. EXPECT_TRUE(file.filename.empty());
  2875. EXPECT_EQ("application/octet-stream", file.content_type);
  2876. EXPECT_EQ(0u, file.content.size());
  2877. }
  2878. } else {
  2879. std::string body;
  2880. content_reader([&](const char *data, size_t data_length) {
  2881. EXPECT_EQ(7U, data_length);
  2882. body.append(data, data_length);
  2883. return true;
  2884. });
  2885. EXPECT_EQ(body, "content");
  2886. res.set_content(body, "text/plain");
  2887. }
  2888. })
  2889. .Put("/content_receiver",
  2890. [&](const Request & /*req*/, Response &res,
  2891. const ContentReader &content_reader) {
  2892. std::string body;
  2893. content_reader([&](const char *data, size_t data_length) {
  2894. body.append(data, data_length);
  2895. return true;
  2896. });
  2897. EXPECT_EQ(body, "content");
  2898. res.set_content(body, "text/plain");
  2899. })
  2900. .Patch("/content_receiver",
  2901. [&](const Request & /*req*/, Response &res,
  2902. const ContentReader &content_reader) {
  2903. std::string body;
  2904. content_reader([&](const char *data, size_t data_length) {
  2905. body.append(data, data_length);
  2906. return true;
  2907. });
  2908. EXPECT_EQ(body, "content");
  2909. res.set_content(body, "text/plain");
  2910. })
  2911. .Post("/query-string-and-body",
  2912. [&](const Request &req, Response & /*res*/) {
  2913. ASSERT_TRUE(req.has_param("key"));
  2914. EXPECT_EQ(req.get_param_value("key"), "value");
  2915. EXPECT_EQ(req.body, "content");
  2916. })
  2917. .Get("/last-request",
  2918. [&](const Request &req, Response & /*res*/) {
  2919. EXPECT_EQ("close", req.get_header_value("Connection"));
  2920. })
  2921. .Get(R"(/redirect/(\d+))",
  2922. [&](const Request &req, Response &res) {
  2923. auto num = std::stoi(req.matches[1]) + 1;
  2924. std::string url = "/redirect/" + std::to_string(num);
  2925. res.set_redirect(url);
  2926. })
  2927. .Post("/binary",
  2928. [&](const Request &req, Response &res) {
  2929. EXPECT_EQ(4U, req.body.size());
  2930. EXPECT_EQ("application/octet-stream",
  2931. req.get_header_value("Content-Type"));
  2932. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2933. res.set_content(req.body, "application/octet-stream");
  2934. })
  2935. .Put("/binary",
  2936. [&](const Request &req, Response &res) {
  2937. EXPECT_EQ(4U, req.body.size());
  2938. EXPECT_EQ("application/octet-stream",
  2939. req.get_header_value("Content-Type"));
  2940. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2941. res.set_content(req.body, "application/octet-stream");
  2942. })
  2943. .Patch("/binary",
  2944. [&](const Request &req, Response &res) {
  2945. EXPECT_EQ(4U, req.body.size());
  2946. EXPECT_EQ("application/octet-stream",
  2947. req.get_header_value("Content-Type"));
  2948. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2949. res.set_content(req.body, "application/octet-stream");
  2950. })
  2951. .Delete("/binary",
  2952. [&](const Request &req, Response &res) {
  2953. EXPECT_EQ(4U, req.body.size());
  2954. EXPECT_EQ("application/octet-stream",
  2955. req.get_header_value("Content-Type"));
  2956. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2957. res.set_content(req.body, "application/octet-stream");
  2958. })
  2959. .Get("/issue1772",
  2960. [&](const Request & /*req*/, Response &res) {
  2961. res.status = 401;
  2962. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2963. })
  2964. .Delete("/issue609",
  2965. [](const httplib::Request &, httplib::Response &res,
  2966. const httplib::ContentReader &) {
  2967. res.set_content("ok", "text/plain");
  2968. })
  2969. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2970. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2971. .Get("/compress",
  2972. [&](const Request & /*req*/, Response &res) {
  2973. res.set_content(
  2974. "12345678901234567890123456789012345678901234567890123456789"
  2975. "01234567890123456789012345678901234567890",
  2976. "text/plain");
  2977. })
  2978. .Get("/nocompress",
  2979. [&](const Request & /*req*/, Response &res) {
  2980. res.set_content(
  2981. "12345678901234567890123456789012345678901234567890123456789"
  2982. "01234567890123456789012345678901234567890",
  2983. "application/octet-stream");
  2984. })
  2985. .Post("/compress-multipart",
  2986. [&](const Request &req, Response & /*res*/) {
  2987. EXPECT_EQ(2u, req.form.fields.size());
  2988. ASSERT_TRUE(!req.form.has_field("???"));
  2989. {
  2990. const auto &text = req.form.get_field("key1");
  2991. EXPECT_EQ("test", text);
  2992. }
  2993. {
  2994. const auto &text = req.form.get_field("key2");
  2995. EXPECT_EQ("--abcdefg123", text);
  2996. }
  2997. })
  2998. #endif
  2999. ;
  3000. persons_["john"] = "programmer";
  3001. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3002. svr_.wait_until_ready();
  3003. }
  3004. virtual void TearDown() {
  3005. svr_.stop();
  3006. if (!request_threads_.empty()) {
  3007. std::this_thread::sleep_for(std::chrono::seconds(1));
  3008. for (auto &t : request_threads_) {
  3009. t.join();
  3010. }
  3011. }
  3012. t_.join();
  3013. }
  3014. map<string, string> persons_;
  3015. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3016. SSLClient cli_;
  3017. SSLServer svr_;
  3018. #else
  3019. Client cli_;
  3020. Server svr_;
  3021. #endif
  3022. thread t_;
  3023. std::vector<thread> request_threads_;
  3024. };
  3025. TEST_F(ServerTest, GetMethod200) {
  3026. auto res = cli_.Get("/hi");
  3027. ASSERT_TRUE(res);
  3028. EXPECT_EQ("HTTP/1.1", res->version);
  3029. EXPECT_EQ(StatusCode::OK_200, res->status);
  3030. EXPECT_EQ("OK", res->reason);
  3031. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3032. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3033. EXPECT_EQ("Hello World!", res->body);
  3034. }
  3035. void performance_test(const char *host) {
  3036. auto port = 1234;
  3037. Server svr;
  3038. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3039. res.set_content("Benchmark Response", "text/plain");
  3040. });
  3041. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. listen_thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. Client cli(host, port);
  3049. auto start = std::chrono::high_resolution_clock::now();
  3050. auto res = cli.Get("/benchmark");
  3051. ASSERT_TRUE(res);
  3052. EXPECT_EQ(StatusCode::OK_200, res->status);
  3053. auto end = std::chrono::high_resolution_clock::now();
  3054. auto elapsed =
  3055. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3056. .count();
  3057. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3058. << "ms (Issue #1777)";
  3059. }
  3060. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3061. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3062. TEST_F(ServerTest, GetEmptyFile) {
  3063. auto res = cli_.Get("/empty_file");
  3064. ASSERT_TRUE(res);
  3065. EXPECT_EQ(StatusCode::OK_200, res->status);
  3066. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3067. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3068. EXPECT_EQ("", res->body);
  3069. }
  3070. TEST_F(ServerTest, GetFileContent) {
  3071. auto res = cli_.Get("/file_content");
  3072. ASSERT_TRUE(res);
  3073. EXPECT_EQ(StatusCode::OK_200, res->status);
  3074. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3075. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3076. EXPECT_EQ("test.html", res->body);
  3077. }
  3078. TEST_F(ServerTest, GetFileContentWithRange) {
  3079. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3080. ASSERT_TRUE(res);
  3081. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3082. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3083. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3084. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3085. EXPECT_EQ("est", res->body);
  3086. }
  3087. TEST_F(ServerTest, GetFileContentWithContentType) {
  3088. auto res = cli_.Get("/file_content_with_content_type");
  3089. ASSERT_TRUE(res);
  3090. EXPECT_EQ(StatusCode::OK_200, res->status);
  3091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3092. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3093. EXPECT_EQ("file\n", res->body);
  3094. }
  3095. TEST_F(ServerTest, GetInvalidFileContent) {
  3096. auto res = cli_.Get("/invalid_file_content");
  3097. ASSERT_TRUE(res);
  3098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3099. }
  3100. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3101. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ("HTTP/1.1", res->version);
  3104. EXPECT_EQ(StatusCode::OK_200, res->status);
  3105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3106. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3107. EXPECT_EQ("Hello World!", res->body);
  3108. }
  3109. TEST_F(ServerTest, GetMethod302) {
  3110. auto res = cli_.Get("/");
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::Found_302, res->status);
  3113. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3114. }
  3115. TEST_F(ServerTest, GetMethod302Redirect) {
  3116. cli_.set_follow_location(true);
  3117. auto res = cli_.Get("/");
  3118. ASSERT_TRUE(res);
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_EQ("Hello World!", res->body);
  3121. EXPECT_EQ("/hi", res->location);
  3122. }
  3123. TEST_F(ServerTest, GetMethod404) {
  3124. auto res = cli_.Get("/invalid");
  3125. ASSERT_TRUE(res);
  3126. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3127. }
  3128. TEST_F(ServerTest, HeadMethod200) {
  3129. auto res = cli_.Head("/hi");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ(StatusCode::OK_200, res->status);
  3132. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3133. EXPECT_TRUE(res->body.empty());
  3134. }
  3135. TEST_F(ServerTest, HeadMethod200Static) {
  3136. auto res = cli_.Head("/mount/dir/index.html");
  3137. ASSERT_TRUE(res);
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3140. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3141. EXPECT_TRUE(res->body.empty());
  3142. }
  3143. TEST_F(ServerTest, HeadMethod404) {
  3144. auto res = cli_.Head("/invalid");
  3145. ASSERT_TRUE(res);
  3146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3147. EXPECT_TRUE(res->body.empty());
  3148. }
  3149. TEST_F(ServerTest, GetMethodPersonJohn) {
  3150. auto res = cli_.Get("/person/john");
  3151. ASSERT_TRUE(res);
  3152. EXPECT_EQ(StatusCode::OK_200, res->status);
  3153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3154. EXPECT_EQ("programmer", res->body);
  3155. }
  3156. TEST_F(ServerTest, PostMethod1) {
  3157. auto res = cli_.Get("/person/john1");
  3158. ASSERT_TRUE(res);
  3159. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3160. res = cli_.Post("/person", "name=john1&note=coder",
  3161. "application/x-www-form-urlencoded");
  3162. ASSERT_TRUE(res);
  3163. ASSERT_EQ(StatusCode::OK_200, res->status);
  3164. res = cli_.Get("/person/john1");
  3165. ASSERT_TRUE(res);
  3166. ASSERT_EQ(StatusCode::OK_200, res->status);
  3167. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3168. ASSERT_EQ("coder", res->body);
  3169. }
  3170. TEST_F(ServerTest, PostMethod2) {
  3171. auto res = cli_.Get("/person/john2");
  3172. ASSERT_TRUE(res);
  3173. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3174. Params params;
  3175. params.emplace("name", "john2");
  3176. params.emplace("note", "coder");
  3177. res = cli_.Post("/person", params);
  3178. ASSERT_TRUE(res);
  3179. ASSERT_EQ(StatusCode::OK_200, res->status);
  3180. res = cli_.Get("/person/john2");
  3181. ASSERT_TRUE(res);
  3182. ASSERT_EQ(StatusCode::OK_200, res->status);
  3183. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3184. ASSERT_EQ("coder", res->body);
  3185. }
  3186. TEST_F(ServerTest, PutMethod3) {
  3187. auto res = cli_.Get("/person/john3");
  3188. ASSERT_TRUE(res);
  3189. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3190. Params params;
  3191. params.emplace("name", "john3");
  3192. params.emplace("note", "coder");
  3193. res = cli_.Put("/person", params);
  3194. ASSERT_TRUE(res);
  3195. ASSERT_EQ(StatusCode::OK_200, res->status);
  3196. res = cli_.Get("/person/john3");
  3197. ASSERT_TRUE(res);
  3198. ASSERT_EQ(StatusCode::OK_200, res->status);
  3199. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3200. ASSERT_EQ("coder", res->body);
  3201. }
  3202. TEST_F(ServerTest, DeleteMethod1) {
  3203. auto res = cli_.Get("/person/john4");
  3204. ASSERT_TRUE(res);
  3205. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3206. Params params;
  3207. params.emplace("name", "john4");
  3208. params.emplace("note", "coder");
  3209. res = cli_.Post("/person", params);
  3210. ASSERT_TRUE(res);
  3211. ASSERT_EQ(StatusCode::OK_200, res->status);
  3212. res = cli_.Get("/person/john4");
  3213. ASSERT_TRUE(res);
  3214. ASSERT_EQ(StatusCode::OK_200, res->status);
  3215. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3216. ASSERT_EQ("coder", res->body);
  3217. Params delete_params;
  3218. delete_params.emplace("name", "john4");
  3219. res = cli_.Delete("/person", delete_params);
  3220. ASSERT_TRUE(res);
  3221. ASSERT_EQ(StatusCode::OK_200, res->status);
  3222. ASSERT_EQ("DELETED", res->body);
  3223. res = cli_.Get("/person/john4");
  3224. ASSERT_TRUE(res);
  3225. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3226. }
  3227. TEST_F(ServerTest, DeleteMethod2) {
  3228. auto res = cli_.Get("/person/john5");
  3229. ASSERT_TRUE(res);
  3230. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3231. Params params;
  3232. params.emplace("name", "john5");
  3233. params.emplace("note", "developer");
  3234. res = cli_.Post("/person", params);
  3235. ASSERT_TRUE(res);
  3236. ASSERT_EQ(StatusCode::OK_200, res->status);
  3237. res = cli_.Get("/person/john5");
  3238. ASSERT_TRUE(res);
  3239. ASSERT_EQ(StatusCode::OK_200, res->status);
  3240. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3241. ASSERT_EQ("developer", res->body);
  3242. Params delete_params;
  3243. delete_params.emplace("name", "john5");
  3244. Headers headers;
  3245. headers.emplace("Custom-Header", "test-value");
  3246. res = cli_.Delete("/person", headers, delete_params);
  3247. ASSERT_TRUE(res);
  3248. ASSERT_EQ(StatusCode::OK_200, res->status);
  3249. ASSERT_EQ("DELETED", res->body);
  3250. res = cli_.Get("/person/john5");
  3251. ASSERT_TRUE(res);
  3252. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3253. }
  3254. TEST_F(ServerTest, DeleteMethod3) {
  3255. auto res = cli_.Get("/person/john6");
  3256. ASSERT_TRUE(res);
  3257. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3258. Params params;
  3259. params.emplace("name", "john6");
  3260. params.emplace("note", "tester");
  3261. res = cli_.Post("/person", params);
  3262. ASSERT_TRUE(res);
  3263. ASSERT_EQ(StatusCode::OK_200, res->status);
  3264. res = cli_.Get("/person/john6");
  3265. ASSERT_TRUE(res);
  3266. ASSERT_EQ(StatusCode::OK_200, res->status);
  3267. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3268. ASSERT_EQ("tester", res->body);
  3269. Params delete_params;
  3270. delete_params.emplace("name", "john6");
  3271. Headers headers;
  3272. headers.emplace("Custom-Header", "test-value");
  3273. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3274. ASSERT_TRUE(res);
  3275. ASSERT_EQ(StatusCode::OK_200, res->status);
  3276. ASSERT_EQ("DELETED", res->body);
  3277. res = cli_.Get("/person/john6");
  3278. ASSERT_TRUE(res);
  3279. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3280. }
  3281. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3282. Params params;
  3283. params.emplace("json", JSON_DATA);
  3284. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3285. ASSERT_TRUE(res);
  3286. ASSERT_EQ(StatusCode::OK_200, res->status);
  3287. ASSERT_EQ(JSON_DATA, res->body);
  3288. }
  3289. TEST_F(ServerTest, PostEmptyContent) {
  3290. auto res = cli_.Post("/empty", "", "text/plain");
  3291. ASSERT_TRUE(res);
  3292. ASSERT_EQ(StatusCode::OK_200, res->status);
  3293. ASSERT_EQ("empty", res->body);
  3294. }
  3295. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3296. auto res = cli_.Post("/empty-no-content-type");
  3297. ASSERT_TRUE(res);
  3298. ASSERT_EQ(StatusCode::OK_200, res->status);
  3299. ASSERT_EQ("empty-no-content-type", res->body);
  3300. }
  3301. TEST_F(ServerTest, PostPathOnly) {
  3302. auto res = cli_.Post("/path-only");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::OK_200, res->status);
  3305. ASSERT_EQ("path-only", res->body);
  3306. }
  3307. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3308. auto res = cli_.Post("/path-headers-only",
  3309. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3310. ASSERT_TRUE(res);
  3311. ASSERT_EQ(StatusCode::OK_200, res->status);
  3312. ASSERT_EQ("path-headers-only", res->body);
  3313. }
  3314. TEST_F(ServerTest, PostLarge) {
  3315. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3316. ASSERT_TRUE(res);
  3317. ASSERT_EQ(StatusCode::OK_200, res->status);
  3318. EXPECT_EQ(LARGE_DATA, res->body);
  3319. }
  3320. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3321. auto res = cli_.Put("/empty-no-content-type");
  3322. ASSERT_TRUE(res);
  3323. ASSERT_EQ(StatusCode::OK_200, res->status);
  3324. ASSERT_EQ("empty-no-content-type", res->body);
  3325. }
  3326. TEST_F(ServerTest, GetMethodDir) {
  3327. auto res = cli_.Get("/dir/");
  3328. ASSERT_TRUE(res);
  3329. EXPECT_EQ(StatusCode::OK_200, res->status);
  3330. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3331. auto body = R"(<html>
  3332. <head>
  3333. </head>
  3334. <body>
  3335. <a href="/dir/test.html">Test</a>
  3336. <a href="/hi">hi</a>
  3337. </body>
  3338. </html>
  3339. )";
  3340. EXPECT_EQ(body, res->body);
  3341. }
  3342. TEST_F(ServerTest, GetMethodDirTest) {
  3343. auto res = cli_.Get("/dir/test.html");
  3344. ASSERT_TRUE(res);
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3347. EXPECT_EQ("test.html", res->body);
  3348. }
  3349. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3350. auto res = cli_.Get("/dir/../dir/test.html");
  3351. ASSERT_TRUE(res);
  3352. EXPECT_EQ(StatusCode::OK_200, res->status);
  3353. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3354. EXPECT_EQ("test.html", res->body);
  3355. }
  3356. TEST_F(ServerTest, GetMethodInvalidPath) {
  3357. auto res = cli_.Get("/dir/../test.html");
  3358. ASSERT_TRUE(res);
  3359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3360. }
  3361. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3362. auto res = cli_.Get("/../www/dir/test.html");
  3363. ASSERT_TRUE(res);
  3364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3365. }
  3366. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3367. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3368. ASSERT_TRUE(res);
  3369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3370. }
  3371. TEST_F(ServerTest, GetMethodDirMountTest) {
  3372. auto res = cli_.Get("/mount/dir/test.html");
  3373. ASSERT_TRUE(res);
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3376. EXPECT_EQ("test.html", res->body);
  3377. }
  3378. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3379. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3380. ASSERT_TRUE(res);
  3381. EXPECT_EQ(StatusCode::OK_200, res->status);
  3382. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3383. EXPECT_EQ("test.html", res->body);
  3384. }
  3385. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3386. auto res = cli_.Get("/mount/dir/../test.html");
  3387. ASSERT_TRUE(res);
  3388. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3389. }
  3390. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3391. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3392. ASSERT_TRUE(res);
  3393. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3394. }
  3395. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3396. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3397. ASSERT_TRUE(res);
  3398. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3399. }
  3400. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3401. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3402. ASSERT_TRUE(res);
  3403. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3404. }
  3405. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3406. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3407. ASSERT_TRUE(res);
  3408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3409. }
  3410. TEST_F(ServerTest, PostMethod303) {
  3411. auto res = cli_.Post("/1", "body", "text/plain");
  3412. ASSERT_TRUE(res);
  3413. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3414. EXPECT_EQ("/2", res->get_header_value("Location"));
  3415. }
  3416. TEST_F(ServerTest, PostMethod303Redirect) {
  3417. cli_.set_follow_location(true);
  3418. auto res = cli_.Post("/1", "body", "text/plain");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::OK_200, res->status);
  3421. EXPECT_EQ("redirected.", res->body);
  3422. EXPECT_EQ("/2", res->location);
  3423. }
  3424. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3425. auto res = cli_.Get("/dir/test.abcde");
  3426. ASSERT_TRUE(res);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ("abcde", res->body);
  3430. }
  3431. TEST_F(ServerTest, StaticFileRange) {
  3432. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3433. ASSERT_TRUE(res);
  3434. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3435. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3436. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3437. EXPECT_EQ(true, res->has_header("Content-Range"));
  3438. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3439. EXPECT_EQ(std::string("cd"), res->body);
  3440. }
  3441. TEST_F(ServerTest, StaticFileRanges) {
  3442. auto res =
  3443. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3446. EXPECT_TRUE(
  3447. res->get_header_value("Content-Type")
  3448. .find(
  3449. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3450. 0);
  3451. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3452. }
  3453. TEST_F(ServerTest, StaticFileRangeHead) {
  3454. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3455. ASSERT_TRUE(res);
  3456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3457. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3458. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3459. EXPECT_EQ(true, res->has_header("Content-Range"));
  3460. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3461. }
  3462. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3463. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3464. ASSERT_TRUE(res);
  3465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3467. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3468. EXPECT_EQ(true, res->has_header("Content-Range"));
  3469. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3470. res->get_header_value("Content-Range"));
  3471. EXPECT_EQ("LAST\n", res->body);
  3472. }
  3473. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3474. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3479. EXPECT_EQ(true, res->has_header("Content-Range"));
  3480. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3481. }
  3482. TEST_F(ServerTest, StaticFileBigFile) {
  3483. auto res = cli_.Get("/dir/1MB.txt");
  3484. ASSERT_TRUE(res);
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3487. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3488. }
  3489. TEST_F(ServerTest, InvalidBaseDirMount) {
  3490. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3491. }
  3492. TEST_F(ServerTest, Binary) {
  3493. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3494. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3495. "application/octet-stream");
  3496. ASSERT_TRUE(res);
  3497. ASSERT_EQ(StatusCode::OK_200, res->status);
  3498. ASSERT_EQ(4U, res->body.size());
  3499. res = cli_.Put("/binary", binary.data(), binary.size(),
  3500. "application/octet-stream");
  3501. ASSERT_TRUE(res);
  3502. ASSERT_EQ(StatusCode::OK_200, res->status);
  3503. ASSERT_EQ(4U, res->body.size());
  3504. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3505. "application/octet-stream");
  3506. ASSERT_TRUE(res);
  3507. ASSERT_EQ(StatusCode::OK_200, res->status);
  3508. ASSERT_EQ(4U, res->body.size());
  3509. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3510. "application/octet-stream");
  3511. ASSERT_TRUE(res);
  3512. ASSERT_EQ(StatusCode::OK_200, res->status);
  3513. ASSERT_EQ(4U, res->body.size());
  3514. }
  3515. TEST_F(ServerTest, BinaryString) {
  3516. auto binary = std::string("\x00\x01\x02\x03", 4);
  3517. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. ASSERT_EQ(4U, res->body.size());
  3521. res = cli_.Put("/binary", binary, "application/octet-stream");
  3522. ASSERT_TRUE(res);
  3523. ASSERT_EQ(StatusCode::OK_200, res->status);
  3524. ASSERT_EQ(4U, res->body.size());
  3525. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3526. ASSERT_TRUE(res);
  3527. ASSERT_EQ(StatusCode::OK_200, res->status);
  3528. ASSERT_EQ(4U, res->body.size());
  3529. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3530. ASSERT_TRUE(res);
  3531. ASSERT_EQ(StatusCode::OK_200, res->status);
  3532. ASSERT_EQ(4U, res->body.size());
  3533. }
  3534. TEST_F(ServerTest, EmptyRequest) {
  3535. auto res = cli_.Get("");
  3536. ASSERT_TRUE(!res);
  3537. EXPECT_EQ(Error::Connection, res.error());
  3538. }
  3539. TEST_F(ServerTest, LongRequest) {
  3540. std::string request;
  3541. for (size_t i = 0; i < 545; i++) {
  3542. request += "/TooLongRequest";
  3543. }
  3544. request += "OK";
  3545. auto res = cli_.Get(request.c_str());
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3548. }
  3549. TEST_F(ServerTest, TooLongRequest) {
  3550. std::string request;
  3551. for (size_t i = 0; i < 546; i++) {
  3552. request += "/TooLongRequest";
  3553. }
  3554. request += "_NG";
  3555. auto res = cli_.Get(request.c_str());
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3558. }
  3559. TEST_F(ServerTest, AlmostTooLongRequest) {
  3560. // test for #2046 - URI length check shouldn't include other content on req
  3561. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3562. // leading /, space, HTTP/1.1)
  3563. std::string request =
  3564. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3565. auto res = cli_.Get(request.c_str());
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3568. }
  3569. TEST_F(ServerTest, LongHeader) {
  3570. Request req;
  3571. req.method = "GET";
  3572. req.path = "/hi";
  3573. std::string host_and_port;
  3574. host_and_port += HOST;
  3575. host_and_port += ":";
  3576. host_and_port += std::to_string(PORT);
  3577. req.headers.emplace("Host", host_and_port.c_str());
  3578. req.headers.emplace("Accept", "*/*");
  3579. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3580. req.headers.emplace(
  3581. "Header-Name",
  3582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3594. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3595. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3596. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3597. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3598. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3599. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3600. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3601. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3602. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@");
  3611. auto res = std::make_shared<Response>();
  3612. auto error = Error::Success;
  3613. auto ret = cli_.send(req, *res, error);
  3614. ASSERT_TRUE(ret);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. }
  3617. TEST_F(ServerTest, LongQueryValue) {
  3618. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3619. ASSERT_TRUE(res);
  3620. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3621. }
  3622. TEST_F(ServerTest, TooLongQueryValue) {
  3623. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3624. ASSERT_FALSE(res);
  3625. EXPECT_EQ(Error::Read, res.error());
  3626. }
  3627. TEST_F(ServerTest, TooLongHeader) {
  3628. Request req;
  3629. req.method = "GET";
  3630. req.path = "/hi";
  3631. std::string host_and_port;
  3632. host_and_port += HOST;
  3633. host_and_port += ":";
  3634. host_and_port += std::to_string(PORT);
  3635. req.headers.emplace("Host", host_and_port.c_str());
  3636. req.headers.emplace("Accept", "*/*");
  3637. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3638. req.headers.emplace(
  3639. "Header-Name",
  3640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@");
  3669. auto res = std::make_shared<Response>();
  3670. auto error = Error::Success;
  3671. auto ret = cli_.send(req, *res, error);
  3672. ASSERT_TRUE(ret);
  3673. EXPECT_EQ(StatusCode::OK_200, res->status);
  3674. }
  3675. TEST_F(ServerTest, HeaderCountAtLimit) {
  3676. // Test with headers just under the 100 limit
  3677. httplib::Headers headers;
  3678. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3679. // This should keep us just under the 100 header limit
  3680. for (int i = 0; i < 95; i++) {
  3681. std::string name = "X-Test-Header-" + std::to_string(i);
  3682. std::string value = "value" + std::to_string(i);
  3683. headers.emplace(name, value);
  3684. }
  3685. // This should work fine as we're under the limit
  3686. auto res = cli_.Get("/hi", headers);
  3687. EXPECT_TRUE(res);
  3688. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3689. }
  3690. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3691. // Test with many headers to exceed the 100 limit
  3692. httplib::Headers headers;
  3693. // Add 150 headers to definitely exceed the 100 limit
  3694. for (int i = 0; i < 150; i++) {
  3695. std::string name = "X-Test-Header-" + std::to_string(i);
  3696. std::string value = "value" + std::to_string(i);
  3697. headers.emplace(name, value);
  3698. }
  3699. // This should fail due to exceeding header count limit
  3700. auto res = cli_.Get("/hi", headers);
  3701. // The request should either fail or return 400 Bad Request
  3702. if (res) {
  3703. // If we get a response, it should be 400 Bad Request
  3704. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3705. } else {
  3706. // Or the request should fail entirely
  3707. EXPECT_FALSE(res);
  3708. }
  3709. }
  3710. TEST_F(ServerTest, PercentEncoding) {
  3711. auto res = cli_.Get("/e%6edwith%");
  3712. ASSERT_TRUE(res);
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. }
  3715. TEST_F(ServerTest, PercentEncodingUnicode) {
  3716. auto res = cli_.Get("/e%u006edwith%");
  3717. ASSERT_TRUE(res);
  3718. EXPECT_EQ(StatusCode::OK_200, res->status);
  3719. }
  3720. TEST_F(ServerTest, InvalidPercentEncoding) {
  3721. auto res = cli_.Get("/%endwith%");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3724. }
  3725. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3726. auto res = cli_.Get("/%uendwith%");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3729. }
  3730. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3731. auto res = cli_.Get("/hello?aaa=bbb%");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3734. }
  3735. TEST_F(ServerTest, PlusSignEncoding) {
  3736. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3737. ASSERT_TRUE(res);
  3738. EXPECT_EQ(StatusCode::OK_200, res->status);
  3739. EXPECT_EQ("a +b", res->body);
  3740. }
  3741. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3742. // This test simulates a potential DoS attack using many headers
  3743. // to verify our security fix prevents memory exhaustion
  3744. httplib::Headers attack_headers;
  3745. // Attempt to add many headers like an attacker would (200 headers to far
  3746. // exceed limit)
  3747. for (int i = 0; i < 200; i++) {
  3748. std::string name = "X-Attack-Header-" + std::to_string(i);
  3749. std::string value = "attack_payload_" + std::to_string(i);
  3750. attack_headers.emplace(name, value);
  3751. }
  3752. // Try to POST with excessive headers
  3753. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3754. // Should either fail or return 400 Bad Request due to security limit
  3755. if (res) {
  3756. // If we get a response, it should be 400 Bad Request
  3757. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3758. } else {
  3759. // Request failed, which is the expected behavior for DoS protection
  3760. EXPECT_FALSE(res);
  3761. }
  3762. }
  3763. TEST_F(ServerTest, MultipartFormData) {
  3764. UploadFormDataItems items = {
  3765. {"text1", "text default", "", ""},
  3766. {"text2", "aωb", "", ""},
  3767. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3768. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3769. {"file3", "", "", "application/octet-stream"},
  3770. {"file4", "", "", " application/json tmp-string "}};
  3771. auto res = cli_.Post("/multipart", items);
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::OK_200, res->status);
  3774. }
  3775. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3776. UploadFormDataItems items = {
  3777. {"text", "default text", "", ""},
  3778. {"multi_text1", "aaaaa", "", ""},
  3779. {"multi_text1", "bbbbb", "", ""},
  3780. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3781. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3782. "application/json"},
  3783. };
  3784. auto res = cli_.Post("/multipart/multi_file_values", items);
  3785. ASSERT_TRUE(res);
  3786. EXPECT_EQ(StatusCode::OK_200, res->status);
  3787. }
  3788. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3789. auto res = cli_.Get("/hi");
  3790. ASSERT_TRUE(res);
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3793. EXPECT_EQ("Hello World!", res->body);
  3794. }
  3795. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3796. Request req;
  3797. req.method = "POST";
  3798. req.path = "/chunked";
  3799. std::string host_and_port;
  3800. host_and_port += HOST;
  3801. host_and_port += ":";
  3802. host_and_port += std::to_string(PORT);
  3803. req.headers.emplace("Host", host_and_port.c_str());
  3804. req.headers.emplace("Accept", "*/*");
  3805. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3806. req.headers.emplace("Content-Type", "text/plain");
  3807. req.headers.emplace("Content-Length", "0");
  3808. req.headers.emplace(
  3809. "Transfer-Encoding",
  3810. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3811. // Client does not chunk, so make a chunked body manually.
  3812. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3813. auto res = std::make_shared<Response>();
  3814. auto error = Error::Success;
  3815. auto ret = cli_.send(req, *res, error);
  3816. ASSERT_TRUE(ret);
  3817. EXPECT_EQ(StatusCode::OK_200, res->status);
  3818. }
  3819. TEST_F(ServerTest, GetStreamed2) {
  3820. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3821. ASSERT_TRUE(res);
  3822. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3823. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3824. EXPECT_EQ(true, res->has_header("Content-Range"));
  3825. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3826. EXPECT_EQ(std::string("ab"), res->body);
  3827. }
  3828. TEST_F(ServerTest, GetStreamed) {
  3829. auto res = cli_.Get("/streamed");
  3830. ASSERT_TRUE(res);
  3831. EXPECT_EQ(StatusCode::OK_200, res->status);
  3832. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3833. EXPECT_EQ(std::string("aaabbb"), res->body);
  3834. }
  3835. TEST_F(ServerTest, GetStreamedWithRange1) {
  3836. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3837. ASSERT_TRUE(res);
  3838. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3839. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3840. EXPECT_EQ(true, res->has_header("Content-Range"));
  3841. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3842. EXPECT_EQ(std::string("def"), res->body);
  3843. }
  3844. TEST_F(ServerTest, GetStreamedWithRange2) {
  3845. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3846. ASSERT_TRUE(res);
  3847. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3848. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3849. EXPECT_EQ(true, res->has_header("Content-Range"));
  3850. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3851. EXPECT_EQ(std::string("bcdefg"), res->body);
  3852. }
  3853. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3854. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3857. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3858. EXPECT_EQ(true, res->has_header("Content-Range"));
  3859. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3860. EXPECT_EQ(std::string("efg"), res->body);
  3861. }
  3862. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3863. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3866. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3867. EXPECT_EQ(false, res->has_header("Content-Range"));
  3868. EXPECT_EQ(0U, res->body.size());
  3869. }
  3870. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3871. auto res = cli_.Get("/streamed-with-range",
  3872. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3873. "92233720368547758079223372036854775807"}});
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3876. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3877. EXPECT_EQ(false, res->has_header("Content-Range"));
  3878. EXPECT_EQ(0U, res->body.size());
  3879. }
  3880. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3881. auto res = cli_.Get(
  3882. "/with-range",
  3883. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3884. {"Accept-Encoding", ""}});
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3887. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3888. EXPECT_EQ(true, res->has_header("Content-Range"));
  3889. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3890. EXPECT_EQ(std::string("abcdefg"), res->body);
  3891. }
  3892. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3893. auto res = cli_.Get("/with-range", {
  3894. {"Range", "bytes=0-"},
  3895. {"Accept-Encoding", ""},
  3896. });
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3899. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3900. EXPECT_EQ(true, res->has_header("Content-Range"));
  3901. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3902. EXPECT_EQ(std::string("abcdefg"), res->body);
  3903. }
  3904. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3905. auto res =
  3906. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(false, res->has_header("Content-Range"));
  3911. EXPECT_EQ(267U, res->body.size());
  3912. // Check that both range contents are present
  3913. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3914. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3915. // Check that Content-Range headers are present for both ranges
  3916. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3917. std::string::npos);
  3918. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3919. std::string::npos);
  3920. }
  3921. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3922. Ranges ranges;
  3923. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3924. ranges.emplace_back(0, -1);
  3925. }
  3926. auto res =
  3927. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3930. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3931. EXPECT_EQ(false, res->has_header("Content-Range"));
  3932. EXPECT_EQ(0U, res->body.size());
  3933. }
  3934. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3935. auto res =
  3936. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3939. EXPECT_EQ(5U, res->body.size());
  3940. // Check that overlapping ranges are coalesced into a single range
  3941. EXPECT_EQ("bcdef", res->body);
  3942. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3943. // Should be single range, not multipart
  3944. EXPECT_TRUE(res->has_header("Content-Range"));
  3945. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3946. }
  3947. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3948. auto res =
  3949. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3952. EXPECT_EQ(268U, res->body.size());
  3953. // Check that both range contents are present
  3954. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3955. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3956. // Check that Content-Range headers are present for both ranges
  3957. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3958. std::string::npos);
  3959. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3960. std::string::npos);
  3961. }
  3962. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3963. auto res =
  3964. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3965. ASSERT_TRUE(res);
  3966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3967. EXPECT_EQ(269U, res->body.size());
  3968. // Check that both duplicate range contents are present
  3969. size_t first_abc = res->body.find("abc\r\n");
  3970. EXPECT_TRUE(first_abc != std::string::npos);
  3971. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3972. EXPECT_TRUE(second_abc != std::string::npos);
  3973. // Check that Content-Range headers are present for both ranges
  3974. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3975. EXPECT_TRUE(first_range != std::string::npos);
  3976. size_t second_range =
  3977. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  3978. EXPECT_TRUE(second_range != std::string::npos);
  3979. }
  3980. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3981. auto res = cli_.Get("/streamed-with-range?error",
  3982. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3985. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ(false, res->has_header("Content-Range"));
  3987. EXPECT_EQ(0U, res->body.size());
  3988. }
  3989. TEST_F(ServerTest, GetStreamedEndless) {
  3990. uint64_t offset = 0;
  3991. auto res = cli_.Get("/streamed-cancel",
  3992. [&](const char * /*data*/, uint64_t data_length) {
  3993. if (offset < 100) {
  3994. offset += data_length;
  3995. return true;
  3996. }
  3997. return false;
  3998. });
  3999. ASSERT_TRUE(!res);
  4000. EXPECT_EQ(Error::Canceled, res.error());
  4001. }
  4002. TEST_F(ServerTest, ClientStop) {
  4003. std::atomic_size_t count{4};
  4004. std::vector<std::thread> threads;
  4005. for (auto i = count.load(); i != 0; --i) {
  4006. threads.emplace_back([&]() {
  4007. auto res = cli_.Get("/streamed-cancel",
  4008. [&](const char *, uint64_t) { return true; });
  4009. --count;
  4010. ASSERT_TRUE(!res);
  4011. EXPECT_TRUE(res.error() == Error::Canceled ||
  4012. res.error() == Error::Read || res.error() == Error::Write);
  4013. });
  4014. }
  4015. std::this_thread::sleep_for(std::chrono::seconds(2));
  4016. while (count != 0) {
  4017. cli_.stop();
  4018. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4019. }
  4020. for (auto &t : threads) {
  4021. t.join();
  4022. }
  4023. }
  4024. TEST_F(ServerTest, GetWithRange1) {
  4025. auto res = cli_.Get("/with-range", {
  4026. make_range_header({{3, 5}}),
  4027. {"Accept-Encoding", ""},
  4028. });
  4029. ASSERT_TRUE(res);
  4030. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4031. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4032. EXPECT_EQ(true, res->has_header("Content-Range"));
  4033. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4034. EXPECT_EQ(std::string("def"), res->body);
  4035. }
  4036. TEST_F(ServerTest, GetWithRange2) {
  4037. auto res = cli_.Get("/with-range", {
  4038. make_range_header({{1, -1}}),
  4039. {"Accept-Encoding", ""},
  4040. });
  4041. ASSERT_TRUE(res);
  4042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4043. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4044. EXPECT_EQ(true, res->has_header("Content-Range"));
  4045. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4046. EXPECT_EQ(std::string("bcdefg"), res->body);
  4047. }
  4048. TEST_F(ServerTest, GetWithRange3) {
  4049. auto res = cli_.Get("/with-range", {
  4050. make_range_header({{0, 0}}),
  4051. {"Accept-Encoding", ""},
  4052. });
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4055. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(true, res->has_header("Content-Range"));
  4057. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4058. EXPECT_EQ(std::string("a"), res->body);
  4059. }
  4060. TEST_F(ServerTest, GetWithRange4) {
  4061. auto res = cli_.Get("/with-range", {
  4062. make_range_header({{-1, 2}}),
  4063. {"Accept-Encoding", ""},
  4064. });
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4068. EXPECT_EQ(true, res->has_header("Content-Range"));
  4069. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4070. EXPECT_EQ(std::string("fg"), res->body);
  4071. }
  4072. TEST_F(ServerTest, GetWithRange5) {
  4073. auto res = cli_.Get("/with-range", {
  4074. make_range_header({{0, 5}}),
  4075. {"Accept-Encoding", ""},
  4076. });
  4077. ASSERT_TRUE(res);
  4078. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4079. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4080. EXPECT_EQ(true, res->has_header("Content-Range"));
  4081. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4082. EXPECT_EQ(std::string("abcdef"), res->body);
  4083. }
  4084. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4085. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4086. ASSERT_TRUE(res);
  4087. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4088. }
  4089. TEST_F(ServerTest, GetWithRangeMultipart) {
  4090. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4094. EXPECT_EQ(false, res->has_header("Content-Range"));
  4095. EXPECT_EQ(267U, res->body.size());
  4096. }
  4097. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4098. auto res =
  4099. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4102. }
  4103. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4104. auto res = cli_.Get("/with-range-customized-response",
  4105. {{make_range_header({{1, 2}})}});
  4106. ASSERT_TRUE(res);
  4107. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4108. EXPECT_EQ(true, res->has_header("Content-Length"));
  4109. EXPECT_EQ(false, res->has_header("Content-Range"));
  4110. EXPECT_EQ(JSON_DATA, res->body);
  4111. }
  4112. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4113. auto res = cli_.Get("/with-range-customized-response",
  4114. {{make_range_header({{1, 2}, {4, 5}})}});
  4115. ASSERT_TRUE(res);
  4116. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4117. EXPECT_EQ(true, res->has_header("Content-Length"));
  4118. EXPECT_EQ(false, res->has_header("Content-Range"));
  4119. EXPECT_EQ(JSON_DATA, res->body);
  4120. }
  4121. TEST_F(ServerTest, Issue1772) {
  4122. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4125. }
  4126. TEST_F(ServerTest, Issue609) {
  4127. auto res = cli_.Delete("/issue609");
  4128. ASSERT_TRUE(res);
  4129. EXPECT_EQ(StatusCode::OK_200, res->status);
  4130. EXPECT_EQ(std::string("ok"), res->body);
  4131. }
  4132. TEST_F(ServerTest, GetStreamedChunked) {
  4133. auto res = cli_.Get("/streamed-chunked");
  4134. ASSERT_TRUE(res);
  4135. EXPECT_EQ(StatusCode::OK_200, res->status);
  4136. EXPECT_EQ(std::string("123456789"), res->body);
  4137. }
  4138. TEST_F(ServerTest, GetStreamedChunked2) {
  4139. auto res = cli_.Get("/streamed-chunked2");
  4140. ASSERT_TRUE(res);
  4141. EXPECT_EQ(StatusCode::OK_200, res->status);
  4142. EXPECT_EQ(std::string("123456789"), res->body);
  4143. }
  4144. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4145. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::OK_200, res->status);
  4148. EXPECT_EQ(std::string("123456789"), res->body);
  4149. EXPECT_TRUE(res->has_header("Trailer"));
  4150. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4151. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4152. // Trailers are now stored separately from headers (security fix)
  4153. EXPECT_EQ(2U, res->trailers.size());
  4154. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4155. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4156. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4157. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4158. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4159. // Verify trailers are NOT in headers (security verification)
  4160. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4161. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4162. }
  4163. TEST_F(ServerTest, LargeChunkedPost) {
  4164. Request req;
  4165. req.method = "POST";
  4166. req.path = "/large-chunked";
  4167. std::string host_and_port;
  4168. host_and_port += HOST;
  4169. host_and_port += ":";
  4170. host_and_port += std::to_string(PORT);
  4171. req.headers.emplace("Host", host_and_port.c_str());
  4172. req.headers.emplace("Accept", "*/*");
  4173. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4174. req.headers.emplace("Content-Type", "text/plain");
  4175. req.headers.emplace("Content-Length", "0");
  4176. req.headers.emplace("Transfer-Encoding", "chunked");
  4177. std::string long_string(30 * 1024u, 'a');
  4178. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4179. // Attempt to make a large enough post to exceed OS buffers, to test that
  4180. // the server handles short reads if the full chunk data isn't available.
  4181. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4182. auto res = std::make_shared<Response>();
  4183. auto error = Error::Success;
  4184. auto ret = cli_.send(req, *res, error);
  4185. ASSERT_TRUE(ret);
  4186. EXPECT_EQ(StatusCode::OK_200, res->status);
  4187. }
  4188. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4189. auto res = cli_.Get("/remote_addr");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(StatusCode::OK_200, res->status);
  4192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4193. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4194. }
  4195. TEST_F(ServerTest, GetMethodLocalAddr) {
  4196. auto res = cli_.Get("/local_addr");
  4197. ASSERT_TRUE(res);
  4198. EXPECT_EQ(StatusCode::OK_200, res->status);
  4199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4200. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4201. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4202. }
  4203. TEST_F(ServerTest, HTTPResponseSplitting) {
  4204. auto res = cli_.Get("/http_response_splitting");
  4205. ASSERT_TRUE(res);
  4206. EXPECT_EQ(StatusCode::OK_200, res->status);
  4207. }
  4208. TEST_F(ServerTest, SlowRequest) {
  4209. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4210. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4211. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4212. }
  4213. #if 0
  4214. TEST_F(ServerTest, SlowPost) {
  4215. char buffer[64 * 1024];
  4216. memset(buffer, 0x42, sizeof(buffer));
  4217. auto res = cli_.Post(
  4218. "/slowpost", 64 * 1024 * 1024,
  4219. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4220. auto ret = sink.write(buffer, sizeof(buffer));
  4221. EXPECT_TRUE(ret);
  4222. return true;
  4223. },
  4224. "text/plain");
  4225. ASSERT_TRUE(res);
  4226. EXPECT_EQ(StatusCode::OK_200, res->status);
  4227. }
  4228. TEST_F(ServerTest, SlowPostFail) {
  4229. char buffer[64 * 1024];
  4230. memset(buffer, 0x42, sizeof(buffer));
  4231. cli_.set_write_timeout(std::chrono::seconds(0));
  4232. auto res = cli_.Post(
  4233. "/slowpost", 64 * 1024 * 1024,
  4234. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4235. sink.write(buffer, sizeof(buffer));
  4236. return true;
  4237. },
  4238. "text/plain");
  4239. ASSERT_TRUE(!res);
  4240. EXPECT_EQ(Error::Write, res.error());
  4241. }
  4242. #endif
  4243. TEST_F(ServerTest, Put) {
  4244. auto res = cli_.Put("/put", "PUT", "text/plain");
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::OK_200, res->status);
  4247. EXPECT_EQ("PUT", res->body);
  4248. }
  4249. TEST_F(ServerTest, PutWithContentProvider) {
  4250. auto res = cli_.Put(
  4251. "/put", 3,
  4252. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4253. sink.os << "PUT";
  4254. return true;
  4255. },
  4256. "text/plain");
  4257. ASSERT_TRUE(res);
  4258. EXPECT_EQ(StatusCode::OK_200, res->status);
  4259. EXPECT_EQ("PUT", res->body);
  4260. }
  4261. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4262. auto res = cli_.Post(
  4263. "/post", 42,
  4264. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4265. return false;
  4266. },
  4267. "text/plain");
  4268. ASSERT_TRUE(!res);
  4269. EXPECT_EQ(Error::Canceled, res.error());
  4270. }
  4271. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4272. auto res = cli_.Put(
  4273. "/put",
  4274. [](size_t /*offset*/, DataSink &sink) {
  4275. sink.os << "PUT";
  4276. sink.done();
  4277. return true;
  4278. },
  4279. "text/plain");
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::OK_200, res->status);
  4282. EXPECT_EQ("PUT", res->body);
  4283. }
  4284. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4285. auto res = cli_.Post(
  4286. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4287. "text/plain");
  4288. ASSERT_TRUE(!res);
  4289. EXPECT_EQ(Error::Canceled, res.error());
  4290. }
  4291. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4292. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4293. cli_.set_compress(true);
  4294. auto res = cli_.Put(
  4295. "/put", 3,
  4296. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4297. sink.os << "PUT";
  4298. return true;
  4299. },
  4300. "text/plain");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ("PUT", res->body);
  4304. }
  4305. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4306. cli_.set_compress(true);
  4307. auto res = cli_.Post(
  4308. "/post", 42,
  4309. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4310. return false;
  4311. },
  4312. "text/plain");
  4313. ASSERT_TRUE(!res);
  4314. EXPECT_EQ(Error::Canceled, res.error());
  4315. }
  4316. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4317. cli_.set_compress(true);
  4318. auto res = cli_.Put(
  4319. "/put",
  4320. [](size_t /*offset*/, DataSink &sink) {
  4321. sink.os << "PUT";
  4322. sink.done();
  4323. return true;
  4324. },
  4325. "text/plain");
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::OK_200, res->status);
  4328. EXPECT_EQ("PUT", res->body);
  4329. }
  4330. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4331. cli_.set_compress(true);
  4332. auto res = cli_.Post(
  4333. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4334. "text/plain");
  4335. ASSERT_TRUE(!res);
  4336. EXPECT_EQ(Error::Canceled, res.error());
  4337. }
  4338. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4339. cli_.set_compress(true);
  4340. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::OK_200, res->status);
  4343. EXPECT_EQ(LARGE_DATA, res->body);
  4344. }
  4345. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4346. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4347. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4348. Client cli(s.c_str());
  4349. cli.enable_server_certificate_verification(false);
  4350. #else
  4351. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4352. Client cli(s.c_str());
  4353. #endif
  4354. cli.set_compress(true);
  4355. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4356. ASSERT_TRUE(res);
  4357. EXPECT_EQ(StatusCode::OK_200, res->status);
  4358. EXPECT_EQ(LARGE_DATA, res->body);
  4359. // The compressed size should be less than a 10th of the original. May vary
  4360. // depending on the zlib library.
  4361. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4362. static_cast<uint64_t>(10 * 1024 * 1024));
  4363. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4364. }
  4365. TEST_F(ServerTest, PutContentWithDeflate) {
  4366. cli_.set_compress(false);
  4367. Headers headers;
  4368. headers.emplace("Content-Encoding", "deflate");
  4369. // PUT in deflate format:
  4370. auto res = cli_.Put("/put", headers,
  4371. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ("PUT", res->body);
  4375. }
  4376. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4377. Headers headers;
  4378. headers.emplace("Accept-Encoding", "gzip, deflate");
  4379. auto res = cli_.Get("/streamed-chunked", headers);
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. EXPECT_EQ(std::string("123456789"), res->body);
  4383. }
  4384. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4385. Headers headers;
  4386. headers.emplace("Accept-Encoding", "gzip, deflate");
  4387. auto res = cli_.Get("/streamed-chunked2", headers);
  4388. ASSERT_TRUE(res);
  4389. EXPECT_EQ(StatusCode::OK_200, res->status);
  4390. EXPECT_EQ(std::string("123456789"), res->body);
  4391. }
  4392. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4393. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. }
  4397. TEST(GzipDecompressor, ChunkedDecompression) {
  4398. std::string data;
  4399. for (size_t i = 0; i < 32 * 1024; ++i) {
  4400. data.push_back(static_cast<char>('a' + i % 26));
  4401. }
  4402. std::string compressed_data;
  4403. {
  4404. httplib::detail::gzip_compressor compressor;
  4405. bool result = compressor.compress(
  4406. data.data(), data.size(),
  4407. /*last=*/true,
  4408. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4409. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4410. compressed_data_size);
  4411. return true;
  4412. });
  4413. ASSERT_TRUE(result);
  4414. }
  4415. std::string decompressed_data;
  4416. {
  4417. httplib::detail::gzip_decompressor decompressor;
  4418. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4419. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4420. size_t chunk_size = 130;
  4421. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4422. chunk_begin += chunk_size) {
  4423. size_t current_chunk_size =
  4424. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4425. bool result = decompressor.decompress(
  4426. compressed_data.data() + chunk_begin, current_chunk_size,
  4427. [&](const char *decompressed_data_chunk,
  4428. size_t decompressed_data_chunk_size) {
  4429. decompressed_data.insert(decompressed_data.size(),
  4430. decompressed_data_chunk,
  4431. decompressed_data_chunk_size);
  4432. return true;
  4433. });
  4434. ASSERT_TRUE(result);
  4435. }
  4436. }
  4437. ASSERT_EQ(data, decompressed_data);
  4438. }
  4439. TEST(GzipDecompressor, DeflateDecompression) {
  4440. std::string original_text = "Raw deflate without gzip";
  4441. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4442. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4443. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4444. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4445. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4446. std::string decompressed_data;
  4447. {
  4448. httplib::detail::gzip_decompressor decompressor;
  4449. bool result = decompressor.decompress(
  4450. compressed_data.data(), compressed_data.size(),
  4451. [&](const char *decompressed_data_chunk,
  4452. size_t decompressed_data_chunk_size) {
  4453. decompressed_data.insert(decompressed_data.size(),
  4454. decompressed_data_chunk,
  4455. decompressed_data_chunk_size);
  4456. return true;
  4457. });
  4458. ASSERT_TRUE(result);
  4459. }
  4460. ASSERT_EQ(original_text, decompressed_data);
  4461. }
  4462. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4463. std::string original_text = "Raw deflate without gzip";
  4464. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4465. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4466. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4467. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4468. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4469. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4470. std::string decompressed_data;
  4471. {
  4472. httplib::detail::gzip_decompressor decompressor;
  4473. bool result = decompressor.decompress(
  4474. compressed_data.data(), compressed_data.size(),
  4475. [&](const char *decompressed_data_chunk,
  4476. size_t decompressed_data_chunk_size) {
  4477. decompressed_data.insert(decompressed_data.size(),
  4478. decompressed_data_chunk,
  4479. decompressed_data_chunk_size);
  4480. return true;
  4481. });
  4482. ASSERT_TRUE(result);
  4483. }
  4484. ASSERT_EQ(original_text, decompressed_data);
  4485. }
  4486. #ifdef _WIN32
  4487. TEST(GzipDecompressor, LargeRandomData) {
  4488. // prepare large random data that is difficult to be compressed and is
  4489. // expected to have large size even when compressed
  4490. std::random_device seed_gen;
  4491. std::mt19937 random(seed_gen());
  4492. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4493. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4494. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4495. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4496. // compress data over 4GiB
  4497. std::string compressed_data;
  4498. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4499. httplib::detail::gzip_compressor compressor;
  4500. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4501. data.size() * sizeof(std::uint32_t), true,
  4502. [&](const char *data, size_t size) {
  4503. compressed_data.insert(
  4504. compressed_data.size(), data, size);
  4505. return true;
  4506. });
  4507. ASSERT_TRUE(result);
  4508. // FIXME: compressed data size is expected to be greater than 4GiB,
  4509. // but there is no guarantee
  4510. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4511. // decompress data over 4GiB
  4512. std::string decompressed_data;
  4513. decompressed_data.reserve(data_size);
  4514. httplib::detail::gzip_decompressor decompressor;
  4515. result = decompressor.decompress(
  4516. compressed_data.data(), compressed_data.size(),
  4517. [&](const char *data, size_t size) {
  4518. decompressed_data.insert(decompressed_data.size(), data, size);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(result);
  4522. // compare
  4523. ASSERT_EQ(data_size, decompressed_data.size());
  4524. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4525. 0);
  4526. }
  4527. #endif
  4528. #endif
  4529. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4530. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4531. Headers headers;
  4532. headers.emplace("Accept-Encoding", "br");
  4533. auto res = cli_.Get("/streamed-chunked", headers);
  4534. ASSERT_TRUE(res);
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ(std::string("123456789"), res->body);
  4537. }
  4538. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4539. Headers headers;
  4540. headers.emplace("Accept-Encoding", "br");
  4541. auto res = cli_.Get("/streamed-chunked2", headers);
  4542. ASSERT_TRUE(res);
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. EXPECT_EQ(std::string("123456789"), res->body);
  4545. }
  4546. #endif
  4547. TEST_F(ServerTest, Patch) {
  4548. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4549. ASSERT_TRUE(res);
  4550. EXPECT_EQ(StatusCode::OK_200, res->status);
  4551. EXPECT_EQ("PATCH", res->body);
  4552. }
  4553. TEST_F(ServerTest, Delete) {
  4554. auto res = cli_.Delete("/delete");
  4555. ASSERT_TRUE(res);
  4556. EXPECT_EQ(StatusCode::OK_200, res->status);
  4557. EXPECT_EQ("DELETE", res->body);
  4558. }
  4559. TEST_F(ServerTest, DeleteContentReceiver) {
  4560. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4561. ASSERT_TRUE(res);
  4562. EXPECT_EQ(StatusCode::OK_200, res->status);
  4563. EXPECT_EQ("content", res->body);
  4564. }
  4565. TEST_F(ServerTest, Options) {
  4566. auto res = cli_.Options("*");
  4567. ASSERT_TRUE(res);
  4568. EXPECT_EQ(StatusCode::OK_200, res->status);
  4569. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4570. EXPECT_TRUE(res->body.empty());
  4571. }
  4572. TEST_F(ServerTest, URL) {
  4573. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4574. ASSERT_TRUE(res);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST_F(ServerTest, ArrayParam) {
  4578. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4579. ASSERT_TRUE(res);
  4580. EXPECT_EQ(StatusCode::OK_200, res->status);
  4581. }
  4582. TEST_F(ServerTest, NoMultipleHeaders) {
  4583. Headers headers = {{"Content-Length", "5"}};
  4584. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4585. "text/plain");
  4586. ASSERT_TRUE(res);
  4587. EXPECT_EQ(StatusCode::OK_200, res->status);
  4588. }
  4589. TEST_F(ServerTest, PostContentReceiver) {
  4590. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4591. ASSERT_TRUE(res);
  4592. ASSERT_EQ(StatusCode::OK_200, res->status);
  4593. ASSERT_EQ("content", res->body);
  4594. }
  4595. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4596. UploadFormDataItems items = {
  4597. {"text1", "text default", "", ""},
  4598. {"text2", "aωb", "", ""},
  4599. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4600. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4601. {"file3", "", "", "application/octet-stream"},
  4602. };
  4603. auto res = cli_.Post("/content_receiver", items);
  4604. ASSERT_TRUE(res);
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. }
  4607. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4608. UploadFormDataItems items = {
  4609. {"text1", "text default", "", ""},
  4610. {"text2", "aωb", "", ""},
  4611. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4612. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4613. {"file3", "", "", "application/octet-stream"},
  4614. };
  4615. auto boundary = std::string("+++++");
  4616. std::string body;
  4617. for (const auto &item : items) {
  4618. body += "--" + boundary + "\r\n";
  4619. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4620. if (!item.filename.empty()) {
  4621. body += "; filename=\"" + item.filename + "\"";
  4622. }
  4623. body += "\r\n";
  4624. if (!item.content_type.empty()) {
  4625. body += "Content-Type: " + item.content_type + "\r\n";
  4626. }
  4627. body += "\r\n";
  4628. body += item.content + "\r\n";
  4629. }
  4630. body += "--" + boundary + "--\r\n";
  4631. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4632. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4633. ASSERT_TRUE(res);
  4634. EXPECT_EQ(StatusCode::OK_200, res->status);
  4635. }
  4636. TEST_F(ServerTest, PostContentReceiverGzip) {
  4637. cli_.set_compress(true);
  4638. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4639. ASSERT_TRUE(res);
  4640. ASSERT_EQ(StatusCode::OK_200, res->status);
  4641. ASSERT_EQ("content", res->body);
  4642. }
  4643. TEST_F(ServerTest, PutContentReceiver) {
  4644. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4645. ASSERT_TRUE(res);
  4646. ASSERT_EQ(StatusCode::OK_200, res->status);
  4647. ASSERT_EQ("content", res->body);
  4648. }
  4649. TEST_F(ServerTest, PatchContentReceiver) {
  4650. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4651. ASSERT_TRUE(res);
  4652. ASSERT_EQ(StatusCode::OK_200, res->status);
  4653. ASSERT_EQ("content", res->body);
  4654. }
  4655. template <typename ClientType>
  4656. void TestWithHeadersAndContentReceiver(
  4657. ClientType &cli,
  4658. std::function<Result(ClientType &, const std::string &, const Headers &,
  4659. const std::string &, const std::string &,
  4660. ContentReceiver, DownloadProgress)>
  4661. request_func) {
  4662. Headers headers;
  4663. headers.emplace("X-Custom-Header", "test-value");
  4664. std::string received_body;
  4665. auto res = request_func(
  4666. cli, "/content_receiver", headers, "content", "application/json",
  4667. [&](const char *data, size_t data_length) {
  4668. received_body.append(data, data_length);
  4669. return true;
  4670. },
  4671. nullptr);
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. EXPECT_EQ("content", received_body);
  4675. }
  4676. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4678. using ClientT = SSLClient;
  4679. #else
  4680. using ClientT = Client;
  4681. #endif
  4682. TestWithHeadersAndContentReceiver<ClientT>(
  4683. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4684. const std::string &body, const std::string &content_type,
  4685. ContentReceiver receiver, DownloadProgress progress) {
  4686. return cli.Post(path, headers, body, content_type, receiver, progress);
  4687. });
  4688. }
  4689. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4691. using ClientT = SSLClient;
  4692. #else
  4693. using ClientT = Client;
  4694. #endif
  4695. TestWithHeadersAndContentReceiver<ClientT>(
  4696. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4697. const std::string &body, const std::string &content_type,
  4698. ContentReceiver receiver, DownloadProgress progress) {
  4699. return cli.Put(path, headers, body, content_type, receiver, progress);
  4700. });
  4701. }
  4702. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4703. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4704. using ClientT = SSLClient;
  4705. #else
  4706. using ClientT = Client;
  4707. #endif
  4708. TestWithHeadersAndContentReceiver<ClientT>(
  4709. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4710. const std::string &body, const std::string &content_type,
  4711. ContentReceiver receiver, DownloadProgress progress) {
  4712. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4713. });
  4714. }
  4715. template <typename ClientType>
  4716. void TestWithHeadersAndContentReceiverWithProgress(
  4717. ClientType &cli,
  4718. std::function<Result(ClientType &, const std::string &, const Headers &,
  4719. const std::string &, const std::string &,
  4720. ContentReceiver, DownloadProgress)>
  4721. request_func) {
  4722. Headers headers;
  4723. headers.emplace("X-Test-Header", "progress-test");
  4724. std::string received_body;
  4725. auto progress_called = false;
  4726. auto res = request_func(
  4727. cli, "/content_receiver", headers, "content", "text/plain",
  4728. [&](const char *data, size_t data_length) {
  4729. received_body.append(data, data_length);
  4730. return true;
  4731. },
  4732. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4733. progress_called = true;
  4734. return true;
  4735. });
  4736. ASSERT_TRUE(res);
  4737. EXPECT_EQ(StatusCode::OK_200, res->status);
  4738. EXPECT_EQ("content", received_body);
  4739. EXPECT_TRUE(progress_called);
  4740. }
  4741. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4743. using ClientT = SSLClient;
  4744. #else
  4745. using ClientT = Client;
  4746. #endif
  4747. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4748. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4749. const std::string &body, const std::string &content_type,
  4750. ContentReceiver receiver, DownloadProgress progress) {
  4751. return cli.Post(path, headers, body, content_type, receiver, progress);
  4752. });
  4753. }
  4754. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4755. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4756. using ClientT = SSLClient;
  4757. #else
  4758. using ClientT = Client;
  4759. #endif
  4760. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4761. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4762. const std::string &body, const std::string &content_type,
  4763. ContentReceiver receiver, DownloadProgress progress) {
  4764. return cli.Put(path, headers, body, content_type, receiver, progress);
  4765. });
  4766. }
  4767. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4769. using ClientT = SSLClient;
  4770. #else
  4771. using ClientT = Client;
  4772. #endif
  4773. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4774. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4775. const std::string &body, const std::string &content_type,
  4776. ContentReceiver receiver, DownloadProgress progress) {
  4777. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4778. });
  4779. }
  4780. template <typename ClientType>
  4781. void TestWithHeadersAndContentReceiverError(
  4782. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4783. const Headers &, const std::string &,
  4784. const std::string &, ContentReceiver)>
  4785. request_func) {
  4786. Headers headers;
  4787. headers.emplace("X-Error-Test", "true");
  4788. std::string received_body;
  4789. auto receiver_failed = false;
  4790. auto res =
  4791. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4792. [&](const char *data, size_t data_length) {
  4793. received_body.append(data, data_length);
  4794. receiver_failed = true;
  4795. return false;
  4796. });
  4797. ASSERT_FALSE(res);
  4798. EXPECT_TRUE(receiver_failed);
  4799. }
  4800. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4801. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4802. using ClientT = SSLClient;
  4803. #else
  4804. using ClientT = Client;
  4805. #endif
  4806. TestWithHeadersAndContentReceiverError<ClientT>(
  4807. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4808. const std::string &body, const std::string &content_type,
  4809. ContentReceiver receiver) {
  4810. return cli.Post(path, headers, body, content_type, receiver);
  4811. });
  4812. }
  4813. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4815. using ClientT = SSLClient;
  4816. #else
  4817. using ClientT = Client;
  4818. #endif
  4819. TestWithHeadersAndContentReceiverError<ClientT>(
  4820. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4821. const std::string &body, const std::string &content_type,
  4822. ContentReceiver receiver) {
  4823. return cli.Put(path, headers, body, content_type, receiver);
  4824. });
  4825. }
  4826. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4827. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4828. using ClientT = SSLClient;
  4829. #else
  4830. using ClientT = Client;
  4831. #endif
  4832. TestWithHeadersAndContentReceiverError<ClientT>(
  4833. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4834. const std::string &body, const std::string &content_type,
  4835. ContentReceiver receiver) {
  4836. return cli.Patch(path, headers, body, content_type, receiver);
  4837. });
  4838. }
  4839. TEST_F(ServerTest, PostQueryStringAndBody) {
  4840. auto res =
  4841. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4842. ASSERT_TRUE(res);
  4843. ASSERT_EQ(StatusCode::OK_200, res->status);
  4844. }
  4845. TEST_F(ServerTest, HTTP2Magic) {
  4846. Request req;
  4847. req.method = "PRI";
  4848. req.path = "*";
  4849. req.body = "SM";
  4850. auto res = std::make_shared<Response>();
  4851. auto error = Error::Success;
  4852. auto ret = cli_.send(req, *res, error);
  4853. ASSERT_TRUE(ret);
  4854. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4855. }
  4856. TEST_F(ServerTest, KeepAlive) {
  4857. auto res = cli_.Get("/hi");
  4858. ASSERT_TRUE(res);
  4859. EXPECT_EQ(StatusCode::OK_200, res->status);
  4860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4861. EXPECT_EQ("Hello World!", res->body);
  4862. res = cli_.Get("/hi");
  4863. ASSERT_TRUE(res);
  4864. EXPECT_EQ(StatusCode::OK_200, res->status);
  4865. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4866. EXPECT_EQ("Hello World!", res->body);
  4867. res = cli_.Get("/hi");
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4871. EXPECT_EQ("Hello World!", res->body);
  4872. res = cli_.Get("/not-exist");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4875. res = cli_.Post("/empty", "", "text/plain");
  4876. ASSERT_TRUE(res);
  4877. EXPECT_EQ(StatusCode::OK_200, res->status);
  4878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4879. EXPECT_EQ("empty", res->body);
  4880. EXPECT_EQ("close", res->get_header_value("Connection"));
  4881. res = cli_.Post(
  4882. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4883. "text/plain");
  4884. ASSERT_TRUE(res);
  4885. EXPECT_EQ(StatusCode::OK_200, res->status);
  4886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4887. EXPECT_EQ("empty", res->body);
  4888. cli_.set_keep_alive(false);
  4889. res = cli_.Get("/last-request");
  4890. ASSERT_TRUE(res);
  4891. EXPECT_EQ(StatusCode::OK_200, res->status);
  4892. EXPECT_EQ("close", res->get_header_value("Connection"));
  4893. }
  4894. TEST_F(ServerTest, TooManyRedirect) {
  4895. cli_.set_follow_location(true);
  4896. auto res = cli_.Get("/redirect/0");
  4897. ASSERT_TRUE(!res);
  4898. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4899. }
  4900. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4901. TEST_F(ServerTest, Gzip) {
  4902. Headers headers;
  4903. headers.emplace("Accept-Encoding", "gzip, deflate");
  4904. auto res = cli_.Get("/compress", headers);
  4905. ASSERT_TRUE(res);
  4906. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4907. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4908. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4909. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4910. "7890123456789012345678901234567890",
  4911. res->body);
  4912. EXPECT_EQ(StatusCode::OK_200, res->status);
  4913. }
  4914. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4915. Headers headers;
  4916. headers.emplace("Accept-Encoding", "");
  4917. auto res = cli_.Get("/compress", headers);
  4918. ASSERT_TRUE(res);
  4919. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4921. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4922. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4923. "7890123456789012345678901234567890",
  4924. res->body);
  4925. EXPECT_EQ(StatusCode::OK_200, res->status);
  4926. }
  4927. TEST_F(ServerTest, GzipWithContentReceiver) {
  4928. Headers headers;
  4929. headers.emplace("Accept-Encoding", "gzip, deflate");
  4930. std::string body;
  4931. auto res = cli_.Get("/compress", headers,
  4932. [&](const char *data, uint64_t data_length) {
  4933. EXPECT_EQ(100U, data_length);
  4934. body.append(data, data_length);
  4935. return true;
  4936. });
  4937. ASSERT_TRUE(res);
  4938. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4940. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4941. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4942. "7890123456789012345678901234567890",
  4943. body);
  4944. EXPECT_EQ(StatusCode::OK_200, res->status);
  4945. }
  4946. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4947. Headers headers;
  4948. headers.emplace("Accept-Encoding", "gzip, deflate");
  4949. cli_.set_decompress(false);
  4950. auto res = cli_.Get("/compress", headers);
  4951. ASSERT_TRUE(res);
  4952. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4953. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4954. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4955. EXPECT_EQ(33U, res->body.size());
  4956. EXPECT_EQ(StatusCode::OK_200, res->status);
  4957. }
  4958. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4959. Headers headers;
  4960. headers.emplace("Accept-Encoding", "");
  4961. std::string body;
  4962. auto res = cli_.Get("/compress", headers,
  4963. [&](const char *data, uint64_t data_length) {
  4964. EXPECT_EQ(100U, data_length);
  4965. body.append(data, data_length);
  4966. return true;
  4967. });
  4968. ASSERT_TRUE(res);
  4969. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4970. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4971. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4972. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4973. "7890123456789012345678901234567890",
  4974. body);
  4975. EXPECT_EQ(StatusCode::OK_200, res->status);
  4976. }
  4977. TEST_F(ServerTest, NoGzip) {
  4978. Headers headers;
  4979. headers.emplace("Accept-Encoding", "gzip, deflate");
  4980. auto res = cli_.Get("/nocompress", headers);
  4981. ASSERT_TRUE(res);
  4982. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  4983. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  4984. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4985. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4986. "7890123456789012345678901234567890",
  4987. res->body);
  4988. EXPECT_EQ(StatusCode::OK_200, res->status);
  4989. }
  4990. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  4991. Headers headers;
  4992. headers.emplace("Accept-Encoding", "gzip, deflate");
  4993. std::string body;
  4994. auto res = cli_.Get("/nocompress", headers,
  4995. [&](const char *data, uint64_t data_length) {
  4996. EXPECT_EQ(100U, data_length);
  4997. body.append(data, data_length);
  4998. return true;
  4999. });
  5000. ASSERT_TRUE(res);
  5001. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5002. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5003. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5004. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5005. "7890123456789012345678901234567890",
  5006. body);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. }
  5009. TEST_F(ServerTest, MultipartFormDataGzip) {
  5010. UploadFormDataItems items = {
  5011. {"key1", "test", "", ""},
  5012. {"key2", "--abcdefg123", "", ""},
  5013. };
  5014. cli_.set_compress(true);
  5015. auto res = cli_.Post("/compress-multipart", items);
  5016. ASSERT_TRUE(res);
  5017. EXPECT_EQ(StatusCode::OK_200, res->status);
  5018. }
  5019. #endif
  5020. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5021. TEST_F(ServerTest, Brotli) {
  5022. Headers headers;
  5023. headers.emplace("Accept-Encoding", "br");
  5024. auto res = cli_.Get("/compress", headers);
  5025. ASSERT_TRUE(res);
  5026. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5027. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5028. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5029. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5030. "7890123456789012345678901234567890",
  5031. res->body);
  5032. EXPECT_EQ(StatusCode::OK_200, res->status);
  5033. }
  5034. #endif
  5035. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5036. TEST_F(ServerTest, Zstd) {
  5037. Headers headers;
  5038. headers.emplace("Accept-Encoding", "zstd");
  5039. auto res = cli_.Get("/compress", headers);
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5042. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5043. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5044. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5045. "7890123456789012345678901234567890",
  5046. res->body);
  5047. EXPECT_EQ(StatusCode::OK_200, res->status);
  5048. }
  5049. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5050. Headers headers;
  5051. headers.emplace("Accept-Encoding", "");
  5052. auto res = cli_.Get("/compress", headers);
  5053. ASSERT_TRUE(res);
  5054. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5056. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5057. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5058. "7890123456789012345678901234567890",
  5059. res->body);
  5060. EXPECT_EQ(StatusCode::OK_200, res->status);
  5061. }
  5062. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5063. Headers headers;
  5064. headers.emplace("Accept-Encoding", "zstd");
  5065. std::string body;
  5066. auto res = cli_.Get("/compress", headers,
  5067. [&](const char *data, uint64_t data_length) {
  5068. EXPECT_EQ(100U, data_length);
  5069. body.append(data, data_length);
  5070. return true;
  5071. });
  5072. ASSERT_TRUE(res);
  5073. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5075. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5076. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5077. "7890123456789012345678901234567890",
  5078. body);
  5079. EXPECT_EQ(StatusCode::OK_200, res->status);
  5080. }
  5081. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5082. Headers headers;
  5083. headers.emplace("Accept-Encoding", "zstd");
  5084. cli_.set_decompress(false);
  5085. auto res = cli_.Get("/compress", headers);
  5086. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5087. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5088. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5089. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5093. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. ASSERT_EQ(26U, res->body.size());
  5096. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5097. 0);
  5098. }
  5099. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5100. Headers headers;
  5101. headers.emplace("Accept-Encoding", "");
  5102. std::string body;
  5103. auto res = cli_.Get("/compress", headers,
  5104. [&](const char *data, uint64_t data_length) {
  5105. EXPECT_EQ(100U, data_length);
  5106. body.append(data, data_length);
  5107. return true;
  5108. });
  5109. ASSERT_TRUE(res);
  5110. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5111. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5112. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5113. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5114. "7890123456789012345678901234567890",
  5115. body);
  5116. EXPECT_EQ(StatusCode::OK_200, res->status);
  5117. }
  5118. TEST_F(ServerTest, NoZstd) {
  5119. Headers headers;
  5120. headers.emplace("Accept-Encoding", "zstd");
  5121. auto res = cli_.Get("/nocompress", headers);
  5122. ASSERT_TRUE(res);
  5123. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5124. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5125. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5126. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5127. "7890123456789012345678901234567890",
  5128. res->body);
  5129. EXPECT_EQ(StatusCode::OK_200, res->status);
  5130. }
  5131. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5132. Headers headers;
  5133. headers.emplace("Accept-Encoding", "zstd");
  5134. std::string body;
  5135. auto res = cli_.Get("/nocompress", headers,
  5136. [&](const char *data, uint64_t data_length) {
  5137. EXPECT_EQ(100U, data_length);
  5138. body.append(data, data_length);
  5139. return true;
  5140. });
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5143. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5144. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5145. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5146. "7890123456789012345678901234567890",
  5147. body);
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. // TODO: How to enable zstd ??
  5151. TEST_F(ServerTest, MultipartFormDataZstd) {
  5152. UploadFormDataItems items = {
  5153. {"key1", "test", "", ""},
  5154. {"key2", "--abcdefg123", "", ""},
  5155. };
  5156. Headers headers;
  5157. headers.emplace("Accept-Encoding", "zstd");
  5158. cli_.set_compress(true);
  5159. auto res = cli_.Post("/compress-multipart", headers, items);
  5160. ASSERT_TRUE(res);
  5161. EXPECT_EQ(StatusCode::OK_200, res->status);
  5162. }
  5163. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5164. Headers headers;
  5165. headers.emplace("Accept-Encoding", "zstd");
  5166. cli_.set_compress(true);
  5167. auto res = cli_.Put(
  5168. "/put", headers, 3,
  5169. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5170. sink.os << "PUT";
  5171. return true;
  5172. },
  5173. "text/plain");
  5174. ASSERT_TRUE(res);
  5175. EXPECT_EQ(StatusCode::OK_200, res->status);
  5176. EXPECT_EQ("PUT", res->body);
  5177. }
  5178. // Pre-compression logging tests
  5179. TEST_F(ServerTest, PreCompressionLogging) {
  5180. // Test data for compression (matches the actual /compress endpoint content)
  5181. const std::string test_content =
  5182. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5183. "3456789012345678901234567890";
  5184. // Variables to capture logging data
  5185. std::string pre_compression_body;
  5186. std::string pre_compression_content_type;
  5187. std::string pre_compression_content_encoding;
  5188. std::string post_compression_body;
  5189. std::string post_compression_content_type;
  5190. std::string post_compression_content_encoding;
  5191. // Set up pre-compression logger
  5192. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5193. const Response &res) {
  5194. pre_compression_body = res.body;
  5195. pre_compression_content_type = res.get_header_value("Content-Type");
  5196. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5197. });
  5198. // Set up post-compression logger
  5199. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5200. post_compression_body = res.body;
  5201. post_compression_content_type = res.get_header_value("Content-Type");
  5202. post_compression_content_encoding =
  5203. res.get_header_value("Content-Encoding");
  5204. });
  5205. // Test with gzip compression
  5206. Headers headers;
  5207. headers.emplace("Accept-Encoding", "gzip");
  5208. auto res = cli_.Get("/compress", headers);
  5209. // Verify response was compressed
  5210. ASSERT_TRUE(res);
  5211. EXPECT_EQ(StatusCode::OK_200, res->status);
  5212. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5213. // Verify pre-compression logger captured uncompressed content
  5214. EXPECT_EQ(test_content, pre_compression_body);
  5215. EXPECT_EQ("text/plain", pre_compression_content_type);
  5216. EXPECT_TRUE(pre_compression_content_encoding
  5217. .empty()); // No encoding header before compression
  5218. // Verify post-compression logger captured compressed content
  5219. EXPECT_NE(test_content,
  5220. post_compression_body); // Should be different after compression
  5221. EXPECT_EQ("text/plain", post_compression_content_type);
  5222. EXPECT_EQ("gzip", post_compression_content_encoding);
  5223. // Verify compressed content is smaller
  5224. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5225. }
  5226. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5227. const std::string test_content =
  5228. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5229. "3456789012345678901234567890";
  5230. std::string pre_compression_body;
  5231. std::string post_compression_body;
  5232. svr_.set_pre_compression_logger(
  5233. [&](const Request & /*req*/, const Response &res) {
  5234. pre_compression_body = res.body;
  5235. });
  5236. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5237. post_compression_body = res.body;
  5238. });
  5239. Headers headers;
  5240. headers.emplace("Accept-Encoding", "br");
  5241. auto res = cli_.Get("/compress", headers);
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5245. // Verify pre-compression content is uncompressed
  5246. EXPECT_EQ(test_content, pre_compression_body);
  5247. // Verify post-compression content is compressed
  5248. EXPECT_NE(test_content, post_compression_body);
  5249. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5250. }
  5251. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5252. const std::string test_content =
  5253. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5254. "3456789012345678901234567890";
  5255. std::string pre_compression_body;
  5256. std::string post_compression_body;
  5257. svr_.set_pre_compression_logger(
  5258. [&](const Request & /*req*/, const Response &res) {
  5259. pre_compression_body = res.body;
  5260. });
  5261. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5262. post_compression_body = res.body;
  5263. });
  5264. // Request without compression (use /nocompress endpoint)
  5265. Headers headers;
  5266. auto res = cli_.Get("/nocompress", headers);
  5267. ASSERT_TRUE(res);
  5268. EXPECT_EQ(StatusCode::OK_200, res->status);
  5269. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5270. // Pre-compression logger should not be called when no compression is applied
  5271. EXPECT_TRUE(
  5272. pre_compression_body.empty()); // Pre-compression logger not called
  5273. EXPECT_EQ(
  5274. test_content,
  5275. post_compression_body); // Post-compression logger captures final content
  5276. }
  5277. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5278. const std::string test_content =
  5279. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5280. "3456789012345678901234567890";
  5281. std::string pre_compression_body;
  5282. bool pre_logger_called = false;
  5283. // Set only pre-compression logger
  5284. svr_.set_pre_compression_logger(
  5285. [&](const Request & /*req*/, const Response &res) {
  5286. pre_compression_body = res.body;
  5287. pre_logger_called = true;
  5288. });
  5289. Headers headers;
  5290. headers.emplace("Accept-Encoding", "gzip");
  5291. auto res = cli_.Get("/compress", headers);
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5295. // Verify pre-compression logger was called
  5296. EXPECT_TRUE(pre_logger_called);
  5297. EXPECT_EQ(test_content, pre_compression_body);
  5298. }
  5299. TEST(ZstdDecompressor, ChunkedDecompression) {
  5300. std::string data;
  5301. for (size_t i = 0; i < 32 * 1024; ++i) {
  5302. data.push_back(static_cast<char>('a' + i % 26));
  5303. }
  5304. std::string compressed_data;
  5305. {
  5306. httplib::detail::zstd_compressor compressor;
  5307. bool result = compressor.compress(
  5308. data.data(), data.size(),
  5309. /*last=*/true,
  5310. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5311. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5312. compressed_data_size);
  5313. return true;
  5314. });
  5315. ASSERT_TRUE(result);
  5316. }
  5317. std::string decompressed_data;
  5318. {
  5319. httplib::detail::zstd_decompressor decompressor;
  5320. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5321. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5322. size_t chunk_size = 130;
  5323. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5324. chunk_begin += chunk_size) {
  5325. size_t current_chunk_size =
  5326. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5327. bool result = decompressor.decompress(
  5328. compressed_data.data() + chunk_begin, current_chunk_size,
  5329. [&](const char *decompressed_data_chunk,
  5330. size_t decompressed_data_chunk_size) {
  5331. decompressed_data.insert(decompressed_data.size(),
  5332. decompressed_data_chunk,
  5333. decompressed_data_chunk_size);
  5334. return true;
  5335. });
  5336. ASSERT_TRUE(result);
  5337. }
  5338. }
  5339. ASSERT_EQ(data, decompressed_data);
  5340. }
  5341. TEST(ZstdDecompressor, Decompress) {
  5342. std::string original_text = "Compressed with ZSTD";
  5343. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5344. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5345. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5346. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5347. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5348. std::string decompressed_data;
  5349. {
  5350. httplib::detail::zstd_decompressor decompressor;
  5351. bool result = decompressor.decompress(
  5352. compressed_data.data(), compressed_data.size(),
  5353. [&](const char *decompressed_data_chunk,
  5354. size_t decompressed_data_chunk_size) {
  5355. decompressed_data.insert(decompressed_data.size(),
  5356. decompressed_data_chunk,
  5357. decompressed_data_chunk_size);
  5358. return true;
  5359. });
  5360. ASSERT_TRUE(result);
  5361. }
  5362. ASSERT_EQ(original_text, decompressed_data);
  5363. }
  5364. #endif
  5365. // Sends a raw request to a server listening at HOST:PORT.
  5366. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5367. std::string *resp = nullptr) {
  5368. auto error = Error::Success;
  5369. auto client_sock = detail::create_client_socket(
  5370. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5371. /*connection_timeout_sec=*/5, 0,
  5372. /*read_timeout_sec=*/5, 0,
  5373. /*write_timeout_sec=*/5, 0, std::string(), error);
  5374. if (client_sock == INVALID_SOCKET) { return false; }
  5375. auto ret = detail::process_client_socket(
  5376. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5377. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5378. if (req.size() !=
  5379. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5380. return false;
  5381. }
  5382. char buf[512];
  5383. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5384. while (line_reader.getline()) {
  5385. if (resp) { *resp += line_reader.ptr(); }
  5386. }
  5387. return true;
  5388. });
  5389. detail::close_socket(client_sock);
  5390. return ret;
  5391. }
  5392. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5393. Server svr;
  5394. std::string header_value;
  5395. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5396. header_value = req.get_header_value("foo");
  5397. res.set_content("ok", "text/plain");
  5398. });
  5399. thread t = thread([&] { svr.listen(HOST, PORT); });
  5400. auto se = detail::scope_exit([&] {
  5401. svr.stop();
  5402. t.join();
  5403. ASSERT_FALSE(svr.is_running());
  5404. });
  5405. svr.wait_until_ready();
  5406. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5407. // like characters are not treated the same - use vertical tab and escape.
  5408. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5409. "foo: \t \v bar \x1B\t \r\n"
  5410. "Connection: close\r\n"
  5411. "\r\n";
  5412. std::string res;
  5413. ASSERT_TRUE(send_request(5, req, &res));
  5414. EXPECT_EQ(header_value, "");
  5415. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5416. }
  5417. // Sends a raw request and verifies that there isn't a crash or exception.
  5418. static void test_raw_request(const std::string &req,
  5419. std::string *out = nullptr) {
  5420. Server svr;
  5421. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5422. res.set_content("ok", "text/plain");
  5423. });
  5424. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5425. res.set_content("ok", "text/plain");
  5426. });
  5427. svr.Get("/header_field_value_check",
  5428. [&](const Request & /*req*/, Response &res) {
  5429. res.set_content("ok", "text/plain");
  5430. });
  5431. // Server read timeout must be longer than the client read timeout for the
  5432. // bug to reproduce, probably to force the server to process a request
  5433. // without a trailing blank line.
  5434. const time_t client_read_timeout_sec = 1;
  5435. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5436. bool listen_thread_ok = false;
  5437. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5438. auto se = detail::scope_exit([&] {
  5439. svr.stop();
  5440. t.join();
  5441. ASSERT_FALSE(svr.is_running());
  5442. EXPECT_TRUE(listen_thread_ok);
  5443. });
  5444. svr.wait_until_ready();
  5445. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5446. }
  5447. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5448. // A certain header line causes an exception if the header property is parsed
  5449. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5450. test_raw_request(
  5451. "GET /hi HTTP/1.1\r\n"
  5452. " : "
  5453. " "
  5454. " ");
  5455. }
  5456. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5457. // A certain header line causes an exception if the header property *name* is
  5458. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5459. // greedy matcher and requires backtracking when there are a lot of ":"
  5460. // characters.
  5461. // This occurs with libc++ but not libstdc++.
  5462. test_raw_request(
  5463. "GET /hi HTTP/1.1\r\n"
  5464. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5465. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5466. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5467. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5468. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5469. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5470. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5471. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5472. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5473. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5474. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5475. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5476. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5477. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5478. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5479. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5480. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5481. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5482. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5483. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5484. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5485. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5486. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5487. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5488. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5489. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5490. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5491. "&&&%%%");
  5492. }
  5493. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5494. // Make sure this doesn't crash the server.
  5495. // In a previous version of the header line regex, the "\r" rendered the line
  5496. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5497. // a new position where the leading white space ended and the field value
  5498. // began.
  5499. // The crash occurs with libc++ but not libstdc++.
  5500. test_raw_request("GET /hi HTTP/1.1\r\n"
  5501. "a:" +
  5502. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5503. "\r\n"
  5504. "\r\n");
  5505. }
  5506. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5507. std::string out;
  5508. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5509. "Content-Type: text/plain\r\n"
  5510. "Transfer-Encoding: chunked\r\n"
  5511. "\r\n"
  5512. "nothex\r\n",
  5513. &out);
  5514. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5515. }
  5516. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5517. std::string out;
  5518. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5519. "Content-Type: text/plain\r\n"
  5520. "Transfer-Encoding: chunked\r\n"
  5521. "\r\n"
  5522. "3\r\n"
  5523. "xyz\r\n"
  5524. "NaN\r\n",
  5525. &out);
  5526. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5527. }
  5528. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5529. std::string out;
  5530. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5531. "Content-Type: text/plain\r\n"
  5532. "Transfer-Encoding: chunked\r\n"
  5533. "\r\n"
  5534. // Length is too large for 64 bits.
  5535. "1ffffffffffffffff\r\n"
  5536. "xyz\r\n",
  5537. &out);
  5538. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5539. }
  5540. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5541. test_raw_request("GET /hi HTTP/1.1\r\n"
  5542. "Content-Type: text/plain\r\n\r");
  5543. }
  5544. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5545. std::string out;
  5546. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5547. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5548. }
  5549. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5550. std::string out;
  5551. std::string request(
  5552. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5553. test_raw_request(request, &out);
  5554. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5555. }
  5556. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5557. std::string out;
  5558. std::string request(
  5559. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5560. test_raw_request(request, &out);
  5561. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5562. }
  5563. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5564. std::string out;
  5565. std::string request(
  5566. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5567. test_raw_request(request, &out);
  5568. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5569. }
  5570. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5571. std::string out;
  5572. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5573. "Test: \r\n\r\n",
  5574. &out);
  5575. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5576. }
  5577. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5578. Server svr;
  5579. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5580. res.set_header("Cache-Control", "no-cache");
  5581. res.set_chunked_content_provider(
  5582. "text/event-stream", [](size_t offset, DataSink &sink) {
  5583. std::string s = "data:";
  5584. s += std::to_string(offset);
  5585. s += "\n\n";
  5586. auto ret = sink.write(s.data(), s.size());
  5587. EXPECT_TRUE(ret);
  5588. std::this_thread::sleep_for(std::chrono::seconds(1));
  5589. return true;
  5590. });
  5591. });
  5592. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5593. svr.wait_until_ready();
  5594. Client client(HOST, PORT);
  5595. const Headers headers = {{"Accept", "text/event-stream"}};
  5596. auto get_thread = std::thread([&client, &headers]() {
  5597. auto res = client.Get(
  5598. "/events", headers,
  5599. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5600. });
  5601. auto se = detail::scope_exit([&] {
  5602. svr.stop();
  5603. get_thread.join();
  5604. listen_thread.join();
  5605. ASSERT_FALSE(svr.is_running());
  5606. });
  5607. // Give GET time to get a few messages.
  5608. std::this_thread::sleep_for(std::chrono::seconds(2));
  5609. }
  5610. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5611. httplib::Server svr;
  5612. svr.Post("/hi",
  5613. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5614. res.status = StatusCode::OK_200;
  5615. });
  5616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5617. svr.wait_until_ready();
  5618. Client cli(HOST, PORT);
  5619. auto res = cli.Post("/hi", "data", "text/plain");
  5620. ASSERT_TRUE(res);
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. svr.stop();
  5623. thread.join();
  5624. ASSERT_FALSE(svr.is_running());
  5625. res = cli.Post("/hi", "data", "text/plain");
  5626. ASSERT_FALSE(res);
  5627. }
  5628. TEST(ServerStopTest, ListenFailure) {
  5629. Server svr;
  5630. auto t = thread([&]() {
  5631. auto ret = svr.listen("????", PORT);
  5632. EXPECT_FALSE(ret);
  5633. });
  5634. svr.wait_until_ready();
  5635. svr.stop();
  5636. t.join();
  5637. }
  5638. TEST(ServerStopTest, Decommision) {
  5639. Server svr;
  5640. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5641. for (int i = 0; i < 4; i++) {
  5642. auto is_even = !(i % 2);
  5643. std::thread t{[&] {
  5644. try {
  5645. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5646. if (is_even) {
  5647. throw std::runtime_error("Some thing that happens to go wrong.");
  5648. }
  5649. svr.listen(HOST, PORT);
  5650. } catch (...) { svr.decommission(); }
  5651. }};
  5652. svr.wait_until_ready();
  5653. // Server is up
  5654. {
  5655. Client cli(HOST, PORT);
  5656. auto res = cli.Get("/hi");
  5657. if (is_even) {
  5658. EXPECT_FALSE(res);
  5659. } else {
  5660. EXPECT_TRUE(res);
  5661. EXPECT_EQ("hi...", res->body);
  5662. }
  5663. }
  5664. svr.stop();
  5665. t.join();
  5666. // Server is down...
  5667. {
  5668. Client cli(HOST, PORT);
  5669. auto res = cli.Get("/hi");
  5670. EXPECT_FALSE(res);
  5671. }
  5672. }
  5673. }
  5674. // Helper function for string body upload progress tests
  5675. template <typename SetupHandler, typename ClientCall>
  5676. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5677. ClientCall &&client_call,
  5678. const string &body) {
  5679. Server svr;
  5680. setup_handler(svr);
  5681. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5682. auto se = detail::scope_exit([&] {
  5683. svr.stop();
  5684. t.join();
  5685. });
  5686. svr.wait_until_ready();
  5687. Client cli(HOST, PORT);
  5688. vector<uint64_t> progress_values;
  5689. bool progress_called = false;
  5690. auto res =
  5691. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5692. progress_values.push_back(current);
  5693. progress_called = true;
  5694. return true;
  5695. });
  5696. ASSERT_TRUE(res);
  5697. EXPECT_EQ(200, res->status);
  5698. EXPECT_TRUE(progress_called);
  5699. }
  5700. TEST(UploadProgressTest, PostStringBodyBasic) {
  5701. TestStringBodyUploadProgress(
  5702. [](Server &svr) {
  5703. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5704. res.set_content("received", "text/plain");
  5705. });
  5706. },
  5707. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5708. return cli.Post("/test", body, "text/plain", progress_callback);
  5709. },
  5710. "test data for upload progress");
  5711. }
  5712. TEST(UploadProgressTest, PutStringBodyBasic) {
  5713. TestStringBodyUploadProgress(
  5714. [](Server &svr) {
  5715. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5716. res.set_content("put received", "text/plain");
  5717. });
  5718. },
  5719. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5720. return cli.Put("/test", body, "text/plain", progress_callback);
  5721. },
  5722. "put test data for upload progress");
  5723. }
  5724. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5725. TestStringBodyUploadProgress(
  5726. [](Server &svr) {
  5727. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5728. res.set_content("patch received", "text/plain");
  5729. });
  5730. },
  5731. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5732. return cli.Patch("/test", body, "text/plain", progress_callback);
  5733. },
  5734. "patch test data for upload progress");
  5735. }
  5736. // Helper function for content provider upload progress tests
  5737. template <typename SetupHandler, typename ClientCall>
  5738. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5739. ClientCall &&client_call) {
  5740. Server svr;
  5741. setup_handler(svr);
  5742. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5743. auto se = detail::scope_exit([&] {
  5744. svr.stop();
  5745. t.join();
  5746. });
  5747. svr.wait_until_ready();
  5748. Client cli(HOST, PORT);
  5749. vector<uint64_t> progress_values;
  5750. auto res =
  5751. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5752. progress_values.push_back(current);
  5753. return true;
  5754. });
  5755. ASSERT_TRUE(res);
  5756. EXPECT_EQ(200, res->status);
  5757. EXPECT_FALSE(progress_values.empty());
  5758. }
  5759. TEST(UploadProgressTest, PostContentProviderProgress) {
  5760. TestContentProviderUploadProgress(
  5761. [](Server &svr) {
  5762. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5763. res.set_content("provider received", "text/plain");
  5764. });
  5765. },
  5766. [](Client &cli, UploadProgress progress_callback) {
  5767. return cli.Post(
  5768. "/test", 10,
  5769. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5770. sink.os << "test data";
  5771. return true;
  5772. },
  5773. "text/plain", progress_callback);
  5774. });
  5775. }
  5776. // Helper function for multipart upload progress tests
  5777. template <typename SetupHandler, typename ClientCall>
  5778. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5779. ClientCall &&client_call,
  5780. const string &endpoint) {
  5781. Server svr;
  5782. setup_handler(svr);
  5783. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5784. auto se = detail::scope_exit([&] {
  5785. svr.stop();
  5786. t.join();
  5787. });
  5788. svr.wait_until_ready();
  5789. Client cli(HOST, PORT);
  5790. vector<uint64_t> progress_values;
  5791. UploadFormDataItems items = {
  5792. {"field1", "value1", "", ""},
  5793. {"field2", "longer value for progress tracking test", "", ""},
  5794. {"file1", "file content data for upload progress", "test.txt",
  5795. "text/plain"}};
  5796. auto res = client_call(cli, endpoint, items,
  5797. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5798. progress_values.push_back(current);
  5799. return true;
  5800. });
  5801. ASSERT_TRUE(res);
  5802. EXPECT_EQ(200, res->status);
  5803. EXPECT_FALSE(progress_values.empty());
  5804. }
  5805. TEST(UploadProgressTest, PostMultipartProgress) {
  5806. TestMultipartUploadProgress(
  5807. [](Server &svr) {
  5808. svr.Post("/multipart", [](const Request &req, Response &res) {
  5809. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5810. res.set_content("multipart received", "text/plain");
  5811. });
  5812. },
  5813. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5814. UploadProgress progress_callback) {
  5815. return cli.Post(endpoint, items, progress_callback);
  5816. },
  5817. "/multipart");
  5818. }
  5819. // Helper function for basic download progress tests
  5820. template <typename SetupHandler, typename ClientCall>
  5821. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5822. ClientCall &&client_call, const string &endpoint,
  5823. size_t expected_content_size) {
  5824. Server svr;
  5825. setup_handler(svr);
  5826. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5827. auto se = detail::scope_exit([&] {
  5828. svr.stop();
  5829. t.join();
  5830. });
  5831. svr.wait_until_ready();
  5832. Client cli(HOST, PORT);
  5833. vector<uint64_t> progress_values;
  5834. auto res = client_call(cli, endpoint,
  5835. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5836. progress_values.push_back(current);
  5837. return true;
  5838. });
  5839. ASSERT_TRUE(res);
  5840. EXPECT_EQ(200, res->status);
  5841. EXPECT_FALSE(progress_values.empty());
  5842. EXPECT_EQ(expected_content_size, res->body.size());
  5843. }
  5844. TEST(DownloadProgressTest, GetBasic) {
  5845. TestBasicDownloadProgress(
  5846. [](Server &svr) {
  5847. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5848. string content(1000, 'D');
  5849. res.set_content(content, "text/plain");
  5850. });
  5851. },
  5852. [](Client &cli, const string &endpoint,
  5853. DownloadProgress progress_callback) {
  5854. return cli.Get(endpoint, progress_callback);
  5855. },
  5856. "/download", 1000u);
  5857. }
  5858. // Helper function for content receiver download progress tests
  5859. template <typename SetupHandler, typename ClientCall>
  5860. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5861. ClientCall &&client_call,
  5862. const string &endpoint,
  5863. size_t expected_content_size) {
  5864. Server svr;
  5865. setup_handler(svr);
  5866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5867. auto se = detail::scope_exit([&] {
  5868. svr.stop();
  5869. t.join();
  5870. });
  5871. svr.wait_until_ready();
  5872. Client cli(HOST, PORT);
  5873. vector<uint64_t> progress_values;
  5874. string received_body;
  5875. auto res = client_call(
  5876. cli, endpoint,
  5877. [&](const char *data, size_t data_length) -> bool {
  5878. received_body.append(data, data_length);
  5879. return true;
  5880. },
  5881. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5882. progress_values.push_back(current);
  5883. return true;
  5884. });
  5885. ASSERT_TRUE(res);
  5886. EXPECT_EQ(200, res->status);
  5887. EXPECT_FALSE(progress_values.empty());
  5888. EXPECT_EQ(expected_content_size, received_body.size());
  5889. EXPECT_TRUE(res->body.empty());
  5890. }
  5891. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5892. TestContentReceiverDownloadProgress(
  5893. [](Server &svr) {
  5894. svr.Get("/download-receiver",
  5895. [](const Request & /*req*/, Response &res) {
  5896. string content(2000, 'R');
  5897. res.set_content(content, "text/plain");
  5898. });
  5899. },
  5900. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5901. DownloadProgress progress_callback) {
  5902. return cli.Get(endpoint, content_receiver, progress_callback);
  5903. },
  5904. "/download-receiver", 2000u);
  5905. }
  5906. TEST(StreamingTest, NoContentLengthStreaming) {
  5907. Server svr;
  5908. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5909. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5910. if (offset < 6) {
  5911. sink.os << (offset < 3 ? "a" : "b");
  5912. } else {
  5913. sink.done();
  5914. }
  5915. return true;
  5916. });
  5917. });
  5918. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5919. auto listen_se = detail::scope_exit([&] {
  5920. svr.stop();
  5921. listen_thread.join();
  5922. ASSERT_FALSE(svr.is_running());
  5923. });
  5924. svr.wait_until_ready();
  5925. Client client(HOST, PORT);
  5926. auto get_thread = std::thread([&client]() {
  5927. std::string s;
  5928. auto res =
  5929. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5930. s += std::string(data, len);
  5931. return true;
  5932. });
  5933. ASSERT_TRUE(res);
  5934. EXPECT_EQ(StatusCode::OK_200, res->status);
  5935. EXPECT_EQ("aaabbb", s);
  5936. });
  5937. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5938. // Give GET time to get a few messages.
  5939. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5940. }
  5941. TEST(MountTest, Unmount) {
  5942. Server svr;
  5943. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5944. auto se = detail::scope_exit([&] {
  5945. svr.stop();
  5946. listen_thread.join();
  5947. ASSERT_FALSE(svr.is_running());
  5948. });
  5949. svr.wait_until_ready();
  5950. Client cli("localhost", PORT);
  5951. svr.set_mount_point("/mount2", "./www2");
  5952. auto res = cli.Get("/");
  5953. ASSERT_TRUE(res);
  5954. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5955. res = cli.Get("/mount2/dir/test.html");
  5956. ASSERT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::OK_200, res->status);
  5958. svr.set_mount_point("/", "./www");
  5959. res = cli.Get("/dir/");
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ(StatusCode::OK_200, res->status);
  5962. svr.remove_mount_point("/");
  5963. res = cli.Get("/dir/");
  5964. ASSERT_TRUE(res);
  5965. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5966. svr.remove_mount_point("/mount2");
  5967. res = cli.Get("/mount2/dir/test.html");
  5968. ASSERT_TRUE(res);
  5969. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5970. }
  5971. TEST(MountTest, Redicect) {
  5972. Server svr;
  5973. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5974. auto se = detail::scope_exit([&] {
  5975. svr.stop();
  5976. listen_thread.join();
  5977. ASSERT_FALSE(svr.is_running());
  5978. });
  5979. svr.set_mount_point("/", "./www");
  5980. svr.wait_until_ready();
  5981. Client cli("localhost", PORT);
  5982. auto res = cli.Get("/dir/");
  5983. ASSERT_TRUE(res);
  5984. EXPECT_EQ(StatusCode::OK_200, res->status);
  5985. res = cli.Get("/dir");
  5986. ASSERT_TRUE(res);
  5987. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5988. res = cli.Get("/file");
  5989. ASSERT_TRUE(res);
  5990. EXPECT_EQ(StatusCode::OK_200, res->status);
  5991. res = cli.Get("/file/");
  5992. ASSERT_TRUE(res);
  5993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5994. cli.set_follow_location(true);
  5995. res = cli.Get("/dir");
  5996. ASSERT_TRUE(res);
  5997. EXPECT_EQ(StatusCode::OK_200, res->status);
  5998. }
  5999. TEST(MountTest, MultibytesPathName) {
  6000. Server svr;
  6001. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6002. auto se = detail::scope_exit([&] {
  6003. svr.stop();
  6004. listen_thread.join();
  6005. ASSERT_FALSE(svr.is_running());
  6006. });
  6007. svr.set_mount_point("/", "./www");
  6008. svr.wait_until_ready();
  6009. Client cli("localhost", PORT);
  6010. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6011. ASSERT_TRUE(res);
  6012. EXPECT_EQ(StatusCode::OK_200, res->status);
  6013. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6014. }
  6015. TEST(KeepAliveTest, ReadTimeout) {
  6016. Server svr;
  6017. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6018. std::this_thread::sleep_for(std::chrono::seconds(2));
  6019. res.set_content("a", "text/plain");
  6020. });
  6021. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6022. res.set_content("b", "text/plain");
  6023. });
  6024. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6025. auto se = detail::scope_exit([&] {
  6026. svr.stop();
  6027. listen_thread.join();
  6028. ASSERT_FALSE(svr.is_running());
  6029. });
  6030. svr.wait_until_ready();
  6031. Client cli("localhost", PORT);
  6032. cli.set_keep_alive(true);
  6033. cli.set_read_timeout(std::chrono::seconds(1));
  6034. auto resa = cli.Get("/a");
  6035. ASSERT_FALSE(resa);
  6036. EXPECT_EQ(Error::Read, resa.error());
  6037. auto resb = cli.Get("/b");
  6038. ASSERT_TRUE(resb);
  6039. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6040. EXPECT_EQ("b", resb->body);
  6041. }
  6042. TEST(KeepAliveTest, MaxCount) {
  6043. size_t keep_alive_max_count = 3;
  6044. Server svr;
  6045. svr.set_keep_alive_max_count(keep_alive_max_count);
  6046. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6047. res.set_content("Hello World!", "text/plain");
  6048. });
  6049. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6050. auto se = detail::scope_exit([&] {
  6051. svr.stop();
  6052. listen_thread.join();
  6053. ASSERT_FALSE(svr.is_running());
  6054. });
  6055. svr.wait_until_ready();
  6056. Client cli(HOST, PORT);
  6057. cli.set_keep_alive(true);
  6058. for (size_t i = 0; i < 5; i++) {
  6059. auto result = cli.Get("/hi");
  6060. ASSERT_TRUE(result);
  6061. EXPECT_EQ(StatusCode::OK_200, result->status);
  6062. if (i == keep_alive_max_count - 1) {
  6063. EXPECT_EQ("close", result->get_header_value("Connection"));
  6064. } else {
  6065. EXPECT_FALSE(result->has_header("Connection"));
  6066. }
  6067. }
  6068. }
  6069. TEST(KeepAliveTest, Issue1041) {
  6070. Server svr;
  6071. svr.set_keep_alive_timeout(3);
  6072. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6073. res.set_content("Hello World!", "text/plain");
  6074. });
  6075. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6076. auto se = detail::scope_exit([&] {
  6077. svr.stop();
  6078. listen_thread.join();
  6079. ASSERT_FALSE(svr.is_running());
  6080. });
  6081. svr.wait_until_ready();
  6082. Client cli(HOST, PORT);
  6083. cli.set_keep_alive(true);
  6084. auto result = cli.Get("/hi");
  6085. ASSERT_TRUE(result);
  6086. EXPECT_EQ(StatusCode::OK_200, result->status);
  6087. std::this_thread::sleep_for(std::chrono::seconds(5));
  6088. result = cli.Get("/hi");
  6089. ASSERT_TRUE(result);
  6090. EXPECT_EQ(StatusCode::OK_200, result->status);
  6091. }
  6092. TEST(KeepAliveTest, Issue1959) {
  6093. Server svr;
  6094. svr.set_keep_alive_timeout(5);
  6095. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6096. res.set_content("a", "text/plain");
  6097. });
  6098. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6099. auto se = detail::scope_exit([&] {
  6100. if (!svr.is_running()) return;
  6101. svr.stop();
  6102. listen_thread.join();
  6103. ASSERT_FALSE(svr.is_running());
  6104. });
  6105. svr.wait_until_ready();
  6106. Client cli("localhost", PORT);
  6107. cli.set_keep_alive(true);
  6108. using namespace std::chrono;
  6109. auto start = steady_clock::now();
  6110. cli.Get("/a");
  6111. svr.stop();
  6112. listen_thread.join();
  6113. auto end = steady_clock::now();
  6114. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6115. EXPECT_LT(elapsed, 5000);
  6116. }
  6117. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6118. TEST(KeepAliveTest, SSLClientReconnection) {
  6119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6120. ASSERT_TRUE(svr.is_valid());
  6121. svr.set_keep_alive_timeout(1);
  6122. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6123. res.set_content("Hello World!", "text/plain");
  6124. });
  6125. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6126. auto se = detail::scope_exit([&] {
  6127. svr.stop();
  6128. listen_thread.join();
  6129. ASSERT_FALSE(svr.is_running());
  6130. });
  6131. svr.wait_until_ready();
  6132. SSLClient cli(HOST, PORT);
  6133. cli.enable_server_certificate_verification(false);
  6134. cli.set_keep_alive(true);
  6135. auto result = cli.Get("/hi");
  6136. ASSERT_TRUE(result);
  6137. EXPECT_EQ(StatusCode::OK_200, result->status);
  6138. result = cli.Get("/hi");
  6139. ASSERT_TRUE(result);
  6140. EXPECT_EQ(StatusCode::OK_200, result->status);
  6141. std::this_thread::sleep_for(std::chrono::seconds(2));
  6142. // Recoonect
  6143. result = cli.Get("/hi");
  6144. ASSERT_TRUE(result);
  6145. EXPECT_EQ(StatusCode::OK_200, result->status);
  6146. result = cli.Get("/hi");
  6147. ASSERT_TRUE(result);
  6148. EXPECT_EQ(StatusCode::OK_200, result->status);
  6149. }
  6150. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6152. ASSERT_TRUE(svr.is_valid());
  6153. svr.set_keep_alive_timeout(1);
  6154. std::string content = "reconnect";
  6155. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6156. res.set_content("Hello World!", "text/plain");
  6157. });
  6158. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6159. auto se = detail::scope_exit([&] {
  6160. svr.stop();
  6161. listen_thread.join();
  6162. ASSERT_FALSE(svr.is_running());
  6163. });
  6164. svr.wait_until_ready();
  6165. SSLClient cli(HOST, PORT);
  6166. cli.enable_server_certificate_verification(false);
  6167. cli.set_keep_alive(true);
  6168. auto result = cli.Post(
  6169. "/hi", content.size(),
  6170. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6171. sink.write(content.c_str(), content.size());
  6172. return true;
  6173. },
  6174. "text/plain");
  6175. ASSERT_TRUE(result);
  6176. EXPECT_EQ(200, result->status);
  6177. std::this_thread::sleep_for(std::chrono::seconds(2));
  6178. // Recoonect
  6179. result = cli.Post(
  6180. "/hi", content.size(),
  6181. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6182. sink.write(content.c_str(), content.size());
  6183. return true;
  6184. },
  6185. "text/plain");
  6186. ASSERT_TRUE(result);
  6187. EXPECT_EQ(200, result->status);
  6188. result = cli.Post(
  6189. "/hi", content.size(),
  6190. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6191. sink.write(content.c_str(), content.size());
  6192. return true;
  6193. },
  6194. "text/plain");
  6195. ASSERT_TRUE(result);
  6196. EXPECT_EQ(200, result->status);
  6197. }
  6198. #endif
  6199. TEST(ClientProblemDetectionTest, ContentProvider) {
  6200. Server svr;
  6201. size_t content_length = 1024 * 1024;
  6202. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6203. res.set_content_provider(
  6204. content_length, "text/plain",
  6205. [&](size_t offset, size_t length, DataSink &sink) {
  6206. auto out_len = std::min(length, static_cast<size_t>(1024));
  6207. std::string out(out_len, '@');
  6208. sink.write(out.data(), out_len);
  6209. return offset < 4096;
  6210. },
  6211. [](bool success) { ASSERT_FALSE(success); });
  6212. });
  6213. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6214. res.set_content_provider(
  6215. 0, "text/plain",
  6216. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6217. EXPECT_TRUE(false);
  6218. return true;
  6219. },
  6220. [](bool success) { ASSERT_FALSE(success); });
  6221. });
  6222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6223. auto se = detail::scope_exit([&] {
  6224. svr.stop();
  6225. listen_thread.join();
  6226. ASSERT_FALSE(svr.is_running());
  6227. });
  6228. svr.wait_until_ready();
  6229. Client cli("localhost", PORT);
  6230. {
  6231. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6232. size_t /*data_length*/) { return false; });
  6233. ASSERT_FALSE(res);
  6234. }
  6235. {
  6236. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6237. size_t /*data_length*/) { return false; });
  6238. ASSERT_TRUE(res);
  6239. }
  6240. }
  6241. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6242. Server svr;
  6243. svr.set_error_handler([](Request const &, Response &res) -> void {
  6244. res.set_chunked_content_provider(
  6245. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6246. sink.os << "hello";
  6247. sink.os << "world";
  6248. sink.done();
  6249. return true;
  6250. });
  6251. });
  6252. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6253. auto se = detail::scope_exit([&] {
  6254. svr.stop();
  6255. listen_thread.join();
  6256. ASSERT_FALSE(svr.is_running());
  6257. });
  6258. svr.wait_until_ready();
  6259. Client cli("localhost", PORT);
  6260. auto res = cli.Get("/");
  6261. ASSERT_TRUE(res);
  6262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6263. EXPECT_EQ("helloworld", res->body);
  6264. }
  6265. TEST(LongPollingTest, ClientCloseDetection) {
  6266. Server svr;
  6267. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6268. res.set_chunked_content_provider(
  6269. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6270. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6271. sink.os << "hello";
  6272. auto count = 10;
  6273. while (count > 0 && sink.is_writable()) {
  6274. this_thread::sleep_for(chrono::milliseconds(10));
  6275. count--;
  6276. }
  6277. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6278. return true;
  6279. });
  6280. });
  6281. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6282. auto se = detail::scope_exit([&] {
  6283. svr.stop();
  6284. listen_thread.join();
  6285. ASSERT_FALSE(svr.is_running());
  6286. });
  6287. svr.wait_until_ready();
  6288. Client cli("localhost", PORT);
  6289. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6290. EXPECT_EQ("hello", string(data, data_length));
  6291. return false; // close the socket immediately.
  6292. });
  6293. ASSERT_FALSE(res);
  6294. }
  6295. TEST(GetWithParametersTest, GetWithParameters) {
  6296. Server svr;
  6297. svr.Get("/", [&](const Request &req, Response &) {
  6298. EXPECT_EQ("world", req.get_param_value("hello"));
  6299. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6300. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6301. });
  6302. svr.Get("/params", [&](const Request &req, Response &) {
  6303. EXPECT_EQ("world", req.get_param_value("hello"));
  6304. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6305. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6306. });
  6307. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6308. EXPECT_EQ("resource-id", req.matches[1]);
  6309. EXPECT_EQ("foo", req.get_param_value("param1"));
  6310. EXPECT_EQ("bar", req.get_param_value("param2"));
  6311. });
  6312. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6313. EXPECT_EQ("user-id", req.path_params.at("id"));
  6314. EXPECT_EQ("foo", req.get_param_value("param1"));
  6315. EXPECT_EQ("bar", req.get_param_value("param2"));
  6316. });
  6317. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6318. auto se = detail::scope_exit([&] {
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. {
  6325. Client cli(HOST, PORT);
  6326. Params params;
  6327. params.emplace("hello", "world");
  6328. params.emplace("hello2", "world2");
  6329. params.emplace("hello3", "world3");
  6330. auto res = cli.Get("/", params, Headers{});
  6331. ASSERT_TRUE(res);
  6332. EXPECT_EQ(StatusCode::OK_200, res->status);
  6333. }
  6334. {
  6335. Client cli(HOST, PORT);
  6336. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6337. ASSERT_TRUE(res);
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. }
  6340. {
  6341. Client cli(HOST, PORT);
  6342. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6343. ASSERT_TRUE(res);
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. }
  6346. {
  6347. Client cli(HOST, PORT);
  6348. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6349. ASSERT_TRUE(res);
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. }
  6352. }
  6353. TEST(GetWithParametersTest, GetWithParameters2) {
  6354. Server svr;
  6355. svr.Get("/", [&](const Request &req, Response &res) {
  6356. auto text = req.get_param_value("hello");
  6357. res.set_content(text, "text/plain");
  6358. });
  6359. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6360. auto se = detail::scope_exit([&] {
  6361. svr.stop();
  6362. listen_thread.join();
  6363. ASSERT_FALSE(svr.is_running());
  6364. });
  6365. svr.wait_until_ready();
  6366. Client cli("localhost", PORT);
  6367. Params params;
  6368. params.emplace("hello", "world");
  6369. std::string body;
  6370. auto res = cli.Get("/", params, Headers{},
  6371. [&](const char *data, size_t data_length) {
  6372. body.append(data, data_length);
  6373. return true;
  6374. });
  6375. ASSERT_TRUE(res);
  6376. EXPECT_EQ(StatusCode::OK_200, res->status);
  6377. EXPECT_EQ("world", body);
  6378. }
  6379. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6380. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6381. auto host = "httpbin.org";
  6382. auto path = std::string{"/range/32"};
  6383. #else
  6384. auto host = "nghttp2.org";
  6385. auto path = std::string{"/httpbin/range/32"};
  6386. #endif
  6387. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6388. SSLClient cli(host);
  6389. #else
  6390. Client cli(host);
  6391. #endif
  6392. cli.set_default_headers({make_range_header({{1, 10}})});
  6393. cli.set_connection_timeout(5);
  6394. {
  6395. auto res = cli.Get(path);
  6396. ASSERT_TRUE(res);
  6397. EXPECT_EQ("bcdefghijk", res->body);
  6398. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6399. }
  6400. {
  6401. auto res = cli.Get(path);
  6402. ASSERT_TRUE(res);
  6403. EXPECT_EQ("bcdefghijk", res->body);
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. }
  6406. }
  6407. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6408. Server svr;
  6409. svr.set_default_headers({{"Hello", "World"}});
  6410. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6411. res.set_content("ok", "text/plain");
  6412. });
  6413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6414. auto se = detail::scope_exit([&] {
  6415. svr.stop();
  6416. listen_thread.join();
  6417. ASSERT_FALSE(svr.is_running());
  6418. });
  6419. svr.wait_until_ready();
  6420. Client cli("localhost", PORT);
  6421. auto res = cli.Get("/");
  6422. ASSERT_TRUE(res);
  6423. EXPECT_EQ(StatusCode::OK_200, res->status);
  6424. EXPECT_EQ("ok", res->body);
  6425. EXPECT_EQ("World", res->get_header_value("Hello"));
  6426. }
  6427. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6428. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6430. ASSERT_TRUE(svr.is_valid());
  6431. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6432. std::this_thread::sleep_for(std::chrono::seconds(2));
  6433. res.set_content("a", "text/plain");
  6434. });
  6435. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6436. res.set_content("b", "text/plain");
  6437. });
  6438. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6439. auto se = detail::scope_exit([&] {
  6440. svr.stop();
  6441. listen_thread.join();
  6442. ASSERT_FALSE(svr.is_running());
  6443. });
  6444. svr.wait_until_ready();
  6445. SSLClient cli("localhost", PORT);
  6446. cli.enable_server_certificate_verification(false);
  6447. cli.set_keep_alive(true);
  6448. cli.set_read_timeout(std::chrono::seconds(1));
  6449. auto resa = cli.Get("/a");
  6450. ASSERT_TRUE(!resa);
  6451. EXPECT_EQ(Error::Read, resa.error());
  6452. auto resb = cli.Get("/b");
  6453. ASSERT_TRUE(resb);
  6454. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6455. EXPECT_EQ("b", resb->body);
  6456. }
  6457. #endif
  6458. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6459. protected:
  6460. ServerTestWithAI_PASSIVE()
  6461. : cli_(HOST, PORT)
  6462. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6463. ,
  6464. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6465. #endif
  6466. {
  6467. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6468. cli_.enable_server_certificate_verification(false);
  6469. #endif
  6470. }
  6471. virtual void SetUp() {
  6472. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6473. res.set_content("Hello World!", "text/plain");
  6474. });
  6475. t_ = thread(
  6476. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6477. svr_.wait_until_ready();
  6478. }
  6479. virtual void TearDown() {
  6480. svr_.stop();
  6481. t_.join();
  6482. }
  6483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6484. SSLClient cli_;
  6485. SSLServer svr_;
  6486. #else
  6487. Client cli_;
  6488. Server svr_;
  6489. #endif
  6490. thread t_;
  6491. };
  6492. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6493. auto res = cli_.Get("/hi");
  6494. ASSERT_TRUE(res);
  6495. EXPECT_EQ(StatusCode::OK_200, res->status);
  6496. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6497. EXPECT_EQ("Hello World!", res->body);
  6498. }
  6499. class ServerUpDownTest : public ::testing::Test {
  6500. protected:
  6501. ServerUpDownTest() : cli_(HOST, PORT) {}
  6502. virtual void SetUp() {
  6503. t_ = thread([&]() {
  6504. svr_.bind_to_any_port(HOST);
  6505. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6506. ASSERT_TRUE(svr_.listen_after_bind());
  6507. });
  6508. svr_.wait_until_ready();
  6509. }
  6510. virtual void TearDown() {
  6511. svr_.stop();
  6512. t_.join();
  6513. }
  6514. Client cli_;
  6515. Server svr_;
  6516. thread t_;
  6517. };
  6518. TEST_F(ServerUpDownTest, QuickStartStop) {
  6519. // Should not crash, especially when run with
  6520. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6521. }
  6522. class PayloadMaxLengthTest : public ::testing::Test {
  6523. protected:
  6524. PayloadMaxLengthTest()
  6525. : cli_(HOST, PORT)
  6526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6527. ,
  6528. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6529. #endif
  6530. {
  6531. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6532. cli_.enable_server_certificate_verification(false);
  6533. #endif
  6534. }
  6535. virtual void SetUp() {
  6536. svr_.set_payload_max_length(8);
  6537. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6538. res.set_content("test", "text/plain");
  6539. });
  6540. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6541. svr_.wait_until_ready();
  6542. }
  6543. virtual void TearDown() {
  6544. svr_.stop();
  6545. t_.join();
  6546. }
  6547. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6548. SSLClient cli_;
  6549. SSLServer svr_;
  6550. #else
  6551. Client cli_;
  6552. Server svr_;
  6553. #endif
  6554. thread t_;
  6555. };
  6556. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6557. auto res = cli_.Post("/test", "123456789", "text/plain");
  6558. ASSERT_TRUE(res);
  6559. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6560. res = cli_.Post("/test", "12345678", "text/plain");
  6561. ASSERT_TRUE(res);
  6562. EXPECT_EQ(StatusCode::OK_200, res->status);
  6563. }
  6564. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6565. // Test chunked encoding with payload exceeding the 8-byte limit
  6566. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6567. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6568. ASSERT_TRUE(res);
  6569. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6570. }
  6571. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6572. // Test chunked encoding with payload within the 8-byte limit
  6573. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6574. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6575. ASSERT_TRUE(res);
  6576. EXPECT_EQ(StatusCode::OK_200, res->status);
  6577. }
  6578. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6579. // Test using send_request to send chunked data exceeding payload limit
  6580. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6581. "Host: " +
  6582. std::string(HOST) + ":" + std::to_string(PORT) +
  6583. "\r\n"
  6584. "Transfer-Encoding: chunked\r\n"
  6585. "Connection: close\r\n"
  6586. "\r\n"
  6587. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6588. "0123456789\r\n"
  6589. "0\r\n" // End chunk
  6590. "\r\n";
  6591. std::string response;
  6592. bool result = send_request(1, chunked_request, &response);
  6593. if (!result) {
  6594. // If send_request fails, it might be because the server closed the
  6595. // connection due to payload limit enforcement, which is acceptable
  6596. SUCCEED()
  6597. << "Server rejected oversized chunked request (connection closed)";
  6598. } else {
  6599. // If we got a response, check if it's an error response or connection was
  6600. // closed early Short response length indicates connection was closed due to
  6601. // payload limit
  6602. if (response.length() <= 10) {
  6603. SUCCEED() << "Server closed connection for oversized chunked request";
  6604. } else {
  6605. // Check for error status codes
  6606. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6607. response.find("Payload Too Large") != std::string::npos ||
  6608. response.find("400") != std::string::npos);
  6609. }
  6610. }
  6611. }
  6612. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6613. // Test request without Content-Length header exceeding payload limit
  6614. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6615. "Host: " +
  6616. std::string(HOST) + ":" +
  6617. std::to_string(PORT) +
  6618. "\r\n"
  6619. "Connection: close\r\n"
  6620. "\r\n";
  6621. // Add payload exceeding the 8-byte limit
  6622. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6623. request_without_content_length += large_payload;
  6624. std::string response;
  6625. bool result = send_request(1, request_without_content_length, &response);
  6626. if (!result) {
  6627. // If send_request fails, server likely closed connection due to payload
  6628. // limit
  6629. SUCCEED() << "Server rejected oversized request without Content-Length "
  6630. "(connection closed)";
  6631. } else {
  6632. // Check if server responded with error or closed connection early
  6633. if (response.length() <= 10) {
  6634. SUCCEED() << "Server closed connection for oversized request without "
  6635. "Content-Length";
  6636. } else {
  6637. // Check for error status codes
  6638. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6639. response.find("Payload Too Large") != std::string::npos ||
  6640. response.find("400") != std::string::npos);
  6641. }
  6642. }
  6643. }
  6644. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6645. // Test request without Content-Length header within payload limit
  6646. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6647. "Host: " +
  6648. std::string(HOST) + ":" +
  6649. std::to_string(PORT) +
  6650. "\r\n"
  6651. "Connection: close\r\n"
  6652. "\r\n";
  6653. // Add payload within the 8-byte limit
  6654. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6655. request_without_content_length += small_payload;
  6656. std::string response;
  6657. bool result = send_request(1, request_without_content_length, &response);
  6658. // For requests without Content-Length, the server may have different behavior
  6659. // The key is that it should not reject due to payload limit for small
  6660. // payloads
  6661. if (result) {
  6662. // Check for any HTTP response (success or error, but not connection closed)
  6663. if (response.length() > 10) {
  6664. SUCCEED()
  6665. << "Server processed request without Content-Length within limit";
  6666. } else {
  6667. // Short response might indicate connection closed, which is acceptable
  6668. SUCCEED() << "Server closed connection for request without "
  6669. "Content-Length (acceptable behavior)";
  6670. }
  6671. } else {
  6672. // Connection failure might be due to protocol requirements
  6673. SUCCEED() << "Connection issue with request without Content-Length "
  6674. "(environment-specific)";
  6675. }
  6676. }
  6677. class LargePayloadMaxLengthTest : public ::testing::Test {
  6678. protected:
  6679. LargePayloadMaxLengthTest()
  6680. : cli_(HOST, PORT)
  6681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6682. ,
  6683. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6684. #endif
  6685. {
  6686. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6687. cli_.enable_server_certificate_verification(false);
  6688. #endif
  6689. }
  6690. virtual void SetUp() {
  6691. // Set 10MB payload limit
  6692. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6693. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6694. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6695. res.set_content("Large payload test", "text/plain");
  6696. });
  6697. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6698. svr_.wait_until_ready();
  6699. }
  6700. virtual void TearDown() {
  6701. svr_.stop();
  6702. t_.join();
  6703. }
  6704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6705. SSLClient cli_;
  6706. SSLServer svr_;
  6707. #else
  6708. Client cli_;
  6709. Server svr_;
  6710. #endif
  6711. thread t_;
  6712. };
  6713. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6714. // Test chunked encoding with payload within 10MB limit
  6715. std::string medium_payload(5 * 1024 * 1024,
  6716. 'A'); // 5MB payload, within 10MB limit
  6717. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6718. ASSERT_TRUE(res);
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. }
  6721. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6722. // Test chunked encoding with payload exceeding 10MB limit
  6723. std::string large_payload(12 * 1024 * 1024,
  6724. 'B'); // 12MB payload, exceeds 10MB limit
  6725. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6726. ASSERT_TRUE(res);
  6727. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6728. }
  6729. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6730. // Test request without Content-Length header within 10MB limit
  6731. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6732. "Host: " +
  6733. std::string(HOST) + ":" +
  6734. std::to_string(PORT) +
  6735. "\r\n"
  6736. "Connection: close\r\n"
  6737. "\r\n";
  6738. // Add 1MB payload (within 10MB limit)
  6739. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6740. request_without_content_length += medium_payload;
  6741. std::string response;
  6742. bool result = send_request(5, request_without_content_length, &response);
  6743. if (result) {
  6744. // Should get a proper HTTP response for payloads within limit
  6745. if (response.length() > 10) {
  6746. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6747. "10MB limit";
  6748. } else {
  6749. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6750. "Content-Length)";
  6751. }
  6752. } else {
  6753. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6754. }
  6755. }
  6756. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6757. // Test request without Content-Length header exceeding 10MB limit
  6758. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6759. "Host: " +
  6760. std::string(HOST) + ":" +
  6761. std::to_string(PORT) +
  6762. "\r\n"
  6763. "Connection: close\r\n"
  6764. "\r\n";
  6765. // Add 12MB payload (exceeds 10MB limit)
  6766. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6767. request_without_content_length += large_payload;
  6768. std::string response;
  6769. bool result = send_request(10, request_without_content_length, &response);
  6770. if (!result) {
  6771. // Server should close connection due to payload limit
  6772. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6773. "(connection closed)";
  6774. } else {
  6775. // Check for error response
  6776. if (response.length() <= 10) {
  6777. SUCCEED()
  6778. << "Server closed connection for 12MB request exceeding 10MB limit";
  6779. } else {
  6780. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6781. response.find("Payload Too Large") != std::string::npos ||
  6782. response.find("400") != std::string::npos);
  6783. }
  6784. }
  6785. }
  6786. TEST(HostAndPortPropertiesTest, NoSSL) {
  6787. httplib::Client cli("www.google.com", 1234);
  6788. ASSERT_EQ("www.google.com", cli.host());
  6789. ASSERT_EQ(1234, cli.port());
  6790. }
  6791. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6792. httplib::Client cli("www.google.com:1234");
  6793. ASSERT_EQ("www.google.com", cli.host());
  6794. ASSERT_EQ(1234, cli.port());
  6795. }
  6796. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6797. TEST(HostAndPortPropertiesTest, SSL) {
  6798. httplib::SSLClient cli("www.google.com");
  6799. ASSERT_EQ("www.google.com", cli.host());
  6800. ASSERT_EQ(443, cli.port());
  6801. }
  6802. #endif
  6803. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6804. TEST(SSLClientTest, UpdateCAStore) {
  6805. httplib::SSLClient httplib_client("www.google.com");
  6806. auto ca_store_1 = X509_STORE_new();
  6807. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6808. nullptr);
  6809. httplib_client.set_ca_cert_store(ca_store_1);
  6810. auto ca_store_2 = X509_STORE_new();
  6811. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6812. nullptr);
  6813. httplib_client.set_ca_cert_store(ca_store_2);
  6814. }
  6815. TEST(SSLClientTest, ServerNameIndication_Online) {
  6816. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6817. auto host = "httpbin.org";
  6818. auto path = std::string{"/get"};
  6819. #else
  6820. auto host = "nghttp2.org";
  6821. auto path = std::string{"/httpbin/get"};
  6822. #endif
  6823. SSLClient cli(host, 443);
  6824. auto res = cli.Get(path);
  6825. ASSERT_TRUE(res);
  6826. ASSERT_EQ(StatusCode::OK_200, res->status);
  6827. }
  6828. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6829. // Use a site that will cause SSL verification failure due to self-signed cert
  6830. SSLClient cli("self-signed.badssl.com", 443);
  6831. cli.enable_server_certificate_verification(true);
  6832. auto res = cli.Get("/");
  6833. ASSERT_TRUE(!res);
  6834. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6835. // For SSL server verification errors, ssl_error should be 0, only
  6836. // ssl_openssl_error should be set
  6837. EXPECT_EQ(0, res.ssl_error());
  6838. // Verify OpenSSL error is captured for SSLServerVerification
  6839. // This occurs when SSL_get_verify_result() returns a verification failure
  6840. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6841. res.ssl_openssl_error());
  6842. }
  6843. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6844. // Use a site where hostname doesn't match the certificate
  6845. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6846. SSLClient cli("wrong.host.badssl.com", 443);
  6847. cli.enable_server_certificate_verification(true);
  6848. cli.enable_server_hostname_verification(true);
  6849. auto res = cli.Get("/");
  6850. ASSERT_TRUE(!res);
  6851. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6852. // For SSL hostname verification errors, ssl_error should be 0, only
  6853. // ssl_openssl_error should be set
  6854. EXPECT_EQ(0, res.ssl_error());
  6855. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6856. // This occurs when verify_host() fails due to hostname mismatch
  6857. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6858. res.ssl_openssl_error());
  6859. }
  6860. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6861. Client cli("https://google.com");
  6862. auto res = cli.Get("/");
  6863. ASSERT_TRUE(res);
  6864. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6865. }
  6866. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6867. SSLClient cli("google.com");
  6868. cli.set_ca_cert_path(CA_CERT_FILE);
  6869. auto res = cli.Get("/");
  6870. ASSERT_TRUE(res);
  6871. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6872. }
  6873. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6874. SSLClient cli("google.com");
  6875. cli.enable_server_certificate_verification(true);
  6876. cli.set_ca_cert_path("hello");
  6877. auto res = cli.Get("/");
  6878. ASSERT_TRUE(!res);
  6879. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6880. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6881. // should be set
  6882. EXPECT_EQ(0, res.ssl_error());
  6883. // Verify OpenSSL error is captured for SSLLoadingCerts
  6884. // This error occurs when SSL_CTX_load_verify_locations() fails
  6885. // > openssl errstr 0x80000002
  6886. // error:80000002:system library::No such file or directory
  6887. // > openssl errstr 0xA000126
  6888. // error:0A000126:SSL routines::unexpected eof while reading
  6889. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6890. res.ssl_openssl_error() == 0xA000126);
  6891. }
  6892. TEST(SSLClientTest, ServerCertificateVerification4) {
  6893. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6894. ASSERT_TRUE(svr.is_valid());
  6895. svr.Get("/test", [&](const Request &, Response &res) {
  6896. res.set_content("test", "text/plain");
  6897. svr.stop();
  6898. ASSERT_TRUE(true);
  6899. });
  6900. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6901. auto se = detail::scope_exit([&] {
  6902. t.join();
  6903. ASSERT_FALSE(svr.is_running());
  6904. });
  6905. svr.wait_until_ready();
  6906. SSLClient cli("127.0.0.1", PORT);
  6907. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6908. cli.enable_server_certificate_verification(true);
  6909. cli.set_connection_timeout(30);
  6910. auto res = cli.Get("/test");
  6911. ASSERT_TRUE(res);
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. }
  6914. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6915. std::string cert;
  6916. read_file(CA_CERT_FILE, cert);
  6917. SSLClient cli("google.com");
  6918. cli.load_ca_cert_store(cert.data(), cert.size());
  6919. const auto res = cli.Get("/");
  6920. ASSERT_TRUE(res);
  6921. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6922. }
  6923. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6924. // clang-format off
  6925. static constexpr char cert[] =
  6926. "GlobalSign Root CA\n"
  6927. "==================\n"
  6928. "-----BEGIN CERTIFICATE-----\n"
  6929. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6930. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6931. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6932. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6933. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6934. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6935. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6936. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6937. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6938. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6939. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  6940. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  6941. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  6942. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  6943. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  6944. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  6945. "-----END CERTIFICATE-----\n";
  6946. // clang-format on
  6947. SSLClient cli("google.com");
  6948. cli.load_ca_cert_store(cert, sizeof(cert));
  6949. const auto res = cli.Get("/");
  6950. ASSERT_TRUE(res);
  6951. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6952. }
  6953. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  6954. SSLClient cli("www.youtube.com");
  6955. cli.set_ca_cert_path(CA_CERT_FILE);
  6956. cli.enable_server_certificate_verification(true);
  6957. cli.set_follow_location(true);
  6958. auto res = cli.Get("/");
  6959. ASSERT_TRUE(res);
  6960. ASSERT_EQ(StatusCode::OK_200, res->status);
  6961. }
  6962. TEST(SSLClientTest, Issue2004_Online) {
  6963. Client client("https://google.com");
  6964. client.set_follow_location(true);
  6965. auto res = client.Get("/");
  6966. ASSERT_TRUE(res);
  6967. ASSERT_EQ(StatusCode::OK_200, res->status);
  6968. auto body = res->body;
  6969. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  6970. }
  6971. #if 0
  6972. TEST(SSLClientTest, SetInterfaceWithINET6) {
  6973. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  6974. ASSERT_TRUE(cli != nullptr);
  6975. cli->set_address_family(AF_INET6);
  6976. cli->set_interface("en0");
  6977. auto res = cli->Get("/get");
  6978. ASSERT_TRUE(res);
  6979. ASSERT_EQ(StatusCode::OK_200, res->status);
  6980. }
  6981. #endif
  6982. void ClientCertPresent(
  6983. const std::string &client_cert_file,
  6984. const std::string &client_private_key_file,
  6985. const std::string &client_encrypted_private_key_pass = std::string()) {
  6986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  6987. CLIENT_CA_CERT_DIR);
  6988. ASSERT_TRUE(svr.is_valid());
  6989. svr.Get("/test", [&](const Request &req, Response &res) {
  6990. res.set_content("test", "text/plain");
  6991. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  6992. ASSERT_TRUE(peer_cert != nullptr);
  6993. auto subject_name = X509_get_subject_name(peer_cert);
  6994. ASSERT_TRUE(subject_name != nullptr);
  6995. std::string common_name;
  6996. {
  6997. char name[BUFSIZ];
  6998. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  6999. name, sizeof(name));
  7000. common_name.assign(name, static_cast<size_t>(name_len));
  7001. }
  7002. EXPECT_EQ("Common Name", common_name);
  7003. X509_free(peer_cert);
  7004. });
  7005. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7006. auto se = detail::scope_exit([&] {
  7007. svr.stop();
  7008. t.join();
  7009. ASSERT_FALSE(svr.is_running());
  7010. });
  7011. svr.wait_until_ready();
  7012. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7013. client_encrypted_private_key_pass);
  7014. cli.enable_server_certificate_verification(false);
  7015. cli.set_connection_timeout(30);
  7016. auto res = cli.Get("/test");
  7017. ASSERT_TRUE(res);
  7018. ASSERT_EQ(StatusCode::OK_200, res->status);
  7019. }
  7020. TEST(SSLClientServerTest, ClientCertPresent) {
  7021. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7022. }
  7023. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7024. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7025. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7026. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7027. }
  7028. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7029. void MemoryClientCertPresent(
  7030. const std::string &client_cert_file,
  7031. const std::string &client_private_key_file,
  7032. const std::string &client_encrypted_private_key_pass = std::string()) {
  7033. auto f = fopen(SERVER_CERT_FILE, "r+");
  7034. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7035. fclose(f);
  7036. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7037. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7038. fclose(f);
  7039. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7040. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7041. auto client_ca_cert_store = X509_STORE_new();
  7042. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7043. X509_free(client_cert);
  7044. fclose(f);
  7045. f = fopen(client_cert_file.c_str(), "r+");
  7046. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7047. fclose(f);
  7048. f = fopen(client_private_key_file.c_str(), "r+");
  7049. auto client_private_key = PEM_read_PrivateKey(
  7050. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7051. fclose(f);
  7052. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7053. ASSERT_TRUE(svr.is_valid());
  7054. svr.Get("/test", [&](const Request &req, Response &res) {
  7055. res.set_content("test", "text/plain");
  7056. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7057. ASSERT_TRUE(peer_cert != nullptr);
  7058. auto subject_name = X509_get_subject_name(peer_cert);
  7059. ASSERT_TRUE(subject_name != nullptr);
  7060. std::string common_name;
  7061. {
  7062. char name[BUFSIZ];
  7063. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7064. name, sizeof(name));
  7065. common_name.assign(name, static_cast<size_t>(name_len));
  7066. }
  7067. EXPECT_EQ("Common Name", common_name);
  7068. X509_free(peer_cert);
  7069. });
  7070. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7071. auto se = detail::scope_exit([&] {
  7072. svr.stop();
  7073. t.join();
  7074. ASSERT_FALSE(svr.is_running());
  7075. });
  7076. svr.wait_until_ready();
  7077. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7078. client_encrypted_private_key_pass);
  7079. cli.enable_server_certificate_verification(false);
  7080. cli.set_connection_timeout(30);
  7081. auto res = cli.Get("/test");
  7082. ASSERT_TRUE(res);
  7083. ASSERT_EQ(StatusCode::OK_200, res->status);
  7084. X509_free(server_cert);
  7085. EVP_PKEY_free(server_private_key);
  7086. X509_free(client_cert);
  7087. EVP_PKEY_free(client_private_key);
  7088. }
  7089. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7090. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7091. }
  7092. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7093. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7094. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7095. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7096. }
  7097. #endif
  7098. TEST(SSLClientServerTest, ClientCertMissing) {
  7099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7100. CLIENT_CA_CERT_DIR);
  7101. ASSERT_TRUE(svr.is_valid());
  7102. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7103. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7104. auto se = detail::scope_exit([&] {
  7105. svr.stop();
  7106. t.join();
  7107. ASSERT_FALSE(svr.is_running());
  7108. });
  7109. svr.wait_until_ready();
  7110. SSLClient cli(HOST, PORT);
  7111. cli.set_connection_timeout(30);
  7112. auto res = cli.Get("/test");
  7113. ASSERT_TRUE(!res);
  7114. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7115. // For SSL server verification errors, ssl_error should be 0, only
  7116. // ssl_openssl_error should be set
  7117. EXPECT_EQ(0, res.ssl_error());
  7118. // Verify OpenSSL error is captured for SSLServerVerification
  7119. // Note: This test may have different error codes depending on the exact
  7120. // verification failure
  7121. EXPECT_NE(0UL, res.ssl_openssl_error());
  7122. }
  7123. TEST(SSLClientServerTest, TrustDirOptional) {
  7124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7125. ASSERT_TRUE(svr.is_valid());
  7126. svr.Get("/test", [&](const Request &, Response &res) {
  7127. res.set_content("test", "text/plain");
  7128. });
  7129. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7130. auto se = detail::scope_exit([&] {
  7131. svr.stop();
  7132. t.join();
  7133. ASSERT_FALSE(svr.is_running());
  7134. });
  7135. svr.wait_until_ready();
  7136. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7137. cli.enable_server_certificate_verification(false);
  7138. cli.set_connection_timeout(30);
  7139. auto res = cli.Get("/test");
  7140. ASSERT_TRUE(res);
  7141. ASSERT_EQ(StatusCode::OK_200, res->status);
  7142. }
  7143. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7144. class NoListenSSLServer : public SSLServer {
  7145. public:
  7146. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7147. const char *client_ca_cert_file_path,
  7148. const char *client_ca_cert_dir_path = nullptr)
  7149. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7150. client_ca_cert_dir_path),
  7151. stop_(false) {}
  7152. std::atomic_bool stop_;
  7153. private:
  7154. bool process_and_close_socket(socket_t /*sock*/) override {
  7155. // Don't create SSL context
  7156. while (!stop_.load()) {
  7157. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7158. }
  7159. return true;
  7160. }
  7161. };
  7162. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7163. CLIENT_CA_CERT_FILE);
  7164. ASSERT_TRUE(svr.is_valid());
  7165. svr.Get("/test", [&](const Request &, Response &res) {
  7166. res.set_content("test", "text/plain");
  7167. });
  7168. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7169. auto se = detail::scope_exit([&] {
  7170. svr.stop_ = true;
  7171. svr.stop();
  7172. t.join();
  7173. ASSERT_FALSE(svr.is_running());
  7174. });
  7175. svr.wait_until_ready();
  7176. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7177. cli.enable_server_certificate_verification(false);
  7178. cli.set_connection_timeout(1);
  7179. auto res = cli.Get("/test");
  7180. ASSERT_TRUE(!res);
  7181. EXPECT_EQ(Error::SSLConnection, res.error());
  7182. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7183. }
  7184. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7185. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7186. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7187. SSL_CTX_set_options(&ssl_ctx,
  7188. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7189. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7190. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7191. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7192. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7193. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7194. "ECDHE-DSS-AES128-SHA256:"
  7195. "ECDHE-RSA-AES256-SHA256:"
  7196. "ECDHE-DSS-AES256-SHA256:";
  7197. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7198. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7199. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7200. SSL_FILETYPE_PEM) != 1) {
  7201. return false;
  7202. }
  7203. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7204. CLIENT_CA_CERT_DIR);
  7205. SSL_CTX_set_verify(
  7206. &ssl_ctx,
  7207. SSL_VERIFY_PEER |
  7208. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7209. nullptr);
  7210. return true;
  7211. };
  7212. SSLServer svr(setup_ssl_ctx_callback);
  7213. ASSERT_TRUE(svr.is_valid());
  7214. svr.Get("/test", [&](const Request &req, Response &res) {
  7215. res.set_content("test", "text/plain");
  7216. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7217. ASSERT_TRUE(peer_cert != nullptr);
  7218. auto subject_name = X509_get_subject_name(peer_cert);
  7219. ASSERT_TRUE(subject_name != nullptr);
  7220. std::string common_name;
  7221. {
  7222. char name[BUFSIZ];
  7223. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7224. name, sizeof(name));
  7225. common_name.assign(name, static_cast<size_t>(name_len));
  7226. }
  7227. EXPECT_EQ("Common Name", common_name);
  7228. X509_free(peer_cert);
  7229. });
  7230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7231. auto se = detail::scope_exit([&] {
  7232. svr.stop();
  7233. t.join();
  7234. ASSERT_FALSE(svr.is_running());
  7235. });
  7236. svr.wait_until_ready();
  7237. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7238. cli.enable_server_certificate_verification(false);
  7239. cli.set_connection_timeout(30);
  7240. auto res = cli.Get("/test");
  7241. ASSERT_TRUE(res);
  7242. ASSERT_EQ(StatusCode::OK_200, res->status);
  7243. }
  7244. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7245. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7246. // prepare large data
  7247. std::random_device seed_gen;
  7248. std::mt19937 random(seed_gen());
  7249. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7250. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7251. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7252. // server
  7253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7254. ASSERT_TRUE(svr.is_valid());
  7255. svr.Post("/binary", [&](const Request &req, Response &res) {
  7256. EXPECT_EQ(large_size_byte, req.body.size());
  7257. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7258. res.set_content(req.body, "application/octet-stream");
  7259. });
  7260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7261. auto se = detail::scope_exit([&] {
  7262. svr.stop();
  7263. listen_thread.join();
  7264. ASSERT_FALSE(svr.is_running());
  7265. });
  7266. svr.wait_until_ready();
  7267. // client POST
  7268. SSLClient cli("localhost", PORT);
  7269. cli.enable_server_certificate_verification(false);
  7270. cli.set_read_timeout(std::chrono::seconds(100));
  7271. cli.set_write_timeout(std::chrono::seconds(100));
  7272. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7273. large_size_byte, "application/octet-stream");
  7274. // compare
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. EXPECT_EQ(large_size_byte, res->body.size());
  7277. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7278. }
  7279. #endif
  7280. #ifdef _WIN32
  7281. TEST(CleanupTest, WSACleanup) {
  7282. int ret = WSACleanup();
  7283. ASSERT_EQ(0, ret);
  7284. }
  7285. #endif
  7286. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7287. TEST(NoSSLSupport, SimpleInterface) {
  7288. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7289. }
  7290. #endif
  7291. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7292. TEST(InvalidScheme, SimpleInterface) {
  7293. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7294. }
  7295. #endif
  7296. TEST(NoScheme, SimpleInterface) {
  7297. Client cli("yahoo.com:80");
  7298. ASSERT_TRUE(cli.is_valid());
  7299. }
  7300. TEST(SendAPI, SimpleInterface_Online) {
  7301. Client cli("http://yahoo.com");
  7302. Request req;
  7303. req.method = "GET";
  7304. req.path = "/";
  7305. auto res = cli.send(req);
  7306. ASSERT_TRUE(res);
  7307. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7308. }
  7309. TEST(SendAPI, WithParamsInRequest) {
  7310. Server svr;
  7311. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7312. EXPECT_TRUE(req.has_param("test"));
  7313. EXPECT_EQ("test_value", req.get_param_value("test"));
  7314. });
  7315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7316. auto se = detail::scope_exit([&] {
  7317. svr.stop();
  7318. t.join();
  7319. ASSERT_FALSE(svr.is_running());
  7320. });
  7321. svr.wait_until_ready();
  7322. Client cli(HOST, PORT);
  7323. {
  7324. Request req;
  7325. req.method = "GET";
  7326. req.path = "/";
  7327. req.params.emplace("test", "test_value");
  7328. auto res = cli.send(req);
  7329. ASSERT_TRUE(res);
  7330. }
  7331. {
  7332. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7333. ASSERT_TRUE(res);
  7334. }
  7335. }
  7336. TEST(ClientImplMethods, GetSocketTest) {
  7337. httplib::Server svr;
  7338. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7339. res.status = StatusCode::OK_200;
  7340. });
  7341. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7342. auto se = detail::scope_exit([&] {
  7343. svr.stop();
  7344. thread.join();
  7345. ASSERT_FALSE(svr.is_running());
  7346. });
  7347. svr.wait_until_ready();
  7348. {
  7349. httplib::Client cli("http://127.0.0.1:3333");
  7350. cli.set_keep_alive(true);
  7351. // Use the behavior of cpp-httplib of opening the connection
  7352. // only when the first request happens. If that changes,
  7353. // this test would be obsolete.
  7354. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7355. // This also implicitly tests the server. But other tests would fail much
  7356. // earlier than this one to be considered.
  7357. auto res = cli.Get("/");
  7358. ASSERT_TRUE(res);
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7361. }
  7362. }
  7363. // Disabled due to out-of-memory problem on GitHub Actions
  7364. #ifdef _WIN64
  7365. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7366. // allocate content size larger than 2GB in memory
  7367. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7368. char *content = (char *)malloc(content_size);
  7369. ASSERT_TRUE(content);
  7370. Server svr;
  7371. svr.Get("/foo",
  7372. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7373. res.set_content(content, content_size, "application/octet-stream");
  7374. });
  7375. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7376. auto se = detail::scope_exit([&] {
  7377. svr.stop();
  7378. listen_thread.join();
  7379. if (content) free(content);
  7380. ASSERT_FALSE(svr.is_running());
  7381. });
  7382. svr.wait_until_ready();
  7383. Client cli(HOST, PORT);
  7384. auto res = cli.Get("/foo");
  7385. ASSERT_TRUE(res);
  7386. EXPECT_EQ(StatusCode::OK_200, res->status);
  7387. EXPECT_EQ(content_size, res->body.length());
  7388. }
  7389. #endif
  7390. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7391. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7392. Client cli("http://yahoo.com");
  7393. auto res = cli.Get("/");
  7394. ASSERT_TRUE(res);
  7395. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7396. cli.set_follow_location(true);
  7397. res = cli.Get("/");
  7398. ASSERT_TRUE(res);
  7399. EXPECT_EQ(StatusCode::OK_200, res->status);
  7400. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7401. }
  7402. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7403. Client cli("https://yahoo.com");
  7404. auto res = cli.Get("/");
  7405. ASSERT_TRUE(res);
  7406. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7407. cli.set_follow_location(true);
  7408. res = cli.Get("/");
  7409. ASSERT_TRUE(res);
  7410. EXPECT_EQ(StatusCode::OK_200, res->status);
  7411. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7412. }
  7413. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7414. Client cli("https://yahoo.com");
  7415. auto res = cli.Get("/");
  7416. ASSERT_TRUE(res);
  7417. ASSERT_FALSE(!res);
  7418. ASSERT_TRUE(res);
  7419. ASSERT_FALSE(res == nullptr);
  7420. ASSERT_TRUE(res != nullptr);
  7421. EXPECT_EQ(Error::Success, res.error());
  7422. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7423. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7424. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7425. cli.set_follow_location(true);
  7426. res = cli.Get("/");
  7427. ASSERT_TRUE(res);
  7428. EXPECT_EQ(Error::Success, res.error());
  7429. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7430. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7433. }
  7434. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7435. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7436. Client cli("https://cdnjs.cloudflare.com");
  7437. auto res =
  7438. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7439. ASSERT_TRUE(res);
  7440. EXPECT_EQ(StatusCode::OK_200, res->status);
  7441. EXPECT_EQ(287630U, res->body.size());
  7442. EXPECT_EQ("application/javascript; charset=utf-8",
  7443. res->get_header_value("Content-Type"));
  7444. }
  7445. #endif
  7446. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7447. #undef REDIR_HOST // Silence compiler warning
  7448. #define REDIR_HOST "https://httpbingo.org"
  7449. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7450. Client cli(REDIR_HOST);
  7451. cli.set_follow_location(true);
  7452. auto res =
  7453. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7454. ASSERT_TRUE(res);
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. }
  7457. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7458. Client cli(REDIR_HOST);
  7459. cli.set_follow_location(true);
  7460. Params params;
  7461. params.emplace("url", "http://example.com");
  7462. params.emplace("status_code", "302");
  7463. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7464. ASSERT_TRUE(res);
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. }
  7467. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7468. Client cli(REDIR_HOST);
  7469. cli.set_follow_location(true);
  7470. Params params;
  7471. params.emplace("url", "http://example.com");
  7472. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7473. ASSERT_TRUE(res);
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. }
  7476. TEST(HttpToHttpsRedirectTest, CertFile) {
  7477. Server svr;
  7478. ASSERT_TRUE(svr.is_valid());
  7479. svr.Get("/index", [&](const Request &, Response &res) {
  7480. res.set_redirect("https://127.0.0.1:1235/index");
  7481. svr.stop();
  7482. });
  7483. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7484. ASSERT_TRUE(ssl_svr.is_valid());
  7485. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7486. res.set_content("test", "text/plain");
  7487. ssl_svr.stop();
  7488. });
  7489. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7490. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7491. auto se = detail::scope_exit([&] {
  7492. t2.join();
  7493. t.join();
  7494. ASSERT_FALSE(svr.is_running());
  7495. });
  7496. svr.wait_until_ready();
  7497. ssl_svr.wait_until_ready();
  7498. Client cli("127.0.0.1", PORT);
  7499. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7500. cli.enable_server_certificate_verification(true);
  7501. cli.set_follow_location(true);
  7502. cli.set_connection_timeout(30);
  7503. auto res = cli.Get("/index");
  7504. ASSERT_TRUE(res);
  7505. ASSERT_EQ(StatusCode::OK_200, res->status);
  7506. }
  7507. TEST(MultipartFormDataTest, LargeData) {
  7508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7509. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7510. const ContentReader &content_reader) {
  7511. if (req.is_multipart_form_data()) {
  7512. std::vector<FormData> items;
  7513. content_reader(
  7514. [&](const FormData &file) {
  7515. items.push_back(file);
  7516. return true;
  7517. },
  7518. [&](const char *data, size_t data_length) {
  7519. items.back().content.append(data, data_length);
  7520. return true;
  7521. });
  7522. EXPECT_TRUE(std::string(items[0].name) == "document");
  7523. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7524. EXPECT_TRUE(items[0].filename == "2MB_data");
  7525. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7526. EXPECT_TRUE(items[1].name == "hello");
  7527. EXPECT_TRUE(items[1].content == "world");
  7528. EXPECT_TRUE(items[1].filename == "");
  7529. EXPECT_TRUE(items[1].content_type == "");
  7530. } else {
  7531. std::string body;
  7532. content_reader([&](const char *data, size_t data_length) {
  7533. body.append(data, data_length);
  7534. return true;
  7535. });
  7536. }
  7537. });
  7538. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7539. auto se = detail::scope_exit([&] {
  7540. svr.stop();
  7541. t.join();
  7542. ASSERT_FALSE(svr.is_running());
  7543. });
  7544. svr.wait_until_ready();
  7545. {
  7546. std::string data(1024 * 1024 * 2, '.');
  7547. std::stringstream buffer;
  7548. buffer << data;
  7549. Client cli("https://localhost:8080");
  7550. cli.enable_server_certificate_verification(false);
  7551. UploadFormDataItems items{
  7552. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7553. {"hello", "world", "", ""},
  7554. };
  7555. auto res = cli.Post("/post", items);
  7556. ASSERT_TRUE(res);
  7557. ASSERT_EQ(StatusCode::OK_200, res->status);
  7558. }
  7559. }
  7560. TEST(MultipartFormDataTest, DataProviderItems) {
  7561. std::random_device seed_gen;
  7562. std::mt19937 random(seed_gen());
  7563. std::string rand1;
  7564. rand1.resize(1000);
  7565. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7566. std::string rand2;
  7567. rand2.resize(3000);
  7568. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7570. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7571. const ContentReader &content_reader) {
  7572. ASSERT_FALSE(req.is_multipart_form_data());
  7573. std::string body;
  7574. content_reader([&](const char *data, size_t data_length) {
  7575. body.append(data, data_length);
  7576. return true;
  7577. });
  7578. EXPECT_EQ(body, "");
  7579. });
  7580. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7581. const ContentReader &content_reader) {
  7582. ASSERT_TRUE(req.is_multipart_form_data());
  7583. std::vector<FormData> items;
  7584. content_reader(
  7585. [&](const FormData &file) {
  7586. items.push_back(file);
  7587. return true;
  7588. },
  7589. [&](const char *data, size_t data_length) {
  7590. items.back().content.append(data, data_length);
  7591. return true;
  7592. });
  7593. ASSERT_TRUE(items.size() == 2);
  7594. EXPECT_EQ(std::string(items[0].name), "name1");
  7595. EXPECT_EQ(items[0].content, "Testing123");
  7596. EXPECT_EQ(items[0].filename, "filename1");
  7597. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7598. EXPECT_EQ(items[1].name, "name2");
  7599. EXPECT_EQ(items[1].content, "Testing456");
  7600. EXPECT_EQ(items[1].filename, "");
  7601. EXPECT_EQ(items[1].content_type, "");
  7602. });
  7603. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7604. const ContentReader &content_reader) {
  7605. ASSERT_TRUE(req.is_multipart_form_data());
  7606. std::vector<FormData> items;
  7607. content_reader(
  7608. [&](const FormData &file) {
  7609. items.push_back(file);
  7610. return true;
  7611. },
  7612. [&](const char *data, size_t data_length) {
  7613. items.back().content.append(data, data_length);
  7614. return true;
  7615. });
  7616. ASSERT_TRUE(items.size() == 2);
  7617. EXPECT_EQ(items[0].name, "name3");
  7618. EXPECT_EQ(items[0].content, rand1);
  7619. EXPECT_EQ(items[0].filename, "filename3");
  7620. EXPECT_EQ(items[0].content_type, "");
  7621. EXPECT_EQ(items[1].name, "name4");
  7622. EXPECT_EQ(items[1].content, rand2);
  7623. EXPECT_EQ(items[1].filename, "filename4");
  7624. EXPECT_EQ(items[1].content_type, "");
  7625. });
  7626. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7627. const ContentReader &content_reader) {
  7628. ASSERT_TRUE(req.is_multipart_form_data());
  7629. std::vector<FormData> items;
  7630. content_reader(
  7631. [&](const FormData &file) {
  7632. items.push_back(file);
  7633. return true;
  7634. },
  7635. [&](const char *data, size_t data_length) {
  7636. items.back().content.append(data, data_length);
  7637. return true;
  7638. });
  7639. ASSERT_TRUE(items.size() == 4);
  7640. EXPECT_EQ(std::string(items[0].name), "name1");
  7641. EXPECT_EQ(items[0].content, "Testing123");
  7642. EXPECT_EQ(items[0].filename, "filename1");
  7643. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7644. EXPECT_EQ(items[1].name, "name2");
  7645. EXPECT_EQ(items[1].content, "Testing456");
  7646. EXPECT_EQ(items[1].filename, "");
  7647. EXPECT_EQ(items[1].content_type, "");
  7648. EXPECT_EQ(items[2].name, "name3");
  7649. EXPECT_EQ(items[2].content, rand1);
  7650. EXPECT_EQ(items[2].filename, "filename3");
  7651. EXPECT_EQ(items[2].content_type, "");
  7652. EXPECT_EQ(items[3].name, "name4");
  7653. EXPECT_EQ(items[3].content, rand2);
  7654. EXPECT_EQ(items[3].filename, "filename4");
  7655. EXPECT_EQ(items[3].content_type, "");
  7656. });
  7657. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7658. auto se = detail::scope_exit([&] {
  7659. svr.stop();
  7660. t.join();
  7661. ASSERT_FALSE(svr.is_running());
  7662. });
  7663. svr.wait_until_ready();
  7664. {
  7665. Client cli("https://localhost:8080");
  7666. cli.enable_server_certificate_verification(false);
  7667. UploadFormDataItems items{
  7668. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7669. {"name2", "Testing456", "", ""}, // not a file
  7670. };
  7671. {
  7672. auto res = cli.Post("/post-none", {}, {}, {});
  7673. ASSERT_TRUE(res);
  7674. ASSERT_EQ(StatusCode::OK_200, res->status);
  7675. }
  7676. FormDataProviderItems providers;
  7677. {
  7678. auto res =
  7679. cli.Post("/post-items", {}, items, providers); // empty providers
  7680. ASSERT_TRUE(res);
  7681. ASSERT_EQ(StatusCode::OK_200, res->status);
  7682. }
  7683. providers.push_back({"name3",
  7684. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7685. // test the offset is given correctly at each step
  7686. if (!offset)
  7687. sink.os.write(rand1.data(), 30);
  7688. else if (offset == 30)
  7689. sink.os.write(rand1.data() + 30, 300);
  7690. else if (offset == 330)
  7691. sink.os.write(rand1.data() + 330, 670);
  7692. else if (offset == rand1.size())
  7693. sink.done();
  7694. return true;
  7695. },
  7696. "filename3",
  7697. {}});
  7698. providers.push_back({"name4",
  7699. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7700. // test the offset is given correctly at each step
  7701. if (!offset)
  7702. sink.os.write(rand2.data(), 2000);
  7703. else if (offset == 2000)
  7704. sink.os.write(rand2.data() + 2000, 1);
  7705. else if (offset == 2001)
  7706. sink.os.write(rand2.data() + 2001, 999);
  7707. else if (offset == rand2.size())
  7708. sink.done();
  7709. return true;
  7710. },
  7711. "filename4",
  7712. {}});
  7713. {
  7714. auto res = cli.Post("/post-providers", {}, {}, providers);
  7715. ASSERT_TRUE(res);
  7716. ASSERT_EQ(StatusCode::OK_200, res->status);
  7717. }
  7718. {
  7719. auto res = cli.Post("/post-both", {}, items, providers);
  7720. ASSERT_TRUE(res);
  7721. ASSERT_EQ(StatusCode::OK_200, res->status);
  7722. }
  7723. }
  7724. }
  7725. TEST(MultipartFormDataTest, BadHeader) {
  7726. Server svr;
  7727. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7728. res.set_content("ok", "text/plain");
  7729. });
  7730. thread t = thread([&] { svr.listen(HOST, PORT); });
  7731. auto se = detail::scope_exit([&] {
  7732. svr.stop();
  7733. t.join();
  7734. ASSERT_FALSE(svr.is_running());
  7735. });
  7736. svr.wait_until_ready();
  7737. const std::string body =
  7738. "This is the preamble. It is to be ignored, though it\r\n"
  7739. "is a handy place for composition agents to include an\r\n"
  7740. "explanatory note to non-MIME conformant readers.\r\n"
  7741. "\r\n"
  7742. "\r\n"
  7743. "--simple boundary\r\n"
  7744. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7745. ": BAD...\r\n"
  7746. "\r\n"
  7747. "value1\r\n"
  7748. "--simple boundary\r\n"
  7749. "Content-Disposition: form-data; name=\"field2\"; "
  7750. "filename=\"example.txt\"\r\n"
  7751. "\r\n"
  7752. "value2\r\n"
  7753. "--simple boundary--\r\n"
  7754. "This is the epilogue. It is also to be ignored.\r\n";
  7755. std::string content_type =
  7756. R"(multipart/form-data; boundary="simple boundary")";
  7757. Client cli(HOST, PORT);
  7758. auto res = cli.Post("/post", body, content_type.c_str());
  7759. ASSERT_TRUE(res);
  7760. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7761. }
  7762. TEST(MultipartFormDataTest, WithPreamble) {
  7763. Server svr;
  7764. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  7765. res.set_content("ok", "text/plain");
  7766. });
  7767. thread t = thread([&] { svr.listen(HOST, PORT); });
  7768. auto se = detail::scope_exit([&] {
  7769. svr.stop();
  7770. t.join();
  7771. ASSERT_FALSE(svr.is_running());
  7772. });
  7773. svr.wait_until_ready();
  7774. const std::string body =
  7775. "This is the preamble. It is to be ignored, though it\r\n"
  7776. "is a handy place for composition agents to include an\r\n"
  7777. "explanatory note to non-MIME conformant readers.\r\n"
  7778. "\r\n"
  7779. "\r\n"
  7780. "--simple boundary\r\n"
  7781. "Content-Disposition: form-data; name=\"field1\"\r\n"
  7782. "\r\n"
  7783. "value1\r\n"
  7784. "--simple boundary\r\n"
  7785. "Content-Disposition: form-data; name=\"field2\"; "
  7786. "filename=\"example.txt\"\r\n"
  7787. "\r\n"
  7788. "value2\r\n"
  7789. "--simple boundary--\r\n"
  7790. "This is the epilogue. It is also to be ignored.\r\n";
  7791. std::string content_type =
  7792. R"(multipart/form-data; boundary="simple boundary")";
  7793. Client cli(HOST, PORT);
  7794. auto res = cli.Post("/post", body, content_type.c_str());
  7795. ASSERT_TRUE(res);
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. }
  7798. TEST(MultipartFormDataTest, PostCustomBoundary) {
  7799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7800. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  7801. const ContentReader &content_reader) {
  7802. if (req.is_multipart_form_data()) {
  7803. std::vector<FormData> items;
  7804. content_reader(
  7805. [&](const FormData &file) {
  7806. items.push_back(file);
  7807. return true;
  7808. },
  7809. [&](const char *data, size_t data_length) {
  7810. items.back().content.append(data, data_length);
  7811. return true;
  7812. });
  7813. EXPECT_TRUE(std::string(items[0].name) == "document");
  7814. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7815. EXPECT_TRUE(items[0].filename == "2MB_data");
  7816. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7817. EXPECT_TRUE(items[1].name == "hello");
  7818. EXPECT_TRUE(items[1].content == "world");
  7819. EXPECT_TRUE(items[1].filename == "");
  7820. EXPECT_TRUE(items[1].content_type == "");
  7821. } else {
  7822. std::string body;
  7823. content_reader([&](const char *data, size_t data_length) {
  7824. body.append(data, data_length);
  7825. return true;
  7826. });
  7827. }
  7828. });
  7829. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7830. auto se = detail::scope_exit([&] {
  7831. svr.stop();
  7832. t.join();
  7833. ASSERT_FALSE(svr.is_running());
  7834. });
  7835. svr.wait_until_ready();
  7836. {
  7837. std::string data(1024 * 1024 * 2, '.');
  7838. std::stringstream buffer;
  7839. buffer << data;
  7840. Client cli("https://localhost:8080");
  7841. cli.enable_server_certificate_verification(false);
  7842. UploadFormDataItems items{
  7843. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7844. {"hello", "world", "", ""},
  7845. };
  7846. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  7847. ASSERT_TRUE(res);
  7848. ASSERT_EQ(StatusCode::OK_200, res->status);
  7849. }
  7850. }
  7851. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  7852. std::string data(1024 * 1024 * 2, '&');
  7853. std::stringstream buffer;
  7854. buffer << data;
  7855. Client cli("https://localhost:8080");
  7856. UploadFormDataItems items{
  7857. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7858. {"hello", "world", "", ""},
  7859. };
  7860. for (const char &c : " \t\r\n") {
  7861. auto res =
  7862. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  7863. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7864. ASSERT_FALSE(res);
  7865. }
  7866. }
  7867. TEST(MultipartFormDataTest, PutFormData) {
  7868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7869. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  7870. const ContentReader &content_reader) {
  7871. if (req.is_multipart_form_data()) {
  7872. std::vector<FormData> items;
  7873. content_reader(
  7874. [&](const FormData &file) {
  7875. items.push_back(file);
  7876. return true;
  7877. },
  7878. [&](const char *data, size_t data_length) {
  7879. items.back().content.append(data, data_length);
  7880. return true;
  7881. });
  7882. EXPECT_TRUE(std::string(items[0].name) == "document");
  7883. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7884. EXPECT_TRUE(items[0].filename == "2MB_data");
  7885. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7886. EXPECT_TRUE(items[1].name == "hello");
  7887. EXPECT_TRUE(items[1].content == "world");
  7888. EXPECT_TRUE(items[1].filename == "");
  7889. EXPECT_TRUE(items[1].content_type == "");
  7890. } else {
  7891. std::string body;
  7892. content_reader([&](const char *data, size_t data_length) {
  7893. body.append(data, data_length);
  7894. return true;
  7895. });
  7896. }
  7897. });
  7898. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7899. auto se = detail::scope_exit([&] {
  7900. svr.stop();
  7901. t.join();
  7902. ASSERT_FALSE(svr.is_running());
  7903. });
  7904. svr.wait_until_ready();
  7905. {
  7906. std::string data(1024 * 1024 * 2, '&');
  7907. std::stringstream buffer;
  7908. buffer << data;
  7909. Client cli("https://localhost:8080");
  7910. cli.enable_server_certificate_verification(false);
  7911. UploadFormDataItems items{
  7912. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7913. {"hello", "world", "", ""},
  7914. };
  7915. auto res = cli.Put("/put", items);
  7916. ASSERT_TRUE(res);
  7917. ASSERT_EQ(StatusCode::OK_200, res->status);
  7918. }
  7919. }
  7920. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  7921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7922. svr.Put("/put_customboundary",
  7923. [&](const Request &req, const Response & /*res*/,
  7924. const ContentReader &content_reader) {
  7925. if (req.is_multipart_form_data()) {
  7926. std::vector<FormData> items;
  7927. content_reader(
  7928. [&](const FormData &file) {
  7929. items.push_back(file);
  7930. return true;
  7931. },
  7932. [&](const char *data, size_t data_length) {
  7933. items.back().content.append(data, data_length);
  7934. return true;
  7935. });
  7936. EXPECT_TRUE(std::string(items[0].name) == "document");
  7937. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7938. EXPECT_TRUE(items[0].filename == "2MB_data");
  7939. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7940. EXPECT_TRUE(items[1].name == "hello");
  7941. EXPECT_TRUE(items[1].content == "world");
  7942. EXPECT_TRUE(items[1].filename == "");
  7943. EXPECT_TRUE(items[1].content_type == "");
  7944. } else {
  7945. std::string body;
  7946. content_reader([&](const char *data, size_t data_length) {
  7947. body.append(data, data_length);
  7948. return true;
  7949. });
  7950. }
  7951. });
  7952. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7953. auto se = detail::scope_exit([&] {
  7954. svr.stop();
  7955. t.join();
  7956. ASSERT_FALSE(svr.is_running());
  7957. });
  7958. svr.wait_until_ready();
  7959. {
  7960. std::string data(1024 * 1024 * 2, '&');
  7961. std::stringstream buffer;
  7962. buffer << data;
  7963. Client cli("https://localhost:8080");
  7964. cli.enable_server_certificate_verification(false);
  7965. UploadFormDataItems items{
  7966. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7967. {"hello", "world", "", ""},
  7968. };
  7969. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  7970. ASSERT_TRUE(res);
  7971. ASSERT_EQ(StatusCode::OK_200, res->status);
  7972. }
  7973. }
  7974. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  7975. std::string data(1024 * 1024 * 2, '&');
  7976. std::stringstream buffer;
  7977. buffer << data;
  7978. Client cli("https://localhost:8080");
  7979. cli.enable_server_certificate_verification(false);
  7980. UploadFormDataItems items{
  7981. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7982. {"hello", "world", "", ""},
  7983. };
  7984. for (const char &c : " \t\r\n") {
  7985. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  7986. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  7987. ASSERT_FALSE(res);
  7988. }
  7989. }
  7990. TEST(MultipartFormDataTest, AlternateFilename) {
  7991. auto handled = false;
  7992. Server svr;
  7993. svr.Post("/test", [&](const Request &req, Response &res) {
  7994. ASSERT_EQ(2u, req.form.files.size());
  7995. ASSERT_EQ(1u, req.form.fields.size());
  7996. // Test files
  7997. const auto &file1 = req.form.get_file("file1");
  7998. ASSERT_EQ("file1", file1.name);
  7999. ASSERT_EQ("A.txt", file1.filename);
  8000. ASSERT_EQ("text/plain", file1.content_type);
  8001. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8002. const auto &file2 = req.form.get_file("file2");
  8003. ASSERT_EQ("file2", file2.name);
  8004. ASSERT_EQ("a.html", file2.filename);
  8005. ASSERT_EQ("text/html", file2.content_type);
  8006. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8007. file2.content);
  8008. // Test text field
  8009. const auto &text = req.form.get_field("text");
  8010. ASSERT_EQ("text default", text);
  8011. res.set_content("ok", "text/plain");
  8012. handled = true;
  8013. });
  8014. thread t = thread([&] { svr.listen(HOST, PORT); });
  8015. auto se = detail::scope_exit([&] {
  8016. svr.stop();
  8017. t.join();
  8018. ASSERT_FALSE(svr.is_running());
  8019. ASSERT_TRUE(handled);
  8020. });
  8021. svr.wait_until_ready();
  8022. auto req = "POST /test HTTP/1.1\r\n"
  8023. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8024. "Content-Length: 399\r\n"
  8025. "\r\n"
  8026. "----------\r\n"
  8027. "Content-Disposition: form-data; name=\"text\"\r\n"
  8028. "\r\n"
  8029. "text default\r\n"
  8030. "----------\r\n"
  8031. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8032. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8033. "Content-Type: text/plain\r\n"
  8034. "\r\n"
  8035. "Content of a.txt.\r\n"
  8036. "\r\n"
  8037. "----------\r\n"
  8038. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8039. "\"a.html\"\r\n"
  8040. "Content-Type: text/html\r\n"
  8041. "\r\n"
  8042. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8043. "\r\n"
  8044. "------------\r\n";
  8045. ASSERT_TRUE(send_request(1, req));
  8046. }
  8047. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8048. auto handled = false;
  8049. Server svr;
  8050. svr.Post("/test", [&](const Request &req, Response &) {
  8051. ASSERT_EQ(2u, req.form.fields.size());
  8052. const auto &text1 = req.form.get_field("text1");
  8053. ASSERT_EQ("text1", text1);
  8054. const auto &text2 = req.form.get_field("text2");
  8055. ASSERT_EQ("text2", text2);
  8056. handled = true;
  8057. });
  8058. thread t = thread([&] { svr.listen(HOST, PORT); });
  8059. auto se = detail::scope_exit([&] {
  8060. svr.stop();
  8061. t.join();
  8062. ASSERT_FALSE(svr.is_running());
  8063. ASSERT_TRUE(handled);
  8064. });
  8065. svr.wait_until_ready();
  8066. auto req = "POST /test HTTP/1.1\r\n"
  8067. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8068. "Content-Length: 146\r\n"
  8069. "\r\n----------\r\n"
  8070. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8071. "\r\n"
  8072. "text1"
  8073. "\r\n----------\r\n"
  8074. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8075. "\r\n"
  8076. "text2"
  8077. "\r\n------------";
  8078. std::string response;
  8079. ASSERT_TRUE(send_request(1, req, &response));
  8080. ASSERT_EQ("200", response.substr(9, 3));
  8081. }
  8082. TEST(MultipartFormDataTest, ContentLength) {
  8083. auto handled = false;
  8084. Server svr;
  8085. svr.Post("/test", [&](const Request &req, Response &) {
  8086. ASSERT_EQ(2u, req.form.fields.size());
  8087. const auto &text1 = req.form.get_field("text1");
  8088. ASSERT_EQ("text1", text1);
  8089. const auto &text2 = req.form.get_field("text2");
  8090. ASSERT_EQ("text2", text2);
  8091. handled = true;
  8092. });
  8093. thread t = thread([&] { svr.listen(HOST, PORT); });
  8094. auto se = detail::scope_exit([&] {
  8095. svr.stop();
  8096. t.join();
  8097. ASSERT_FALSE(svr.is_running());
  8098. ASSERT_TRUE(handled);
  8099. });
  8100. svr.wait_until_ready();
  8101. auto req = "POST /test HTTP/1.1\r\n"
  8102. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8103. "Content-Length: 167\r\n"
  8104. "\r\n----------\r\n"
  8105. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8106. "Content-Length: 5\r\n"
  8107. "\r\n"
  8108. "text1"
  8109. "\r\n----------\r\n"
  8110. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8111. "\r\n"
  8112. "text2"
  8113. "\r\n------------\r\n";
  8114. std::string response;
  8115. ASSERT_TRUE(send_request(1, req, &response));
  8116. ASSERT_EQ("200", response.substr(9, 3));
  8117. }
  8118. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8119. auto handled = false;
  8120. Server svr;
  8121. svr.Post("/test", [&](const Request &req, Response &) {
  8122. ASSERT_EQ(2u, req.form.fields.size());
  8123. const auto &text1 = req.form.get_field("text1");
  8124. ASSERT_EQ("text1", text1);
  8125. // TODO: Add header access for text fields if needed
  8126. const auto &text2 = req.form.get_field("text2");
  8127. ASSERT_EQ("text2", text2);
  8128. // TODO: Header access for text fields needs to be implemented
  8129. // auto &headers = it->second.headers;
  8130. // ASSERT_EQ(3U, headers.size());
  8131. // auto custom_header = headers.find("x-whatever");
  8132. // ASSERT_TRUE(custom_header != headers.end());
  8133. // ASSERT_NE("customvalue", custom_header->second);
  8134. // ASSERT_EQ("CustomValue", custom_header->second);
  8135. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8136. handled = true;
  8137. });
  8138. thread t = thread([&] { svr.listen(HOST, PORT); });
  8139. auto se = detail::scope_exit([&] {
  8140. svr.stop();
  8141. t.join();
  8142. ASSERT_FALSE(svr.is_running());
  8143. ASSERT_TRUE(handled);
  8144. });
  8145. svr.wait_until_ready();
  8146. auto req = "POST /test HTTP/1.1\r\n"
  8147. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8148. "Content-Length: 232\r\n"
  8149. "\r\n----------\r\n"
  8150. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8151. "Content-Length: 5\r\n"
  8152. "X-Test: 1\r\n"
  8153. "\r\n"
  8154. "text1"
  8155. "\r\n----------\r\n"
  8156. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8157. "Content-Type: text/plain\r\n"
  8158. "X-Whatever: CustomValue\r\n"
  8159. "\r\n"
  8160. "text2"
  8161. "\r\n------------\r\n"
  8162. "That should be disregarded. Not even read";
  8163. std::string response;
  8164. ASSERT_TRUE(send_request(1, req, &response));
  8165. ASSERT_EQ("200", response.substr(9, 3));
  8166. }
  8167. #endif
  8168. TEST(MultipartFormDataTest, LargeHeader) {
  8169. auto handled = false;
  8170. Server svr;
  8171. svr.Post("/test", [&](const Request &req, Response &) {
  8172. ASSERT_EQ(1u, req.form.fields.size());
  8173. const auto &text = req.form.get_field("name1");
  8174. ASSERT_EQ("text1", text);
  8175. handled = true;
  8176. });
  8177. thread t = thread([&] { svr.listen(HOST, PORT); });
  8178. auto se = detail::scope_exit([&] {
  8179. svr.stop();
  8180. t.join();
  8181. ASSERT_FALSE(svr.is_running());
  8182. ASSERT_TRUE(handled);
  8183. });
  8184. svr.wait_until_ready();
  8185. auto boundary = std::string("cpp-httplib-multipart-data");
  8186. std::string content = "--" + boundary +
  8187. "\r\n"
  8188. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8189. "\r\n"
  8190. "text1\r\n"
  8191. "--" +
  8192. boundary + "--\r\n";
  8193. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8194. "Content-Type: multipart/form-data;boundary=" +
  8195. boundary +
  8196. "\r\n"
  8197. "Content-Length: " +
  8198. std::to_string(content.size()) +
  8199. "\r\n"
  8200. "Dummy-Header: ";
  8201. std::string header_suffix = "\r\n"
  8202. "\r\n";
  8203. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8204. size_t header_dummy_size =
  8205. read_buff_size -
  8206. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8207. auto header_dummy = std::string(header_dummy_size, '@');
  8208. auto req = header_prefix + header_dummy + header_suffix + content;
  8209. std::string response;
  8210. ASSERT_TRUE(send_request(1, req, &response));
  8211. ASSERT_EQ("200", response.substr(9, 3));
  8212. }
  8213. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8214. static constexpr unsigned int number_of_tasks{1000000};
  8215. std::atomic_uint count{0};
  8216. std::unique_ptr<TaskQueue> task_queue{
  8217. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8218. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8219. auto queued = task_queue->enqueue(
  8220. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8221. EXPECT_TRUE(queued);
  8222. }
  8223. EXPECT_NO_THROW(task_queue->shutdown());
  8224. EXPECT_EQ(number_of_tasks, count.load());
  8225. }
  8226. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8227. static constexpr unsigned int number_of_tasks{1000000};
  8228. static constexpr unsigned int qlimit{2};
  8229. unsigned int queued_count{0};
  8230. std::atomic_uint count{0};
  8231. std::unique_ptr<TaskQueue> task_queue{
  8232. new ThreadPool{/*num_threads=*/1, qlimit}};
  8233. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8234. if (task_queue->enqueue(
  8235. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8236. queued_count++;
  8237. }
  8238. }
  8239. EXPECT_NO_THROW(task_queue->shutdown());
  8240. EXPECT_EQ(queued_count, count.load());
  8241. EXPECT_TRUE(queued_count <= number_of_tasks);
  8242. EXPECT_TRUE(queued_count >= qlimit);
  8243. }
  8244. TEST(TaskQueueTest, MaxQueuedRequests) {
  8245. static constexpr unsigned int qlimit{3};
  8246. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8247. std::condition_variable sem_cv;
  8248. std::mutex sem_mtx;
  8249. int credits = 0;
  8250. bool queued;
  8251. /* Fill up the queue with tasks that will block until we give them credits to
  8252. * complete. */
  8253. for (unsigned int n = 0; n <= qlimit;) {
  8254. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8255. std::unique_lock<std::mutex> lock(sem_mtx);
  8256. while (credits <= 0) {
  8257. sem_cv.wait(lock);
  8258. }
  8259. /* Consume the credit and signal the test code if they are all gone. */
  8260. if (--credits == 0) { sem_cv.notify_one(); }
  8261. });
  8262. if (n < qlimit) {
  8263. /* The first qlimit enqueues must succeed. */
  8264. EXPECT_TRUE(queued);
  8265. } else {
  8266. /* The last one will succeed only when the worker thread
  8267. * starts and dequeues the first blocking task. Although
  8268. * not necessary for the correctness of this test, we sleep for
  8269. * a short while to avoid busy waiting. */
  8270. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8271. }
  8272. if (queued) { n++; }
  8273. }
  8274. /* Further enqueues must fail since the queue is full. */
  8275. for (auto i = 0; i < 4; i++) {
  8276. queued = task_queue->enqueue([] {});
  8277. EXPECT_FALSE(queued);
  8278. }
  8279. /* Give the credits to allow the previous tasks to complete. */
  8280. {
  8281. std::unique_lock<std::mutex> lock(sem_mtx);
  8282. credits += qlimit + 1;
  8283. }
  8284. sem_cv.notify_all();
  8285. /* Wait for all the credits to be consumed. */
  8286. {
  8287. std::unique_lock<std::mutex> lock(sem_mtx);
  8288. while (credits > 0) {
  8289. sem_cv.wait(lock);
  8290. }
  8291. }
  8292. /* Check that we are able again to enqueue at least qlimit tasks. */
  8293. for (unsigned int i = 0; i < qlimit; i++) {
  8294. queued = task_queue->enqueue([] {});
  8295. EXPECT_TRUE(queued);
  8296. }
  8297. EXPECT_NO_THROW(task_queue->shutdown());
  8298. }
  8299. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8300. Server svr;
  8301. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8302. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8303. });
  8304. svr.Get("/hello", [](const Request &req, Response &res) {
  8305. res.set_content(req.get_param_value("key"), "text/plain");
  8306. });
  8307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8308. auto se = detail::scope_exit([&] {
  8309. svr.stop();
  8310. thread.join();
  8311. ASSERT_FALSE(svr.is_running());
  8312. });
  8313. svr.wait_until_ready();
  8314. {
  8315. Client cli(HOST, PORT);
  8316. cli.set_follow_location(true);
  8317. auto res = cli.Get("/");
  8318. ASSERT_TRUE(res);
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ("val&key2=val2", res->body);
  8321. }
  8322. }
  8323. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8324. Server svr;
  8325. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8326. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8327. });
  8328. svr.Get("/hello", [](const Request &req, Response &res) {
  8329. res.set_content(req.get_param_value("key"), "text/plain");
  8330. });
  8331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8332. auto se = detail::scope_exit([&] {
  8333. svr.stop();
  8334. thread.join();
  8335. ASSERT_FALSE(svr.is_running());
  8336. });
  8337. svr.wait_until_ready();
  8338. {
  8339. Client cli(HOST, PORT);
  8340. cli.set_follow_location(true);
  8341. auto res = cli.Get("/");
  8342. ASSERT_TRUE(res);
  8343. EXPECT_EQ(StatusCode::OK_200, res->status);
  8344. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8345. }
  8346. }
  8347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8348. TEST(RedirectTest, Issue2185_Online) {
  8349. SSLClient client("github.com");
  8350. client.set_follow_location(true);
  8351. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8352. "Coollab-Windows.zip");
  8353. ASSERT_TRUE(res);
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. EXPECT_EQ(9920427U, res->body.size());
  8356. }
  8357. #endif
  8358. TEST(VulnerabilityTest, CRLFInjection) {
  8359. Server svr;
  8360. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8361. res.set_content("Hello 1", "text/plain");
  8362. });
  8363. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8364. res.set_content("Hello 2", "text/plain");
  8365. });
  8366. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8367. res.set_content("Hello 3", "text/plain");
  8368. });
  8369. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8370. res.set_content("Hello 4", "text/plain");
  8371. });
  8372. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8373. for (const auto &x : req.headers) {
  8374. auto key = x.first;
  8375. EXPECT_STRNE("evil", key.c_str());
  8376. }
  8377. });
  8378. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8379. auto se = detail::scope_exit([&] {
  8380. svr.stop();
  8381. thread.join();
  8382. ASSERT_FALSE(svr.is_running());
  8383. });
  8384. svr.wait_until_ready();
  8385. {
  8386. Client cli(HOST, PORT);
  8387. cli.Post("/test1", "A=B",
  8388. "application/x-www-form-urlencoded\r\nevil: hello1");
  8389. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8390. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8391. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8392. }
  8393. }
  8394. TEST(PathParamsTest, StaticMatch) {
  8395. const auto pattern = "/users/all";
  8396. detail::PathParamsMatcher matcher(pattern);
  8397. Request request;
  8398. request.path = "/users/all";
  8399. ASSERT_TRUE(matcher.match(request));
  8400. std::unordered_map<std::string, std::string> expected_params = {};
  8401. EXPECT_EQ(request.path_params, expected_params);
  8402. }
  8403. TEST(PathParamsTest, StaticMismatch) {
  8404. const auto pattern = "/users/all";
  8405. detail::PathParamsMatcher matcher(pattern);
  8406. Request request;
  8407. request.path = "/users/1";
  8408. ASSERT_FALSE(matcher.match(request));
  8409. }
  8410. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8411. const auto pattern = "/users/:id/subscriptions";
  8412. detail::PathParamsMatcher matcher(pattern);
  8413. Request request;
  8414. request.path = "/users/42/subscriptions";
  8415. ASSERT_TRUE(matcher.match(request));
  8416. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8417. EXPECT_EQ(request.path_params, expected_params);
  8418. }
  8419. TEST(PathParamsTest, SingleParamInTheEnd) {
  8420. const auto pattern = "/users/:id";
  8421. detail::PathParamsMatcher matcher(pattern);
  8422. Request request;
  8423. request.path = "/users/24";
  8424. ASSERT_TRUE(matcher.match(request));
  8425. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8426. EXPECT_EQ(request.path_params, expected_params);
  8427. }
  8428. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8429. const auto pattern = "/users/:id/";
  8430. detail::PathParamsMatcher matcher(pattern);
  8431. Request request;
  8432. request.path = "/users/42/";
  8433. ASSERT_TRUE(matcher.match(request));
  8434. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8435. EXPECT_EQ(request.path_params, expected_params);
  8436. }
  8437. TEST(PathParamsTest, EmptyParam) {
  8438. const auto pattern = "/users/:id/";
  8439. detail::PathParamsMatcher matcher(pattern);
  8440. Request request;
  8441. request.path = "/users//";
  8442. ASSERT_TRUE(matcher.match(request));
  8443. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8444. EXPECT_EQ(request.path_params, expected_params);
  8445. }
  8446. TEST(PathParamsTest, FragmentMismatch) {
  8447. const auto pattern = "/users/:id/";
  8448. detail::PathParamsMatcher matcher(pattern);
  8449. Request request;
  8450. request.path = "/admins/24/";
  8451. ASSERT_FALSE(matcher.match(request));
  8452. }
  8453. TEST(PathParamsTest, ExtraFragments) {
  8454. const auto pattern = "/users/:id";
  8455. detail::PathParamsMatcher matcher(pattern);
  8456. Request request;
  8457. request.path = "/users/42/subscriptions";
  8458. ASSERT_FALSE(matcher.match(request));
  8459. }
  8460. TEST(PathParamsTest, MissingTrailingParam) {
  8461. const auto pattern = "/users/:id";
  8462. detail::PathParamsMatcher matcher(pattern);
  8463. Request request;
  8464. request.path = "/users";
  8465. ASSERT_FALSE(matcher.match(request));
  8466. }
  8467. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8468. const auto pattern = "/users/:id/subscriptions";
  8469. detail::PathParamsMatcher matcher(pattern);
  8470. Request request;
  8471. request.path = "/users/subscriptions";
  8472. ASSERT_FALSE(matcher.match(request));
  8473. }
  8474. TEST(PathParamsTest, MultipleParams) {
  8475. const auto pattern = "/users/:userid/subscriptions/:subid";
  8476. detail::PathParamsMatcher matcher(pattern);
  8477. Request request;
  8478. request.path = "/users/42/subscriptions/2";
  8479. ASSERT_TRUE(matcher.match(request));
  8480. std::unordered_map<std::string, std::string> expected_params = {
  8481. {"userid", "42"}, {"subid", "2"}};
  8482. EXPECT_EQ(request.path_params, expected_params);
  8483. }
  8484. TEST(PathParamsTest, SequenceOfParams) {
  8485. const auto pattern = "/values/:x/:y/:z";
  8486. detail::PathParamsMatcher matcher(pattern);
  8487. Request request;
  8488. request.path = "/values/1/2/3";
  8489. ASSERT_TRUE(matcher.match(request));
  8490. std::unordered_map<std::string, std::string> expected_params = {
  8491. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8492. EXPECT_EQ(request.path_params, expected_params);
  8493. }
  8494. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8495. const auto pattern = "/prefix:suffix";
  8496. detail::PathParamsMatcher matcher(pattern);
  8497. Request request;
  8498. request.path = "/prefix:suffix";
  8499. ASSERT_TRUE(matcher.match(request));
  8500. const std::unordered_map<std::string, std::string> expected_params = {};
  8501. EXPECT_EQ(request.path_params, expected_params);
  8502. }
  8503. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8504. // If ipv6 regex working, regex match codepath is taken.
  8505. // else port will default to 80 in Client impl
  8506. int clientImplMagicPort = 80;
  8507. int port = 4321;
  8508. // above ports must be different to avoid false negative
  8509. EXPECT_NE(clientImplMagicPort, port);
  8510. std::string ipV6TestURL = "http://[ff06::c3]";
  8511. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8512. CLIENT_PRIVATE_KEY_FILE);
  8513. EXPECT_EQ(cli.port(), port);
  8514. }
  8515. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8516. auto file_path = "./www/dir/index.html";
  8517. auto dir_path = "./www/dir";
  8518. detail::FileStat stat_file(file_path);
  8519. EXPECT_TRUE(stat_file.is_file());
  8520. EXPECT_FALSE(stat_file.is_dir());
  8521. detail::FileStat stat_dir(dir_path);
  8522. EXPECT_FALSE(stat_dir.is_file());
  8523. EXPECT_TRUE(stat_dir.is_dir());
  8524. }
  8525. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8526. Server svr;
  8527. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8528. EXPECT_EQ(res.status, 400);
  8529. });
  8530. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8531. auto se = detail::scope_exit([&] {
  8532. svr.stop();
  8533. thread.join();
  8534. ASSERT_FALSE(svr.is_running());
  8535. });
  8536. svr.wait_until_ready();
  8537. Client cli(HOST, PORT);
  8538. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8539. }
  8540. TEST(InvalidHeaderCharsTest, is_field_name) {
  8541. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8542. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8543. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8544. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8545. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8546. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8547. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8548. EXPECT_FALSE(detail::fields::is_field_name(""));
  8549. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8550. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8551. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8552. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8553. }
  8554. TEST(InvalidHeaderCharsTest, is_field_value) {
  8555. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8556. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8557. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8558. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8559. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8560. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8561. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8562. EXPECT_TRUE(detail::fields::is_field_value(""));
  8563. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8564. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8565. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8566. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8567. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8568. }
  8569. TEST(InvalidHeaderCharsTest, OnServer) {
  8570. Server svr;
  8571. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8572. std::string header = "Not Set";
  8573. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8574. res.set_header(header, "value");
  8575. res.set_content("Page Content Page Content", "text/plain");
  8576. });
  8577. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8578. std::string header = "Not Set";
  8579. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8580. res.set_header("X-Test", header);
  8581. res.set_content("Page Content Page Content", "text/plain");
  8582. });
  8583. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. thread.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. });
  8589. svr.wait_until_ready();
  8590. Client cli(HOST, PORT);
  8591. {
  8592. auto res = cli.Get(
  8593. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8594. ASSERT_TRUE(res);
  8595. EXPECT_EQ("Page Content Page Content", res->body);
  8596. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8597. }
  8598. {
  8599. auto res = cli.Get(
  8600. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8601. ASSERT_TRUE(res);
  8602. EXPECT_EQ("Page Content Page Content", res->body);
  8603. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8604. }
  8605. }
  8606. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8607. auto handled = false;
  8608. Server svr;
  8609. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8610. thread t = thread([&] { svr.listen(HOST, PORT); });
  8611. auto se = detail::scope_exit([&] {
  8612. svr.stop();
  8613. t.join();
  8614. ASSERT_FALSE(svr.is_running());
  8615. ASSERT_FALSE(handled);
  8616. });
  8617. svr.wait_until_ready();
  8618. auto req = "POST /test HTTP/1.1\r\n"
  8619. "Content-Length: x\r\n"
  8620. "\r\n";
  8621. std::string response;
  8622. ASSERT_TRUE(send_request(1, req, &response));
  8623. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8624. response.substr(0, response.find("\r\n")));
  8625. }
  8626. #ifndef _WIN32
  8627. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8628. static constexpr char reject[] = "Unauthorized";
  8629. static constexpr char accept[] = "Upload accepted";
  8630. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8631. Server svr;
  8632. svr.set_expect_100_continue_handler(
  8633. [](const Request & /*req*/, Response &res) {
  8634. res.status = StatusCode::Unauthorized_401;
  8635. res.set_content(reject, "text/plain");
  8636. return res.status;
  8637. });
  8638. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  8639. res.set_content(accept, "text/plain");
  8640. });
  8641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8642. auto se = detail::scope_exit([&] {
  8643. svr.stop();
  8644. thread.join();
  8645. ASSERT_FALSE(svr.is_running());
  8646. });
  8647. svr.wait_until_ready();
  8648. {
  8649. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  8650. curl_easy_init(), &curl_easy_cleanup};
  8651. ASSERT_NE(curl, nullptr);
  8652. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  8653. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  8654. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  8655. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  8656. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  8657. &curl_slist_free_all};
  8658. ASSERT_NE(list, nullptr);
  8659. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  8660. struct read_data {
  8661. size_t read_size;
  8662. size_t total_size;
  8663. } data = {0, total_size};
  8664. using read_callback_t =
  8665. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8666. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  8667. void *userdata) -> size_t {
  8668. read_data *data = (read_data *)userdata;
  8669. if (!userdata || data->read_size >= data->total_size) { return 0; }
  8670. std::fill_n(ptr, size * nmemb, 'A');
  8671. data->read_size += size * nmemb;
  8672. return size * nmemb;
  8673. };
  8674. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  8675. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  8676. std::vector<char> buffer;
  8677. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  8678. using write_callback_t =
  8679. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  8680. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  8681. void *userdata) -> size_t {
  8682. std::vector<char> *buffer = (std::vector<char> *)userdata;
  8683. buffer->reserve(buffer->size() + size * nmemb + 1);
  8684. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  8685. return size * nmemb;
  8686. };
  8687. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  8688. {
  8689. const auto res = curl_easy_perform(curl.get());
  8690. ASSERT_EQ(res, CURLE_OK);
  8691. }
  8692. {
  8693. auto response_code = long{};
  8694. const auto res =
  8695. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  8696. ASSERT_EQ(res, CURLE_OK);
  8697. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  8698. }
  8699. {
  8700. auto dl = curl_off_t{};
  8701. const auto res =
  8702. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  8703. ASSERT_EQ(res, CURLE_OK);
  8704. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  8705. }
  8706. {
  8707. buffer.push_back('\0');
  8708. ASSERT_STRCASEEQ(buffer.data(), reject);
  8709. }
  8710. }
  8711. }
  8712. #endif
  8713. template <typename S, typename C>
  8714. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  8715. svr.Get("/stream", [&](const Request &, Response &res) {
  8716. auto data = new std::string("01234567890123456789");
  8717. res.set_content_provider(
  8718. data->size(), "text/plain",
  8719. [&, data](size_t offset, size_t length, DataSink &sink) {
  8720. const size_t DATA_CHUNK_SIZE = 4;
  8721. const auto &d = *data;
  8722. std::this_thread::sleep_for(std::chrono::seconds(1));
  8723. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  8724. return true;
  8725. },
  8726. [data](bool success) {
  8727. EXPECT_FALSE(success);
  8728. delete data;
  8729. });
  8730. });
  8731. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  8732. auto i = new size_t(0);
  8733. res.set_content_provider(
  8734. "text/plain",
  8735. [i](size_t, DataSink &sink) {
  8736. if (*i < 5) {
  8737. std::this_thread::sleep_for(std::chrono::seconds(1));
  8738. sink.write("abcd", 4);
  8739. (*i)++;
  8740. } else {
  8741. sink.done();
  8742. }
  8743. return true;
  8744. },
  8745. [i](bool success) {
  8746. EXPECT_FALSE(success);
  8747. delete i;
  8748. });
  8749. });
  8750. svr.Get("/chunked", [&](const Request &, Response &res) {
  8751. auto i = new size_t(0);
  8752. res.set_chunked_content_provider(
  8753. "text/plain",
  8754. [i](size_t, DataSink &sink) {
  8755. if (*i < 5) {
  8756. std::this_thread::sleep_for(std::chrono::seconds(1));
  8757. sink.os << "abcd";
  8758. (*i)++;
  8759. } else {
  8760. sink.done();
  8761. }
  8762. return true;
  8763. },
  8764. [i](bool success) {
  8765. EXPECT_FALSE(success);
  8766. delete i;
  8767. });
  8768. });
  8769. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8770. auto se = detail::scope_exit([&] {
  8771. svr.stop();
  8772. listen_thread.join();
  8773. ASSERT_FALSE(svr.is_running());
  8774. });
  8775. svr.wait_until_ready();
  8776. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  8777. {
  8778. auto start = std::chrono::steady_clock::now();
  8779. auto res = cli.Get("/stream");
  8780. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8781. std::chrono::steady_clock::now() - start)
  8782. .count();
  8783. ASSERT_FALSE(res);
  8784. EXPECT_EQ(Error::Read, res.error());
  8785. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8786. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8787. }
  8788. {
  8789. auto start = std::chrono::steady_clock::now();
  8790. auto res = cli.Get("/stream_without_length");
  8791. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8792. std::chrono::steady_clock::now() - start)
  8793. .count();
  8794. ASSERT_FALSE(res);
  8795. EXPECT_EQ(Error::Read, res.error());
  8796. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8797. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8798. }
  8799. {
  8800. auto start = std::chrono::steady_clock::now();
  8801. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  8802. EXPECT_EQ("abcd", string(data, data_length));
  8803. return true;
  8804. });
  8805. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  8806. std::chrono::steady_clock::now() - start)
  8807. .count();
  8808. ASSERT_FALSE(res);
  8809. EXPECT_EQ(Error::Read, res.error());
  8810. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  8811. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  8812. }
  8813. }
  8814. TEST(MaxTimeoutTest, ContentStream) {
  8815. time_t timeout = 2000;
  8816. time_t threshold = 200;
  8817. Server svr;
  8818. Client cli("localhost", PORT);
  8819. max_timeout_test(svr, cli, timeout, threshold);
  8820. }
  8821. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8822. TEST(MaxTimeoutTest, ContentStreamSSL) {
  8823. time_t timeout = 2000;
  8824. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  8825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8826. SSLClient cli("localhost", PORT);
  8827. cli.enable_server_certificate_verification(false);
  8828. max_timeout_test(svr, cli, timeout, threshold);
  8829. }
  8830. #endif
  8831. class EventDispatcher {
  8832. public:
  8833. EventDispatcher() {}
  8834. void wait_event(DataSink *sink) {
  8835. unique_lock<mutex> lk(m_);
  8836. int id = id_;
  8837. cv_.wait(lk, [&] { return cid_ == id; });
  8838. sink->write(message_.data(), message_.size());
  8839. }
  8840. void send_event(const string &message) {
  8841. lock_guard<mutex> lk(m_);
  8842. cid_ = id_++;
  8843. message_ = message;
  8844. cv_.notify_all();
  8845. }
  8846. private:
  8847. mutex m_;
  8848. condition_variable cv_;
  8849. atomic_int id_{0};
  8850. atomic_int cid_{-1};
  8851. string message_;
  8852. };
  8853. TEST(ClientInThreadTest, Issue2068) {
  8854. EventDispatcher ed;
  8855. Server svr;
  8856. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  8857. res.set_chunked_content_provider("text/event-stream",
  8858. [&](size_t /*offset*/, DataSink &sink) {
  8859. ed.wait_event(&sink);
  8860. return true;
  8861. });
  8862. });
  8863. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8864. svr.wait_until_ready();
  8865. thread event_thread([&] {
  8866. int id = 0;
  8867. while (svr.is_running()) {
  8868. this_thread::sleep_for(chrono::milliseconds(500));
  8869. std::stringstream ss;
  8870. ss << "data: " << id << "\n\n";
  8871. ed.send_event(ss.str());
  8872. id++;
  8873. }
  8874. });
  8875. auto se = detail::scope_exit([&] {
  8876. svr.stop();
  8877. listen_thread.join();
  8878. event_thread.join();
  8879. ASSERT_FALSE(svr.is_running());
  8880. });
  8881. {
  8882. auto client = detail::make_unique<Client>(HOST, PORT);
  8883. client->set_read_timeout(std::chrono::minutes(10));
  8884. std::atomic<bool> stop{false};
  8885. std::thread t([&] {
  8886. client->Get("/event1",
  8887. [&](const char *, size_t) -> bool { return !stop; });
  8888. });
  8889. std::this_thread::sleep_for(std::chrono::seconds(2));
  8890. stop = true;
  8891. client->stop();
  8892. client.reset();
  8893. t.join();
  8894. }
  8895. }
  8896. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  8897. Server svr;
  8898. svr.Get("/", [](const Request &req, Response &res) {
  8899. EXPECT_EQ(2U, req.trailers.size());
  8900. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  8901. // Denied
  8902. EXPECT_FALSE(req.has_trailer("Content-Length"));
  8903. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  8904. // Accepted
  8905. EXPECT_TRUE(req.has_trailer("X-Hello"));
  8906. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  8907. EXPECT_TRUE(req.has_trailer("X-World"));
  8908. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  8909. res.set_content("ok", "text/plain");
  8910. });
  8911. thread t = thread([&]() { svr.listen(HOST, PORT); });
  8912. auto se = detail::scope_exit([&] {
  8913. svr.stop();
  8914. t.join();
  8915. ASSERT_FALSE(svr.is_running());
  8916. });
  8917. svr.wait_until_ready();
  8918. const std::string req = "GET / HTTP/1.1\r\n"
  8919. "Transfer-Encoding: chunked\r\n"
  8920. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  8921. "\r\n"
  8922. "0\r\n"
  8923. "Content-Length: 10\r\n"
  8924. "Host: internal.local\r\n"
  8925. "Content-Type: malicious/content\r\n"
  8926. "Cookie: any\r\n"
  8927. "Set-Cookie: any\r\n"
  8928. "X-Forwarded-For: attacker.com\r\n"
  8929. "X-Real-Ip: 1.1.1.1\r\n"
  8930. "X-Hello: hello\r\n"
  8931. "X-World: world\r\n"
  8932. "\r\n";
  8933. std::string res;
  8934. ASSERT_TRUE(send_request(1, req, &res));
  8935. }