test.cc 434 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152
  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 <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. Server svr;
  74. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  75. res.set_content("Benchmark Response", "text/plain");
  76. });
  77. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  78. auto se = detail::scope_exit([&] {
  79. svr.stop();
  80. listen_thread.join();
  81. ASSERT_FALSE(svr.is_running());
  82. });
  83. svr.wait_until_ready();
  84. Client cli(host, PORT);
  85. // Warm-up request to establish connection and resolve DNS
  86. auto warmup_res = cli.Get("/benchmark");
  87. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  88. // Run multiple trials and collect timings
  89. const int num_trials = 20;
  90. std::vector<int64_t> timings;
  91. timings.reserve(num_trials);
  92. for (int i = 0; i < num_trials; i++) {
  93. auto start = std::chrono::high_resolution_clock::now();
  94. auto res = cli.Get("/benchmark");
  95. auto end = std::chrono::high_resolution_clock::now();
  96. auto elapsed =
  97. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  98. .count();
  99. // Assertions after timing measurement to avoid overhead
  100. ASSERT_TRUE(res);
  101. EXPECT_EQ(StatusCode::OK_200, res->status);
  102. timings.push_back(elapsed);
  103. }
  104. // Calculate 25th percentile (lower quartile)
  105. std::sort(timings.begin(), timings.end());
  106. auto p25 = timings[num_trials / 4];
  107. // Format timings for output
  108. std::ostringstream timings_str;
  109. timings_str << "[";
  110. for (size_t i = 0; i < timings.size(); i++) {
  111. if (i > 0) timings_str << ", ";
  112. timings_str << timings[i];
  113. }
  114. timings_str << "]";
  115. // Localhost HTTP GET should be fast even in CI environments
  116. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  117. << "ms (Issue #1777). Timings: " << timings_str.str();
  118. }
  119. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  120. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  121. class UnixSocketTest : public ::testing::Test {
  122. protected:
  123. void TearDown() override { std::remove(pathname_.c_str()); }
  124. void client_GET(const std::string &addr) {
  125. httplib::Client cli{addr};
  126. cli.set_address_family(AF_UNIX);
  127. ASSERT_TRUE(cli.is_valid());
  128. const auto &result = cli.Get(pattern_);
  129. ASSERT_TRUE(result) << "error: " << result.error();
  130. const auto &resp = result.value();
  131. EXPECT_EQ(resp.status, StatusCode::OK_200);
  132. EXPECT_EQ(resp.body, content_);
  133. }
  134. const std::string pathname_{"./httplib-server.sock"};
  135. const std::string pattern_{"/hi"};
  136. const std::string content_{"Hello World!"};
  137. };
  138. TEST_F(UnixSocketTest, pathname) {
  139. httplib::Server svr;
  140. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  141. res.set_content(content_, "text/plain");
  142. });
  143. std::thread t{[&] {
  144. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  145. }};
  146. auto se = detail::scope_exit([&] {
  147. svr.stop();
  148. t.join();
  149. ASSERT_FALSE(svr.is_running());
  150. });
  151. svr.wait_until_ready();
  152. ASSERT_TRUE(svr.is_running());
  153. client_GET(pathname_);
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_EQ(0, close(fds[1]));
  246. EXPECT_FALSE(s0.wait_writable());
  247. return true;
  248. });
  249. EXPECT_EQ(0, close(fds[0]));
  250. }
  251. TEST(SocketStream, wait_writable_INET) {
  252. sockaddr_in addr;
  253. memset(&addr, 0, sizeof(addr));
  254. addr.sin_family = AF_INET;
  255. addr.sin_port = htons(PORT + 1);
  256. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  257. int disconnected_svr_sock = -1;
  258. std::thread svr{[&] {
  259. const int s = socket(AF_INET, SOCK_STREAM, 0);
  260. ASSERT_LE(0, s);
  261. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  262. ASSERT_EQ(0, listen(s, 1));
  263. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  264. ASSERT_EQ(0, close(s));
  265. }};
  266. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  267. std::thread cli{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. cli.join();
  274. svr.join();
  275. ASSERT_NE(disconnected_svr_sock, -1);
  276. const auto asSocketStream = [&](socket_t fd,
  277. std::function<bool(Stream &)> func) {
  278. return detail::process_client_socket(
  279. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  280. };
  281. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  282. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  283. EXPECT_FALSE(ss.wait_writable());
  284. return true;
  285. });
  286. ASSERT_EQ(0, close(disconnected_svr_sock));
  287. }
  288. #endif // #ifndef _WIN32
  289. TEST(ClientTest, MoveConstructible) {
  290. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  291. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  292. }
  293. TEST(ClientTest, MoveAssignable) {
  294. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  295. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  296. }
  297. #ifdef _WIN32
  298. TEST(StartupTest, WSAStartup) {
  299. WSADATA wsaData;
  300. int ret = WSAStartup(0x0002, &wsaData);
  301. ASSERT_EQ(0, ret);
  302. }
  303. #endif
  304. TEST(DecodePathTest, PercentCharacter) {
  305. EXPECT_EQ(
  306. decode_path_component(
  307. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  308. u8"descrip=Gastos áéíóúñÑ 6");
  309. }
  310. TEST(DecodePathTest, PercentCharacterNUL) {
  311. string expected;
  312. expected.push_back('x');
  313. expected.push_back('\0');
  314. expected.push_back('x');
  315. EXPECT_EQ(decode_path_component("x%00x"), expected);
  316. }
  317. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  318. string unescapedCharacters = "-_.!~*'()";
  319. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  320. }
  321. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  322. string reservedCharacters = ";,/?:@&=+$";
  323. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  324. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  325. }
  326. TEST(ClientQueryOrder, PreserveOrder) {
  327. // This test reproduces Issue #2259: client may reorder query parameters
  328. // when sending a GET request. The expected behavior is that the client
  329. // preserves the original query string order when the caller supplied it
  330. // as part of the path.
  331. Server svr;
  332. svr.Get("/", [&](const Request &req, Response &res) {
  333. // Echo back the raw target so the test can assert ordering
  334. res.set_content(req.target, "text/plain");
  335. });
  336. std::thread t{[&] { svr.listen(HOST, PORT); }};
  337. auto se = detail::scope_exit([&] {
  338. svr.stop();
  339. t.join();
  340. ASSERT_FALSE(svr.is_running());
  341. });
  342. svr.wait_until_ready();
  343. Client cli(HOST, PORT);
  344. ASSERT_TRUE(cli.is_valid());
  345. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  346. auto res = cli.Get(original);
  347. ASSERT_TRUE(res);
  348. // Expect the echoed target to exactly match the original path (order
  349. // preserved)
  350. EXPECT_EQ(res->body, original);
  351. }
  352. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  353. string chineseCharacters = u8"中国語";
  354. string russianCharacters = u8"дом";
  355. string brazilianCharacters = u8"óculos";
  356. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  357. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  358. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  359. "%D0%B4%D0%BE%D0%BC");
  360. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  361. }
  362. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  363. string unescapedCharacters = "-_.!~*'()";
  364. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  365. }
  366. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  367. string reservedCharacters = ";,/?:@&=+$";
  368. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  369. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  370. }
  371. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  372. string chineseCharacters = u8"中国語";
  373. string russianCharacters = u8"дом";
  374. string brazilianCharacters = u8"óculos";
  375. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  376. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  377. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  378. "%D0%B4%D0%BE%D0%BC");
  379. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  380. }
  381. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  382. // Issue #2082 use case: encoding path component with ampersand
  383. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  384. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  385. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  386. }
  387. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  388. string unescapedCharacters = "-_.!~*'()";
  389. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  390. }
  391. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  392. string reservedCharacters = ";,/?:@&=+$#";
  393. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  394. }
  395. TEST(EncodeUriTest, TestUTF8Characters) {
  396. string chineseCharacters = u8"中国語";
  397. string russianCharacters = u8"дом";
  398. string brazilianCharacters = u8"óculos";
  399. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  400. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  401. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriTest, TestCompleteUri) {
  405. string uri =
  406. "https://example.com/path/to/resource?query=value&param=test#fragment";
  407. EXPECT_EQ(
  408. httplib::encode_uri(uri),
  409. "https://example.com/path/to/resource?query=value&param=test#fragment");
  410. }
  411. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  412. string uri =
  413. "https://example.com/path with spaces/file name.html?q=hello world";
  414. EXPECT_EQ(httplib::encode_uri(uri),
  415. "https://example.com/path%20with%20spaces/"
  416. "file%20name.html?q=hello%20world");
  417. }
  418. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  419. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  420. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  421. }
  422. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  423. string unescapedCharacters = "-_.!~*'()";
  424. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  425. }
  426. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  427. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  428. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  429. string encodedBrazilian = "%C3%B3culos";
  430. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  431. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  433. }
  434. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  435. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  436. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  437. "Piri Tommy Villiers - on & on");
  438. }
  439. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  440. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  441. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  442. }
  443. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  445. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  446. }
  447. TEST(DecodeUriTest, TestUTF8Characters) {
  448. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  449. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  450. string encodedBrazilian = "%C3%B3culos";
  451. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  452. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  453. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  454. }
  455. TEST(DecodeUriTest, TestCompleteUri) {
  456. string encodedUri = "https://example.com/path%20with%20spaces/"
  457. "file%20name.html?q=hello%20world";
  458. EXPECT_EQ(
  459. httplib::decode_uri(encodedUri),
  460. "https://example.com/path with spaces/file name.html?q=hello world");
  461. }
  462. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  463. string original =
  464. "https://example.com/path with spaces/file name.html?q=hello world";
  465. string encoded = httplib::encode_uri(original);
  466. string decoded = httplib::decode_uri(encoded);
  467. EXPECT_EQ(decoded, original);
  468. }
  469. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  470. string original = "Piri Tommy Villiers - on & on";
  471. string encoded = httplib::encode_uri_component(original);
  472. string decoded = httplib::decode_uri_component(encoded);
  473. EXPECT_EQ(decoded, original);
  474. }
  475. TEST(TrimTests, TrimStringTests) {
  476. EXPECT_EQ("abc", detail::trim_copy("abc"));
  477. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  478. EXPECT_TRUE(detail::trim_copy("").empty());
  479. }
  480. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  481. // Simple case without quality values
  482. std::vector<std::string> result1;
  483. EXPECT_TRUE(detail::parse_accept_header(
  484. "text/html,application/json,text/plain", result1));
  485. EXPECT_EQ(result1.size(), 3U);
  486. EXPECT_EQ(result1[0], "text/html");
  487. EXPECT_EQ(result1[1], "application/json");
  488. EXPECT_EQ(result1[2], "text/plain");
  489. // With quality values
  490. std::vector<std::string> result2;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  493. EXPECT_EQ(result2.size(), 3U);
  494. EXPECT_EQ(result2[0], "application/json"); // highest q value
  495. EXPECT_EQ(result2[1], "text/html");
  496. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  497. }
  498. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  499. // Mixed with and without quality values
  500. std::vector<std::string> result;
  501. EXPECT_TRUE(detail::parse_accept_header(
  502. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  503. EXPECT_EQ(result.size(), 3U);
  504. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  505. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  506. EXPECT_EQ(result[2], "application/json"); // q=0.5
  507. }
  508. TEST(ParseAcceptHeaderTest, EdgeCases) {
  509. // Empty header
  510. std::vector<std::string> empty_result;
  511. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  512. EXPECT_TRUE(empty_result.empty());
  513. // Single type
  514. std::vector<std::string> single_result;
  515. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  516. EXPECT_EQ(single_result.size(), 1U);
  517. EXPECT_EQ(single_result[0], "application/json");
  518. // Wildcard types
  519. std::vector<std::string> wildcard_result;
  520. EXPECT_TRUE(detail::parse_accept_header(
  521. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  522. EXPECT_EQ(wildcard_result.size(), 3U);
  523. EXPECT_EQ(wildcard_result[0], "application/json");
  524. EXPECT_EQ(wildcard_result[1], "text/*");
  525. EXPECT_EQ(wildcard_result[2], "*/*");
  526. }
  527. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  528. // Common browser Accept header
  529. std::vector<std::string> browser_result;
  530. EXPECT_TRUE(
  531. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  532. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  533. browser_result));
  534. EXPECT_EQ(browser_result.size(), 6U);
  535. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  536. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  540. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  541. // API client header
  542. std::vector<std::string> api_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  545. api_result));
  546. EXPECT_EQ(api_result.size(), 3U);
  547. EXPECT_EQ(api_result[0], "application/json");
  548. EXPECT_EQ(api_result[1], "application/xml");
  549. EXPECT_EQ(api_result[2], "text/plain");
  550. }
  551. TEST(ParseAcceptHeaderTest, SpecialCases) {
  552. // Quality value with 3 decimal places
  553. std::vector<std::string> decimal_result;
  554. EXPECT_TRUE(detail::parse_accept_header(
  555. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  556. EXPECT_EQ(decimal_result.size(), 2U);
  557. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  558. EXPECT_EQ(decimal_result[1], "text/html");
  559. // Zero quality (should still be included but with lowest priority)
  560. std::vector<std::string> zero_q_result;
  561. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  562. zero_q_result));
  563. EXPECT_EQ(zero_q_result.size(), 2U);
  564. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  565. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  566. // No spaces around commas
  567. std::vector<std::string> no_space_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  570. no_space_result));
  571. EXPECT_EQ(no_space_result.size(), 3U);
  572. EXPECT_EQ(no_space_result[0], "text/html");
  573. EXPECT_EQ(no_space_result[1], "application/json");
  574. EXPECT_EQ(no_space_result[2], "text/plain");
  575. }
  576. TEST(ParseAcceptHeaderTest, InvalidCases) {
  577. std::vector<std::string> result;
  578. // Invalid quality value (> 1.0)
  579. EXPECT_FALSE(
  580. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  581. // Invalid quality value (< 0.0)
  582. EXPECT_FALSE(
  583. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  584. // Invalid quality value (not a number)
  585. EXPECT_FALSE(detail::parse_accept_header(
  586. "text/html;q=invalid,application/json", result));
  587. // Empty quality value
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=,application/json", result));
  590. // Invalid media type format (no slash and not wildcard)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("invalidtype,application/json", result));
  593. // Empty media type
  594. result.clear();
  595. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  596. // Only commas
  597. result.clear();
  598. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  599. // Valid cases should still work
  600. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  601. EXPECT_EQ(result.size(), 1U);
  602. EXPECT_EQ(result[0], "*/*");
  603. EXPECT_TRUE(detail::parse_accept_header("*", result));
  604. EXPECT_EQ(result.size(), 1U);
  605. EXPECT_EQ(result[0], "*");
  606. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  607. EXPECT_EQ(result.size(), 1U);
  608. EXPECT_EQ(result[0], "text/*");
  609. }
  610. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  611. Server svr;
  612. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  613. EXPECT_EQ(req.accept_content_types.size(), 3U);
  614. EXPECT_EQ(req.accept_content_types[0], "application/json");
  615. EXPECT_EQ(req.accept_content_types[1], "text/html");
  616. EXPECT_EQ(req.accept_content_types[2], "*/*");
  617. res.set_content("ok", "text/plain");
  618. });
  619. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  620. EXPECT_TRUE(false);
  621. res.set_content("bad request", "text/plain");
  622. });
  623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  624. auto se = detail::scope_exit([&] {
  625. svr.stop();
  626. listen_thread.join();
  627. ASSERT_FALSE(svr.is_running());
  628. });
  629. svr.wait_until_ready();
  630. Client cli("localhost", PORT);
  631. {
  632. auto res =
  633. cli.Get("/accept_ok",
  634. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  635. ASSERT_TRUE(res);
  636. EXPECT_EQ(StatusCode::OK_200, res->status);
  637. }
  638. {
  639. auto res = cli.Get("/accept_bad_request",
  640. {{"Accept", "text/html;q=abc,application/json"}});
  641. ASSERT_TRUE(res);
  642. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  643. }
  644. }
  645. TEST(DivideTest, DivideStringTests) {
  646. auto divide = [](const std::string &str, char d) {
  647. std::string lhs;
  648. std::string rhs;
  649. detail::divide(str, d,
  650. [&](const char *lhs_data, std::size_t lhs_size,
  651. const char *rhs_data, std::size_t rhs_size) {
  652. lhs.assign(lhs_data, lhs_size);
  653. rhs.assign(rhs_data, rhs_size);
  654. });
  655. return std::make_pair(std::move(lhs), std::move(rhs));
  656. };
  657. {
  658. const auto res = divide("", '=');
  659. EXPECT_EQ(res.first, "");
  660. EXPECT_EQ(res.second, "");
  661. }
  662. {
  663. const auto res = divide("=", '=');
  664. EXPECT_EQ(res.first, "");
  665. EXPECT_EQ(res.second, "");
  666. }
  667. {
  668. const auto res = divide(" ", '=');
  669. EXPECT_EQ(res.first, " ");
  670. EXPECT_EQ(res.second, "");
  671. }
  672. {
  673. const auto res = divide("a", '=');
  674. EXPECT_EQ(res.first, "a");
  675. EXPECT_EQ(res.second, "");
  676. }
  677. {
  678. const auto res = divide("a=", '=');
  679. EXPECT_EQ(res.first, "a");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=b", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "b");
  686. }
  687. {
  688. const auto res = divide("a=b", '=');
  689. EXPECT_EQ(res.first, "a");
  690. EXPECT_EQ(res.second, "b");
  691. }
  692. {
  693. const auto res = divide("a=b=", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "b=");
  696. }
  697. {
  698. const auto res = divide("a=b=c", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "b=c");
  701. }
  702. }
  703. TEST(SplitTest, ParseQueryString) {
  704. string s = "key1=val1&key2=val2&key3=val3";
  705. Params dic;
  706. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  707. [&](const char *b, const char *e) {
  708. string key, val;
  709. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  710. if (key.empty()) {
  711. key.assign(b2, e2);
  712. } else {
  713. val.assign(b2, e2);
  714. }
  715. });
  716. dic.emplace(key, val);
  717. });
  718. EXPECT_EQ("val1", dic.find("key1")->second);
  719. EXPECT_EQ("val2", dic.find("key2")->second);
  720. EXPECT_EQ("val3", dic.find("key3")->second);
  721. }
  722. TEST(SplitTest, ParseInvalidQueryTests) {
  723. {
  724. string s = " ";
  725. Params dict;
  726. detail::parse_query_text(s, dict);
  727. EXPECT_TRUE(dict.empty());
  728. }
  729. {
  730. string s = " = =";
  731. Params dict;
  732. detail::parse_query_text(s, dict);
  733. EXPECT_TRUE(dict.empty());
  734. }
  735. }
  736. TEST(ParseQueryTest, ParseQueryString) {
  737. {
  738. std::string s = "key1=val1&key2=val2&key3=val3";
  739. Params dic;
  740. detail::parse_query_text(s, dic);
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. {
  746. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("", dic.find("key1")->second);
  750. EXPECT_EQ("val1", dic.find("key2")->second);
  751. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  752. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  753. }
  754. }
  755. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  756. Params dic;
  757. EXPECT_EQ(detail::params_to_query_str(dic), "");
  758. dic.emplace("key1", "val1");
  759. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  760. dic.emplace("key2", "val2");
  761. dic.emplace("key3", "val3");
  762. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  763. }
  764. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  765. string content_type = "multipart/form-data; boundary=something";
  766. string boundary;
  767. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  768. EXPECT_TRUE(ret);
  769. EXPECT_EQ(boundary, "something");
  770. }
  771. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  772. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  773. string boundary;
  774. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  777. }
  778. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  779. string content_type =
  780. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  793. }
  794. TEST(GetHeaderValueTest, DefaultValue) {
  795. Headers headers = {{"Dummy", "Dummy"}};
  796. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  797. EXPECT_STREQ("text/plain", val);
  798. }
  799. TEST(GetHeaderValueTest, DefaultValueInt) {
  800. Headers headers = {{"Dummy", "Dummy"}};
  801. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  802. EXPECT_EQ(100ull, val);
  803. }
  804. TEST(GetHeaderValueTest, RegularValue) {
  805. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  806. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  807. EXPECT_STREQ("text/html", val);
  808. }
  809. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  810. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  811. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  812. EXPECT_STREQ("text/html", val);
  813. }
  814. TEST(GetHeaderValueTest, SetContent) {
  815. Response res;
  816. res.set_content("html", "text/html");
  817. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  818. res.set_content("text", "text/plain");
  819. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  820. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  821. }
  822. TEST(GetHeaderValueTest, RegularValueInt) {
  823. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  828. Headers headers = {{"Content-Length", "x"}};
  829. auto is_invalid_value = false;
  830. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  831. is_invalid_value);
  832. EXPECT_EQ(0ull, val);
  833. EXPECT_TRUE(is_invalid_value);
  834. }
  835. TEST(GetHeaderValueTest, Range) {
  836. {
  837. Headers headers = {make_range_header({{1, -1}})};
  838. auto val = detail::get_header_value(headers, "Range", 0, 0);
  839. EXPECT_STREQ("bytes=1-", val);
  840. }
  841. {
  842. Headers headers = {make_range_header({{-1, 1}})};
  843. auto val = detail::get_header_value(headers, "Range", 0, 0);
  844. EXPECT_STREQ("bytes=-1", val);
  845. }
  846. {
  847. Headers headers = {make_range_header({{1, 10}})};
  848. auto val = detail::get_header_value(headers, "Range", 0, 0);
  849. EXPECT_STREQ("bytes=1-10", val);
  850. }
  851. {
  852. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  853. auto val = detail::get_header_value(headers, "Range", 0, 0);
  854. EXPECT_STREQ("bytes=1-10, 100-", val);
  855. }
  856. {
  857. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-10, 100-200", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=0-0, -1", val);
  865. }
  866. }
  867. TEST(ParseHeaderValueTest, Range) {
  868. {
  869. Ranges ranges;
  870. auto ret = detail::parse_range_header("bytes=1-", ranges);
  871. EXPECT_TRUE(ret);
  872. EXPECT_EQ(1u, ranges.size());
  873. EXPECT_EQ(1u, ranges[0].first);
  874. EXPECT_EQ(-1, ranges[0].second);
  875. }
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=-1", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(-1, ranges[0].first);
  882. EXPECT_EQ(1u, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(1u, ranges[0].first);
  890. EXPECT_EQ(10u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  895. EXPECT_FALSE(ret);
  896. }
  897. {
  898. Ranges ranges;
  899. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  900. EXPECT_TRUE(ret);
  901. EXPECT_EQ(2u, ranges.size());
  902. EXPECT_EQ(1u, ranges[0].first);
  903. EXPECT_EQ(10u, ranges[0].second);
  904. EXPECT_EQ(100u, ranges[1].first);
  905. EXPECT_EQ(-1, ranges[1].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret =
  910. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  911. EXPECT_TRUE(ret);
  912. EXPECT_EQ(3u, ranges.size());
  913. EXPECT_EQ(1u, ranges[0].first);
  914. EXPECT_EQ(10u, ranges[0].second);
  915. EXPECT_EQ(100u, ranges[1].first);
  916. EXPECT_EQ(200u, ranges[1].second);
  917. EXPECT_EQ(300u, ranges[2].first);
  918. EXPECT_EQ(400u, ranges[2].second);
  919. }
  920. {
  921. Ranges ranges;
  922. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  923. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  926. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  927. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  928. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  929. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  935. EXPECT_TRUE(ranges.empty());
  936. }
  937. }
  938. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  939. Request req;
  940. req.set_header("Accept-Encoding", "gzip");
  941. Response res;
  942. res.set_header("Content-Type", "text/plain");
  943. auto ret = detail::encoding_type(req, res);
  944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  945. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  946. #else
  947. EXPECT_TRUE(ret == detail::EncodingType::None);
  948. #endif
  949. }
  950. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  951. Request req;
  952. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  953. Response res;
  954. res.set_header("Content-Type", "text/plain");
  955. auto ret = detail::encoding_type(req, res);
  956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  957. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  958. #elif CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #elif CPPHTTPLIB_ZSTD_SUPPORT
  961. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  962. #else
  963. EXPECT_TRUE(ret == detail::EncodingType::None);
  964. #endif
  965. }
  966. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  967. Request req;
  968. req.set_header("Accept-Encoding",
  969. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  970. Response res;
  971. res.set_header("Content-Type", "text/plain");
  972. auto ret = detail::encoding_type(req, res);
  973. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  974. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  975. #elif CPPHTTPLIB_ZLIB_SUPPORT
  976. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  977. #elif CPPHTTPLIB_ZSTD_SUPPORT
  978. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  979. #else
  980. EXPECT_TRUE(ret == detail::EncodingType::None);
  981. #endif
  982. }
  983. TEST(BufferStreamTest, read) {
  984. detail::BufferStream strm1;
  985. Stream &strm = strm1;
  986. EXPECT_EQ(5, strm.write("hello"));
  987. char buf[512];
  988. EXPECT_EQ(2, strm.read(buf, 2));
  989. EXPECT_EQ('h', buf[0]);
  990. EXPECT_EQ('e', buf[1]);
  991. EXPECT_EQ(2, strm.read(buf, 2));
  992. EXPECT_EQ('l', buf[0]);
  993. EXPECT_EQ('l', buf[1]);
  994. EXPECT_EQ(1, strm.read(buf, 1));
  995. EXPECT_EQ('o', buf[0]);
  996. EXPECT_EQ(0, strm.read(buf, 1));
  997. }
  998. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  999. auto host = "www.httpwatch.com";
  1000. auto ip = hosted_at(host);
  1001. EXPECT_EQ("23.96.13.243", ip);
  1002. std::vector<std::string> addrs;
  1003. hosted_at(host, addrs);
  1004. EXPECT_EQ(1u, addrs.size());
  1005. }
  1006. #if 0 // It depends on each test environment...
  1007. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1008. auto host = "www.youtube.com";
  1009. std::vector<std::string> addrs;
  1010. hosted_at(host, addrs);
  1011. EXPECT_EQ(20u, addrs.size());
  1012. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1013. EXPECT_TRUE(it != addrs.end());
  1014. }
  1015. #endif
  1016. class ChunkedEncodingTest : public ::testing::Test {
  1017. protected:
  1018. ChunkedEncodingTest()
  1019. : cli_(HOST, PORT)
  1020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1021. ,
  1022. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1023. #endif
  1024. {
  1025. cli_.set_connection_timeout(2);
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. cli_.enable_server_certificate_verification(false);
  1028. #endif
  1029. }
  1030. virtual void SetUp() {
  1031. read_file("./image.jpg", image_data_);
  1032. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1033. res.set_content("Hello World!", "text/plain");
  1034. });
  1035. svr_.Get(
  1036. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1037. res.set_chunked_content_provider(
  1038. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1039. size_t remaining = image_data_.size() - offset;
  1040. if (remaining == 0) {
  1041. sink.done();
  1042. } else {
  1043. constexpr size_t CHUNK_SIZE = 1024;
  1044. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1045. sink.write(&image_data_[offset], send_size);
  1046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1047. }
  1048. return true;
  1049. });
  1050. });
  1051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1052. svr_.wait_until_ready();
  1053. }
  1054. virtual void TearDown() {
  1055. svr_.stop();
  1056. if (!request_threads_.empty()) {
  1057. std::this_thread::sleep_for(std::chrono::seconds(1));
  1058. for (auto &t : request_threads_) {
  1059. t.join();
  1060. }
  1061. }
  1062. t_.join();
  1063. }
  1064. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1065. SSLClient cli_;
  1066. SSLServer svr_;
  1067. #else
  1068. Client cli_;
  1069. Server svr_;
  1070. #endif
  1071. thread t_;
  1072. std::vector<thread> request_threads_;
  1073. std::string image_data_;
  1074. };
  1075. TEST_F(ChunkedEncodingTest, NormalGet) {
  1076. auto res = cli_.Get("/chunked");
  1077. ASSERT_TRUE(res);
  1078. std::string out;
  1079. read_file("./image.jpg", out);
  1080. EXPECT_EQ(StatusCode::OK_200, res->status);
  1081. EXPECT_EQ(out, res->body);
  1082. }
  1083. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1084. std::string body;
  1085. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1086. body.append(data, data_length);
  1087. return true;
  1088. });
  1089. ASSERT_TRUE(res);
  1090. std::string out;
  1091. read_file("./image.jpg", out);
  1092. EXPECT_EQ(StatusCode::OK_200, res->status);
  1093. EXPECT_EQ(out, body);
  1094. }
  1095. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1096. std::string body;
  1097. auto res = cli_.Get(
  1098. "/chunked",
  1099. [&](const Response &response) {
  1100. EXPECT_EQ(StatusCode::OK_200, response.status);
  1101. return true;
  1102. },
  1103. [&](const char *data, size_t data_length) {
  1104. body.append(data, data_length);
  1105. return true;
  1106. });
  1107. ASSERT_TRUE(res);
  1108. std::string out;
  1109. read_file("./image.jpg", out);
  1110. EXPECT_EQ(StatusCode::OK_200, res->status);
  1111. EXPECT_EQ(out, body);
  1112. }
  1113. TEST(RangeTest, FromHTTPBin_Online) {
  1114. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1115. auto host = "httpcan.org";
  1116. auto path = std::string{"/range/32"};
  1117. #else
  1118. auto host = "nghttp2.org";
  1119. auto path = std::string{"/httpbin/range/32"};
  1120. #endif
  1121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1122. auto port = 443;
  1123. SSLClient cli(host, port);
  1124. #else
  1125. auto port = 80;
  1126. Client cli(host, port);
  1127. #endif
  1128. cli.set_connection_timeout(5);
  1129. {
  1130. auto res = cli.Get(path);
  1131. ASSERT_TRUE(res);
  1132. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. }
  1135. {
  1136. Headers headers = {make_range_header({{1, -1}})};
  1137. auto res = cli.Get(path, headers);
  1138. ASSERT_TRUE(res);
  1139. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1141. }
  1142. {
  1143. Headers headers = {make_range_header({{1, 10}})};
  1144. auto res = cli.Get(path, headers);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("bcdefghijk", res->body);
  1147. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{0, 31}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{0, -1}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 32}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1168. }
  1169. }
  1170. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1171. auto host = "unresolvableaddress.local";
  1172. auto path = std::string{"/"};
  1173. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1174. auto port = 443;
  1175. SSLClient cli(host, port);
  1176. #else
  1177. auto port = 80;
  1178. Client cli(host, port);
  1179. #endif
  1180. cli.set_connection_timeout(1);
  1181. {
  1182. auto res = cli.Get(path);
  1183. ASSERT_FALSE(res);
  1184. }
  1185. std::this_thread::sleep_for(std::chrono::seconds(8));
  1186. }
  1187. TEST(ConnectionErrorTest, InvalidHost) {
  1188. auto host = "-abcde.com";
  1189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1190. auto port = 443;
  1191. SSLClient cli(host, port);
  1192. #else
  1193. auto port = 80;
  1194. Client cli(host, port);
  1195. #endif
  1196. cli.set_connection_timeout(std::chrono::seconds(2));
  1197. auto res = cli.Get("/");
  1198. ASSERT_TRUE(!res);
  1199. EXPECT_EQ(Error::Connection, res.error());
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost2) {
  1202. auto host = "httpcan.org/";
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host);
  1205. #else
  1206. Client cli(host);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_EQ(Error::Connection, res.error());
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1214. auto host = "httpcan.org/";
  1215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1216. SSLClient cli(host);
  1217. #else
  1218. Client cli(host);
  1219. #endif
  1220. cli.set_connection_timeout(std::chrono::seconds(2));
  1221. auto res = cli.Get("/");
  1222. ASSERT_TRUE(!res);
  1223. stringstream s;
  1224. s << "error code: " << res.error();
  1225. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidPort) {
  1228. auto host = "localhost";
  1229. auto port = 44380;
  1230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1231. SSLClient cli(host, port);
  1232. #else
  1233. Client cli(host, port);
  1234. #endif
  1235. cli.set_connection_timeout(std::chrono::seconds(2));
  1236. auto res = cli.Get("/");
  1237. ASSERT_TRUE(!res);
  1238. EXPECT_TRUE(Error::Connection == res.error() ||
  1239. Error::ConnectionTimeout == res.error());
  1240. }
  1241. TEST(ConnectionErrorTest, Timeout_Online) {
  1242. auto host = "google.com";
  1243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1244. auto port = 44380;
  1245. SSLClient cli(host, port);
  1246. #else
  1247. auto port = 8080;
  1248. Client cli(host, port);
  1249. #endif
  1250. cli.set_connection_timeout(std::chrono::seconds(2));
  1251. // only probe one address type so that the error reason
  1252. // correlates to the timed-out IPv4, not the unsupported
  1253. // IPv6 connection attempt
  1254. cli.set_address_family(AF_INET);
  1255. auto res = cli.Get("/");
  1256. ASSERT_TRUE(!res);
  1257. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1258. }
  1259. TEST(CancelTest, NoCancel_Online) {
  1260. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1261. auto host = "httpcan.org";
  1262. auto path = std::string{"/range/32"};
  1263. #else
  1264. auto host = "nghttp2.org";
  1265. auto path = std::string{"/httpbin/range/32"};
  1266. #endif
  1267. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1268. auto port = 443;
  1269. SSLClient cli(host, port);
  1270. #else
  1271. auto port = 80;
  1272. Client cli(host, port);
  1273. #endif
  1274. cli.set_connection_timeout(std::chrono::seconds(5));
  1275. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1278. EXPECT_EQ(StatusCode::OK_200, res->status);
  1279. }
  1280. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1281. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1282. auto host = "httpcan.org";
  1283. auto path = std::string{"/range/32"};
  1284. #else
  1285. auto host = "nghttp2.org";
  1286. auto path = std::string{"/httpbin/range/32"};
  1287. #endif
  1288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1289. auto port = 443;
  1290. SSLClient cli(host, port);
  1291. #else
  1292. auto port = 80;
  1293. Client cli(host, port);
  1294. #endif
  1295. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1296. cli.set_connection_timeout(std::chrono::seconds(5));
  1297. ASSERT_TRUE(!res);
  1298. EXPECT_EQ(Error::Canceled, res.error());
  1299. }
  1300. TEST(CancelTest, WithCancelLargePayload_Online) {
  1301. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1302. auto host = "httpcan.org";
  1303. auto path = std::string{"/range/65536"};
  1304. #else
  1305. auto host = "nghttp2.org";
  1306. auto path = std::string{"/httpbin/range/65536"};
  1307. #endif
  1308. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(std::chrono::seconds(5));
  1316. uint32_t count = 0;
  1317. auto res =
  1318. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1319. ASSERT_TRUE(!res);
  1320. EXPECT_EQ(Error::Canceled, res.error());
  1321. }
  1322. TEST(CancelTest, NoCancelPost) {
  1323. Server svr;
  1324. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1325. res.set_content("Hello World!", "text/plain");
  1326. });
  1327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. thread.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. Client cli(HOST, PORT);
  1335. cli.set_connection_timeout(std::chrono::seconds(5));
  1336. auto res =
  1337. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1338. "application/json", [](uint64_t, uint64_t) { return true; });
  1339. ASSERT_TRUE(res);
  1340. EXPECT_EQ("Hello World!", res->body);
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. }
  1343. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1344. Server svr;
  1345. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1346. res.set_content("Hello World!", "text/plain");
  1347. });
  1348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1349. auto se = detail::scope_exit([&] {
  1350. svr.stop();
  1351. thread.join();
  1352. ASSERT_FALSE(svr.is_running());
  1353. });
  1354. svr.wait_until_ready();
  1355. Client cli(HOST, PORT);
  1356. cli.set_connection_timeout(std::chrono::seconds(5));
  1357. auto res =
  1358. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1359. "application/json", [](uint64_t, uint64_t) { return false; });
  1360. ASSERT_TRUE(!res);
  1361. EXPECT_EQ(Error::Canceled, res.error());
  1362. }
  1363. TEST(CancelTest, WithCancelLargePayloadPost) {
  1364. Server svr;
  1365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1366. res.set_content(LARGE_DATA, "text/plain");
  1367. });
  1368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. thread.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. Client cli(HOST, PORT);
  1376. cli.set_connection_timeout(std::chrono::seconds(5));
  1377. auto res =
  1378. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1379. "application/json", [](uint64_t, uint64_t) { return false; });
  1380. ASSERT_TRUE(!res);
  1381. EXPECT_EQ(Error::Canceled, res.error());
  1382. }
  1383. TEST(CancelTest, NoCancelPut) {
  1384. Server svr;
  1385. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1386. res.set_content("Hello World!", "text/plain");
  1387. });
  1388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. thread.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, PORT);
  1396. cli.set_connection_timeout(std::chrono::seconds(5));
  1397. auto res =
  1398. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1399. "application/json", [](uint64_t, uint64_t) { return true; });
  1400. ASSERT_TRUE(res);
  1401. EXPECT_EQ("Hello World!", res->body);
  1402. EXPECT_EQ(StatusCode::OK_200, res->status);
  1403. }
  1404. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1405. Server svr;
  1406. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1407. res.set_content("Hello World!", "text/plain");
  1408. });
  1409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1410. auto se = detail::scope_exit([&] {
  1411. svr.stop();
  1412. thread.join();
  1413. ASSERT_FALSE(svr.is_running());
  1414. });
  1415. svr.wait_until_ready();
  1416. Client cli(HOST, PORT);
  1417. cli.set_connection_timeout(std::chrono::seconds(5));
  1418. auto res =
  1419. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1420. "application/json", [](uint64_t, uint64_t) { return false; });
  1421. ASSERT_TRUE(!res);
  1422. EXPECT_EQ(Error::Canceled, res.error());
  1423. }
  1424. TEST(CancelTest, WithCancelLargePayloadPut) {
  1425. Server svr;
  1426. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1427. res.set_content(LARGE_DATA, "text/plain");
  1428. });
  1429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1430. auto se = detail::scope_exit([&] {
  1431. svr.stop();
  1432. thread.join();
  1433. ASSERT_FALSE(svr.is_running());
  1434. });
  1435. svr.wait_until_ready();
  1436. Client cli(HOST, PORT);
  1437. cli.set_connection_timeout(std::chrono::seconds(5));
  1438. auto res =
  1439. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1440. "application/json", [](uint64_t, uint64_t) { return false; });
  1441. ASSERT_TRUE(!res);
  1442. EXPECT_EQ(Error::Canceled, res.error());
  1443. }
  1444. TEST(CancelTest, NoCancelPatch) {
  1445. Server svr;
  1446. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1447. res.set_content("Hello World!", "text/plain");
  1448. });
  1449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. thread.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. Client cli(HOST, PORT);
  1457. cli.set_connection_timeout(std::chrono::seconds(5));
  1458. auto res =
  1459. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1460. "application/json", [](uint64_t, uint64_t) { return true; });
  1461. ASSERT_TRUE(res);
  1462. EXPECT_EQ("Hello World!", res->body);
  1463. EXPECT_EQ(StatusCode::OK_200, res->status);
  1464. }
  1465. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1466. Server svr;
  1467. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1468. res.set_content("Hello World!", "text/plain");
  1469. });
  1470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1471. auto se = detail::scope_exit([&] {
  1472. svr.stop();
  1473. thread.join();
  1474. ASSERT_FALSE(svr.is_running());
  1475. });
  1476. svr.wait_until_ready();
  1477. Client cli(HOST, PORT);
  1478. cli.set_connection_timeout(std::chrono::seconds(5));
  1479. auto res =
  1480. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1481. "application/json", [](uint64_t, uint64_t) { return false; });
  1482. ASSERT_TRUE(!res);
  1483. EXPECT_EQ(Error::Canceled, res.error());
  1484. }
  1485. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1486. Server svr;
  1487. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1488. res.set_content(LARGE_DATA, "text/plain");
  1489. });
  1490. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. thread.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. Client cli(HOST, PORT);
  1498. cli.set_connection_timeout(std::chrono::seconds(5));
  1499. auto res =
  1500. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1501. "application/json", [](uint64_t, uint64_t) { return false; });
  1502. ASSERT_TRUE(!res);
  1503. EXPECT_EQ(Error::Canceled, res.error());
  1504. }
  1505. TEST(CancelTest, NoCancelDelete) {
  1506. Server svr;
  1507. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1508. res.set_content("Hello World!", "text/plain");
  1509. });
  1510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1511. auto se = detail::scope_exit([&] {
  1512. svr.stop();
  1513. thread.join();
  1514. ASSERT_FALSE(svr.is_running());
  1515. });
  1516. svr.wait_until_ready();
  1517. Client cli(HOST, PORT);
  1518. cli.set_connection_timeout(std::chrono::seconds(5));
  1519. auto res =
  1520. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1521. "application/json", [](uint64_t, uint64_t) { return true; });
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ("Hello World!", res->body);
  1524. EXPECT_EQ(StatusCode::OK_200, res->status);
  1525. }
  1526. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1527. Server svr;
  1528. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1529. res.set_content("Hello World!", "text/plain");
  1530. });
  1531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. thread.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. Client cli(HOST, PORT);
  1539. cli.set_connection_timeout(std::chrono::seconds(5));
  1540. auto res =
  1541. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1542. "application/json", [](uint64_t, uint64_t) { return false; });
  1543. ASSERT_TRUE(!res);
  1544. EXPECT_EQ(Error::Canceled, res.error());
  1545. }
  1546. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1547. Server svr;
  1548. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_connection_timeout(std::chrono::seconds(5));
  1560. auto res =
  1561. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1562. "application/json", [](uint64_t, uint64_t) { return false; });
  1563. ASSERT_TRUE(!res);
  1564. EXPECT_EQ(Error::Canceled, res.error());
  1565. }
  1566. static std::string remove_whitespace(const std::string &input) {
  1567. std::string output;
  1568. output.reserve(input.size());
  1569. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1570. [](unsigned char c) { return !std::isspace(c); });
  1571. return output;
  1572. }
  1573. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1574. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1575. auto host = "httpcan.org";
  1576. auto path = std::string{"/basic-auth/hello/world"};
  1577. #else
  1578. auto host = "nghttp2.org";
  1579. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1580. #endif
  1581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1582. auto port = 443;
  1583. SSLClient cli(host, port);
  1584. #else
  1585. auto port = 80;
  1586. Client cli(host, port);
  1587. #endif
  1588. {
  1589. auto res = cli.Get(path);
  1590. ASSERT_TRUE(res);
  1591. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1592. }
  1593. {
  1594. auto res =
  1595. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1596. ASSERT_TRUE(res);
  1597. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1598. remove_whitespace(res->body));
  1599. EXPECT_EQ(StatusCode::OK_200, res->status);
  1600. }
  1601. {
  1602. cli.set_basic_auth("hello", "world");
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "bad");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("bad", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1620. }
  1621. }
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1624. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1625. auto host = "httpcan.org";
  1626. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1627. auto paths = std::vector<std::string>{
  1628. "/digest-auth/auth/hello/world/MD5",
  1629. "/digest-auth/auth/hello/world/SHA-256",
  1630. "/digest-auth/auth/hello/world/SHA-512",
  1631. };
  1632. #else
  1633. auto host = "nghttp2.org";
  1634. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/httpbin/digest-auth/auth/hello/world/MD5",
  1637. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1638. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1639. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1640. };
  1641. #endif
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. {
  1645. auto res = cli.Get(unauth_path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_digest_auth("hello", "world");
  1651. for (const auto &path : paths) {
  1652. auto res = cli.Get(path.c_str());
  1653. ASSERT_TRUE(res);
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. std::string algo(path.substr(path.rfind('/') + 1));
  1656. EXPECT_EQ(
  1657. remove_whitespace("{\"algorithm\":\"" + algo +
  1658. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1659. remove_whitespace(res->body));
  1660. #else
  1661. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1662. remove_whitespace(res->body));
  1663. #endif
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. }
  1666. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1667. cli.set_digest_auth("hello", "bad");
  1668. for (const auto &path : paths) {
  1669. auto res = cli.Get(path.c_str());
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. #endif
  1674. }
  1675. }
  1676. #endif
  1677. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1678. auto host = "google.com";
  1679. auto another_host = "example.com";
  1680. auto wrong_ip = "0.0.0.0";
  1681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1682. SSLClient cli(host);
  1683. #else
  1684. Client cli(host);
  1685. #endif
  1686. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1687. auto res = cli.Get("/");
  1688. ASSERT_TRUE(res);
  1689. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1690. }
  1691. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1692. auto host = "google.com";
  1693. auto wrong_ip = "0.0.0.0";
  1694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1695. SSLClient cli(host);
  1696. #else
  1697. Client cli(host);
  1698. #endif
  1699. cli.set_hostname_addr_map({{host, wrong_ip}});
  1700. auto res = cli.Get("/");
  1701. ASSERT_TRUE(!res);
  1702. EXPECT_EQ(Error::Connection, res.error());
  1703. }
  1704. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1705. auto host = "nghttp2.org";
  1706. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1707. SSLClient cli(host);
  1708. #else
  1709. Client cli(host);
  1710. #endif
  1711. cli.set_follow_location(true);
  1712. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(StatusCode::OK_200, res->status);
  1715. }
  1716. TEST(RedirectTest, Redirect_Online) {
  1717. auto host = "nghttp2.org";
  1718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1719. SSLClient cli(host);
  1720. #else
  1721. Client cli(host);
  1722. #endif
  1723. cli.set_follow_location(true);
  1724. auto res = cli.Get("/httpbin/redirect/3");
  1725. ASSERT_TRUE(res);
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. TEST(RelativeRedirectTest, Redirect_Online) {
  1729. auto host = "nghttp2.org";
  1730. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1731. SSLClient cli(host);
  1732. #else
  1733. Client cli(host);
  1734. #endif
  1735. cli.set_follow_location(true);
  1736. auto res = cli.Get("/httpbin/relative-redirect/3");
  1737. ASSERT_TRUE(res);
  1738. EXPECT_EQ(StatusCode::OK_200, res->status);
  1739. }
  1740. TEST(TooManyRedirectTest, Redirect_Online) {
  1741. auto host = "nghttp2.org";
  1742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1743. SSLClient cli(host);
  1744. #else
  1745. Client cli(host);
  1746. #endif
  1747. cli.set_follow_location(true);
  1748. auto res = cli.Get("/httpbin/redirect/21");
  1749. ASSERT_TRUE(!res);
  1750. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1751. }
  1752. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1753. TEST(YahooRedirectTest, Redirect_Online) {
  1754. Client cli("yahoo.com");
  1755. auto res = cli.Get("/");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1758. cli.set_follow_location(true);
  1759. res = cli.Get("/");
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1763. }
  1764. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1765. #define REDIR_HOST "httpbingo.org"
  1766. #define REDIR_PATH "/redirect-to"
  1767. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1768. SSLClient cli(REDIR_HOST);
  1769. cli.set_follow_location(true);
  1770. auto res =
  1771. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. Params params;
  1779. params.emplace("url", "http://example.com");
  1780. params.emplace("status_code", "302");
  1781. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. }
  1794. TEST(UrlWithSpace, Redirect_Online) {
  1795. SSLClient cli("edge.forgecdn.net");
  1796. cli.set_follow_location(true);
  1797. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1798. ASSERT_TRUE(res);
  1799. EXPECT_EQ(StatusCode::OK_200, res->status);
  1800. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1801. }
  1802. #endif
  1803. #if !defined(_WIN32) && !defined(_WIN64)
  1804. TEST(ReceiveSignals, Signal) {
  1805. auto setupSignalHandlers = []() {
  1806. struct sigaction act;
  1807. sigemptyset(&act.sa_mask);
  1808. act.sa_flags = SA_SIGINFO;
  1809. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1810. switch (sig) {
  1811. case SIGINT:
  1812. default: break;
  1813. }
  1814. };
  1815. ::sigaction(SIGINT, &act, nullptr);
  1816. };
  1817. Server svr;
  1818. int port = 0;
  1819. auto thread = std::thread([&]() {
  1820. setupSignalHandlers();
  1821. port = svr.bind_to_any_port(HOST);
  1822. svr.listen_after_bind();
  1823. });
  1824. auto se = detail::scope_exit([&] {
  1825. svr.stop();
  1826. thread.join();
  1827. ASSERT_FALSE(svr.is_running());
  1828. });
  1829. svr.wait_until_ready();
  1830. ASSERT_TRUE(svr.is_running());
  1831. pthread_kill(thread.native_handle(), SIGINT);
  1832. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1833. ASSERT_TRUE(svr.is_running());
  1834. }
  1835. #endif
  1836. TEST(RedirectToDifferentPort, Redirect) {
  1837. Server svr1;
  1838. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1839. res.set_content("Hello World!", "text/plain");
  1840. });
  1841. int svr1_port = 0;
  1842. auto thread1 = std::thread([&]() {
  1843. svr1_port = svr1.bind_to_any_port(HOST);
  1844. svr1.listen_after_bind();
  1845. });
  1846. Server svr2;
  1847. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1848. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1849. });
  1850. int svr2_port = 0;
  1851. auto thread2 = std::thread([&]() {
  1852. svr2_port = svr2.bind_to_any_port(HOST);
  1853. svr2.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr2.stop();
  1857. thread2.join();
  1858. svr1.stop();
  1859. thread1.join();
  1860. ASSERT_FALSE(svr2.is_running());
  1861. ASSERT_FALSE(svr1.is_running());
  1862. });
  1863. svr1.wait_until_ready();
  1864. svr2.wait_until_ready();
  1865. Client cli("localhost", svr2_port);
  1866. cli.set_follow_location(true);
  1867. auto res = cli.Get("/2");
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", res->body);
  1871. }
  1872. TEST(RedirectFromPageWithContent, Redirect) {
  1873. Server svr;
  1874. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("___", "text/plain");
  1876. res.set_redirect("/2");
  1877. });
  1878. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!", "text/plain");
  1880. });
  1881. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. th.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. {
  1889. Client cli("localhost", PORT);
  1890. cli.set_follow_location(true);
  1891. std::string body;
  1892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1893. body.append(data, data_length);
  1894. return true;
  1895. });
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::OK_200, res->status);
  1898. EXPECT_EQ("Hello World!", body);
  1899. }
  1900. {
  1901. Client cli("localhost", PORT);
  1902. std::string body;
  1903. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1904. body.append(data, data_length);
  1905. return true;
  1906. });
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::Found_302, res->status);
  1909. EXPECT_EQ("___", body);
  1910. }
  1911. }
  1912. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1913. Server svr;
  1914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1915. res.set_content("___", "text/plain");
  1916. // res.set_redirect("/2");
  1917. res.set_redirect("http://[::1]:1234/2");
  1918. });
  1919. svr.Get("/2", [&](const Request &req, Response &res) {
  1920. auto host_header = req.headers.find("Host");
  1921. ASSERT_TRUE(host_header != req.headers.end());
  1922. EXPECT_EQ("[::1]:1234", host_header->second);
  1923. res.set_content("Hello World!", "text/plain");
  1924. });
  1925. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. th.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1932. // actually starts anything, so the condition !svr.is_running() will
  1933. // always remain true, and the loop never stops.
  1934. // This basically counts how many milliseconds have passed since the
  1935. // call to svr.listen(), and if after 5 seconds nothing started yet
  1936. // aborts the test.
  1937. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1938. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1939. ASSERT_LT(milliseconds, 5000U);
  1940. }
  1941. {
  1942. Client cli("http://[::1]:1234");
  1943. cli.set_follow_location(true);
  1944. std::string body;
  1945. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(StatusCode::OK_200, res->status);
  1951. EXPECT_EQ("Hello World!", body);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. std::string body;
  1956. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::Found_302, res->status);
  1962. EXPECT_EQ("___", body);
  1963. }
  1964. }
  1965. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1966. Server svr;
  1967. svr.Get("/foo", [](const Request &req, Response &res) {
  1968. auto a = req.params.find("a");
  1969. if (a != req.params.end()) {
  1970. res.set_content((*a).second, "text/plain");
  1971. res.status = StatusCode::OK_200;
  1972. } else {
  1973. res.status = StatusCode::BadRequest_400;
  1974. }
  1975. });
  1976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1977. auto se = detail::scope_exit([&] {
  1978. svr.stop();
  1979. thread.join();
  1980. ASSERT_FALSE(svr.is_running());
  1981. });
  1982. svr.wait_until_ready();
  1983. {
  1984. Client cli(HOST, PORT);
  1985. cli.set_path_encode(false);
  1986. auto res = cli.Get("/foo?a=explicitly+encoded");
  1987. ASSERT_TRUE(res);
  1988. EXPECT_EQ(StatusCode::OK_200, res->status);
  1989. // This expects it back with a space, as the `+` won't have been
  1990. // url-encoded, and server-side the params get decoded turning `+`
  1991. // into spaces.
  1992. EXPECT_EQ("explicitly encoded", res->body);
  1993. }
  1994. }
  1995. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1996. Server svr;
  1997. svr.Get("/", [](const Request &req, Response &) {
  1998. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1999. });
  2000. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2001. auto se = detail::scope_exit([&] {
  2002. svr.stop();
  2003. thread.join();
  2004. ASSERT_FALSE(svr.is_running());
  2005. });
  2006. svr.wait_until_ready();
  2007. {
  2008. Client cli(HOST, PORT);
  2009. cli.set_path_encode(false);
  2010. auto res = cli.Get("/?something=%0A");
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. }
  2014. }
  2015. TEST(BindServerTest, DISABLED_BindDualStack) {
  2016. Server svr;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. {
  2028. Client cli("127.0.0.1", PORT);
  2029. auto res = cli.Get("/1");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::OK_200, res->status);
  2032. EXPECT_EQ("Hello World!", res->body);
  2033. }
  2034. {
  2035. Client cli("::1", PORT);
  2036. auto res = cli.Get("/1");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("Hello World!", res->body);
  2040. }
  2041. }
  2042. TEST(BindServerTest, BindAndListenSeparately) {
  2043. Server svr;
  2044. int port = svr.bind_to_any_port("0.0.0.0");
  2045. ASSERT_TRUE(svr.is_valid());
  2046. ASSERT_TRUE(port > 0);
  2047. svr.stop();
  2048. }
  2049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2050. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2052. CLIENT_CA_CERT_DIR);
  2053. int port = svr.bind_to_any_port("0.0.0.0");
  2054. ASSERT_TRUE(svr.is_valid());
  2055. ASSERT_TRUE(port > 0);
  2056. svr.stop();
  2057. }
  2058. #endif
  2059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2060. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2061. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2062. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2063. int port = svr.bind_to_any_port("0.0.0.0");
  2064. ASSERT_TRUE(svr.is_valid());
  2065. ASSERT_TRUE(port > 0);
  2066. svr.stop();
  2067. }
  2068. #endif
  2069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2070. X509 *readCertificate(const std::string &strFileName) {
  2071. std::ifstream inStream(strFileName);
  2072. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2073. std::istreambuf_iterator<char>());
  2074. if (strCertPEM.empty()) return (nullptr);
  2075. BIO *pbCert = BIO_new(BIO_s_mem());
  2076. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2077. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2078. BIO_free(pbCert);
  2079. return (pCert);
  2080. }
  2081. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2082. std::ifstream inStream(strFileName);
  2083. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2084. std::istreambuf_iterator<char>());
  2085. if (strPrivateKeyPEM.empty()) return (nullptr);
  2086. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2087. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2088. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2089. BIO_free(pbPrivKey);
  2090. return (pPrivateKey);
  2091. }
  2092. TEST(BindServerTest, UpdateCerts) {
  2093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2094. int port = svr.bind_to_any_port("0.0.0.0");
  2095. ASSERT_TRUE(svr.is_valid());
  2096. ASSERT_TRUE(port > 0);
  2097. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2098. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2099. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2100. ASSERT_TRUE(cert != nullptr);
  2101. ASSERT_TRUE(ca_cert != nullptr);
  2102. ASSERT_TRUE(key != nullptr);
  2103. X509_STORE *cert_store = X509_STORE_new();
  2104. X509_STORE_add_cert(cert_store, ca_cert);
  2105. svr.update_certs(cert, key, cert_store);
  2106. ASSERT_TRUE(svr.is_valid());
  2107. svr.stop();
  2108. X509_free(cert);
  2109. X509_free(ca_cert);
  2110. EVP_PKEY_free(key);
  2111. }
  2112. #endif
  2113. TEST(ErrorHandlerTest, ContentLength) {
  2114. Server svr;
  2115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2116. res.status = StatusCode::OK_200;
  2117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2118. "text/html"); // <= Content-Length still 13
  2119. });
  2120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!\n", "text/plain");
  2122. res.status = 524;
  2123. });
  2124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2125. auto se = detail::scope_exit([&] {
  2126. svr.stop();
  2127. thread.join();
  2128. ASSERT_FALSE(svr.is_running());
  2129. });
  2130. svr.wait_until_ready();
  2131. {
  2132. Client cli(HOST, PORT);
  2133. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2139. }
  2140. }
  2141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2142. TEST(ExceptionTest, WithoutExceptionHandler) {
  2143. Server svr;
  2144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2145. throw std::runtime_error("exception...");
  2146. });
  2147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2148. throw std::runtime_error("exception\r\n...");
  2149. });
  2150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. listen_thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. Client cli("localhost", PORT);
  2158. {
  2159. auto res = cli.Get("/exception");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2163. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2164. }
  2165. {
  2166. auto res = cli.Get("/unknown");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2169. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2170. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2171. }
  2172. }
  2173. TEST(ExceptionTest, WithExceptionHandler) {
  2174. Server svr;
  2175. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2176. std::exception_ptr ep) {
  2177. EXPECT_FALSE(ep == nullptr);
  2178. try {
  2179. std::rethrow_exception(ep);
  2180. } catch (std::exception &e) {
  2181. EXPECT_EQ("abc", std::string(e.what()));
  2182. } catch (...) {}
  2183. res.status = StatusCode::InternalServerError_500;
  2184. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2185. "text/html"); // <= Content-Length still 13 at this point
  2186. });
  2187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2188. res.set_content("Hello World!\n", "text/plain");
  2189. throw std::runtime_error("abc");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. for (size_t i = 0; i < 10; i++) {
  2199. Client cli(HOST, PORT);
  2200. for (size_t j = 0; j < 100; j++) {
  2201. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2205. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2206. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2207. }
  2208. cli.set_keep_alive(true);
  2209. for (size_t j = 0; j < 100; j++) {
  2210. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2216. }
  2217. }
  2218. }
  2219. TEST(ExceptionTest, AndErrorHandler) {
  2220. Server svr;
  2221. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2222. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2223. });
  2224. svr.set_exception_handler(
  2225. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2226. EXPECT_FALSE(ep == nullptr);
  2227. try {
  2228. std::rethrow_exception(ep);
  2229. } catch (std::exception &e) {
  2230. res.set_content(e.what(), "text/html");
  2231. } catch (...) {}
  2232. res.status = StatusCode::InternalServerError_500;
  2233. });
  2234. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2235. throw std::runtime_error("EXCEPTION");
  2236. });
  2237. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2238. res.set_content("ERROR", "text/html");
  2239. res.status = StatusCode::InternalServerError_500;
  2240. });
  2241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2242. auto se = detail::scope_exit([&] {
  2243. svr.stop();
  2244. thread.join();
  2245. ASSERT_FALSE(svr.is_running());
  2246. });
  2247. svr.wait_until_ready();
  2248. Client cli(HOST, PORT);
  2249. {
  2250. auto res = cli.Get("/exception");
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2253. EXPECT_EQ("EXCEPTION", res->body);
  2254. }
  2255. {
  2256. auto res = cli.Get("/error");
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2259. EXPECT_EQ("ERROR", res->body);
  2260. }
  2261. {
  2262. auto res = cli.Get("/invalid");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("NOT_FOUND", res->body);
  2266. }
  2267. }
  2268. #endif
  2269. TEST(NoContentTest, ContentLength) {
  2270. Server svr;
  2271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2272. res.status = StatusCode::NoContent_204;
  2273. });
  2274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. {
  2282. Client cli(HOST, PORT);
  2283. auto res = cli.Get("/hi");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2287. }
  2288. }
  2289. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2292. ASSERT_TRUE(svr.is_valid());
  2293. #else
  2294. Server svr;
  2295. #endif
  2296. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2297. if (req.path == "/routing_handler") {
  2298. res.set_header("PRE_ROUTING", "on");
  2299. res.set_content("Routing Handler", "text/plain");
  2300. return httplib::Server::HandlerResponse::Handled;
  2301. }
  2302. return httplib::Server::HandlerResponse::Unhandled;
  2303. });
  2304. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2305. res.set_content("Error", "text/html");
  2306. });
  2307. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2308. if (req.path == "/routing_handler") {
  2309. res.set_header("POST_ROUTING", "on");
  2310. }
  2311. });
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.set_content("Hello World!\n", "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2324. SSLClient cli(HOST, PORT);
  2325. cli.enable_server_certificate_verification(false);
  2326. #else
  2327. Client cli(HOST, PORT);
  2328. #endif
  2329. auto res = cli.Get("/routing_handler");
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::OK_200, res->status);
  2332. EXPECT_EQ("Routing Handler", res->body);
  2333. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2334. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2335. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2336. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2337. }
  2338. {
  2339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2340. SSLClient cli(HOST, PORT);
  2341. cli.enable_server_certificate_verification(false);
  2342. #else
  2343. Client cli(HOST, PORT);
  2344. #endif
  2345. auto res = cli.Get("/hi");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(StatusCode::OK_200, res->status);
  2348. EXPECT_EQ("Hello World!\n", res->body);
  2349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2351. }
  2352. {
  2353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2354. SSLClient cli(HOST, PORT);
  2355. cli.enable_server_certificate_verification(false);
  2356. #else
  2357. Client cli(HOST, PORT);
  2358. #endif
  2359. auto res = cli.Get("/aaa");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2362. EXPECT_EQ("Error", res->body);
  2363. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2364. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2365. }
  2366. }
  2367. TEST(RequestHandlerTest, PreRequestHandler) {
  2368. auto route_path = "/user/:user";
  2369. Server svr;
  2370. svr.Get("/hi", [](const Request &, Response &res) {
  2371. res.set_content("hi", "text/plain");
  2372. });
  2373. svr.Get(route_path, [](const Request &req, Response &res) {
  2374. res.set_content(req.path_params.at("user"), "text/plain");
  2375. });
  2376. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2377. if (req.matched_route == route_path) {
  2378. auto user = req.path_params.at("user");
  2379. if (user != "john") {
  2380. res.status = StatusCode::Forbidden_403;
  2381. res.set_content("error", "text/html");
  2382. return Server::HandlerResponse::Handled;
  2383. }
  2384. }
  2385. return Server::HandlerResponse::Unhandled;
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. Client cli(HOST, PORT);
  2395. {
  2396. auto res = cli.Get("/hi");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ("hi", res->body);
  2400. }
  2401. {
  2402. auto res = cli.Get("/user/john");
  2403. ASSERT_TRUE(res);
  2404. EXPECT_EQ(StatusCode::OK_200, res->status);
  2405. EXPECT_EQ("john", res->body);
  2406. }
  2407. {
  2408. auto res = cli.Get("/user/invalid-user");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2411. EXPECT_EQ("error", res->body);
  2412. }
  2413. }
  2414. TEST(InvalidFormatTest, StatusCode) {
  2415. Server svr;
  2416. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2417. res.set_content("Hello World!\n", "text/plain");
  2418. res.status = 9999; // Status should be a three-digit code...
  2419. });
  2420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2421. auto se = detail::scope_exit([&] {
  2422. svr.stop();
  2423. thread.join();
  2424. ASSERT_FALSE(svr.is_running());
  2425. });
  2426. svr.wait_until_ready();
  2427. {
  2428. Client cli(HOST, PORT);
  2429. auto res = cli.Get("/hi");
  2430. ASSERT_FALSE(res);
  2431. }
  2432. }
  2433. TEST(URLFragmentTest, WithFragment) {
  2434. Server svr;
  2435. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2436. EXPECT_TRUE(req.target == "/hi");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. {
  2446. Client cli(HOST, PORT);
  2447. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2448. EXPECT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::OK_200, res->status);
  2450. res = cli.Get("/hi%23key1=val1=key2=val2");
  2451. EXPECT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2453. }
  2454. }
  2455. TEST(HeaderWriter, SetHeaderWriter) {
  2456. Server svr;
  2457. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2458. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2459. return detail::write_headers(strm, hdrs);
  2460. });
  2461. svr.Get("/hi", [](const Request &req, Response &res) {
  2462. auto it = req.headers.find("CustomClientHeader");
  2463. EXPECT_TRUE(it != req.headers.end());
  2464. EXPECT_EQ(it->second, "CustomClientValue");
  2465. res.set_content("Hello World!\n", "text/plain");
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. {
  2475. Client cli(HOST, PORT);
  2476. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2477. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2478. return detail::write_headers(strm, hdrs);
  2479. });
  2480. auto res = cli.Get("/hi");
  2481. EXPECT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::OK_200, res->status);
  2483. auto it = res->headers.find("CustomServerHeader");
  2484. EXPECT_TRUE(it != res->headers.end());
  2485. EXPECT_EQ(it->second, "CustomServerValue");
  2486. }
  2487. }
  2488. class ServerTest : public ::testing::Test {
  2489. protected:
  2490. ServerTest()
  2491. : cli_(HOST, PORT)
  2492. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2493. ,
  2494. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2495. #endif
  2496. {
  2497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2498. cli_.enable_server_certificate_verification(false);
  2499. #endif
  2500. }
  2501. virtual void SetUp() {
  2502. svr_.set_mount_point("/", "./www");
  2503. svr_.set_mount_point("/mount", "./www2");
  2504. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2505. svr_.Get("/hi",
  2506. [&](const Request & /*req*/, Response &res) {
  2507. res.set_content("Hello World!", "text/plain");
  2508. })
  2509. .Get("/file_content",
  2510. [&](const Request & /*req*/, Response &res) {
  2511. res.set_file_content("./www/dir/test.html");
  2512. })
  2513. .Get("/file_content_with_content_type",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_file_content("./www/file", "text/plain");
  2516. })
  2517. .Get("/invalid_file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/invalid_file_path");
  2520. })
  2521. .Get("/http_response_splitting",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2524. EXPECT_EQ(0U, res.headers.size());
  2525. EXPECT_FALSE(res.has_header("a"));
  2526. res.set_header("a", "1\nSet-Cookie: a=1");
  2527. EXPECT_EQ(0U, res.headers.size());
  2528. EXPECT_FALSE(res.has_header("a"));
  2529. res.set_header("a", "1\rSet-Cookie: a=1");
  2530. EXPECT_EQ(0U, res.headers.size());
  2531. EXPECT_FALSE(res.has_header("a"));
  2532. res.set_header("a\r\nb", "0");
  2533. EXPECT_EQ(0U, res.headers.size());
  2534. EXPECT_FALSE(res.has_header("a"));
  2535. res.set_header("a\rb", "0");
  2536. EXPECT_EQ(0U, res.headers.size());
  2537. EXPECT_FALSE(res.has_header("a"));
  2538. res.set_header("a\nb", "0");
  2539. EXPECT_EQ(0U, res.headers.size());
  2540. EXPECT_FALSE(res.has_header("a"));
  2541. res.set_redirect("1\r\nSet-Cookie: a=1");
  2542. EXPECT_EQ(0U, res.headers.size());
  2543. EXPECT_FALSE(res.has_header("Location"));
  2544. })
  2545. .Get("/slow",
  2546. [&](const Request & /*req*/, Response &res) {
  2547. std::this_thread::sleep_for(std::chrono::seconds(2));
  2548. res.set_content("slow", "text/plain");
  2549. })
  2550. #if 0
  2551. .Post("/slowpost",
  2552. [&](const Request & /*req*/, Response &res) {
  2553. std::this_thread::sleep_for(std::chrono::seconds(2));
  2554. res.set_content("slow", "text/plain");
  2555. })
  2556. #endif
  2557. .Get("/remote_addr",
  2558. [&](const Request &req, Response &res) {
  2559. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2560. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2561. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2562. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2563. res.set_content(req.remote_addr, "text/plain");
  2564. })
  2565. .Get("/local_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2568. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2571. auto local_addr = req.local_addr;
  2572. auto local_port = std::to_string(req.local_port);
  2573. res.set_content(local_addr.append(":").append(local_port),
  2574. "text/plain");
  2575. })
  2576. .Get("/endwith%",
  2577. [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. })
  2580. .Get("/a\\+\\+b",
  2581. [&](const Request &req, Response &res) {
  2582. ASSERT_TRUE(req.has_param("a +b"));
  2583. auto val = req.get_param_value("a +b");
  2584. res.set_content(val, "text/plain");
  2585. })
  2586. .Get("/", [&](const Request & /*req*/,
  2587. Response &res) { res.set_redirect("/hi"); })
  2588. .Post("/1",
  2589. [](const Request & /*req*/, Response &res) {
  2590. res.set_redirect("/2", StatusCode::SeeOther_303);
  2591. })
  2592. .Get("/2",
  2593. [](const Request & /*req*/, Response &res) {
  2594. res.set_content("redirected.", "text/plain");
  2595. res.status = StatusCode::OK_200;
  2596. })
  2597. .Post("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name") && req.has_param("note")) {
  2600. persons_[req.get_param_value("name")] =
  2601. req.get_param_value("note");
  2602. } else {
  2603. res.status = StatusCode::BadRequest_400;
  2604. }
  2605. })
  2606. .Put("/person",
  2607. [&](const Request &req, Response &res) {
  2608. if (req.has_param("name") && req.has_param("note")) {
  2609. persons_[req.get_param_value("name")] =
  2610. req.get_param_value("note");
  2611. } else {
  2612. res.status = StatusCode::BadRequest_400;
  2613. }
  2614. })
  2615. .Get("/person/(.*)",
  2616. [&](const Request &req, Response &res) {
  2617. string name = req.matches[1];
  2618. if (persons_.find(name) != persons_.end()) {
  2619. auto note = persons_[name];
  2620. res.set_content(note, "text/plain");
  2621. } else {
  2622. res.status = StatusCode::NotFound_404;
  2623. }
  2624. })
  2625. .Delete("/person",
  2626. [&](const Request &req, Response &res) {
  2627. if (req.has_param("name")) {
  2628. string name = req.get_param_value("name");
  2629. if (persons_.find(name) != persons_.end()) {
  2630. persons_.erase(name);
  2631. res.set_content("DELETED", "text/plain");
  2632. } else {
  2633. res.status = StatusCode::NotFound_404;
  2634. }
  2635. } else {
  2636. res.status = StatusCode::BadRequest_400;
  2637. }
  2638. })
  2639. .Post("/x-www-form-urlencoded-json",
  2640. [&](const Request &req, Response &res) {
  2641. auto json = req.get_param_value("json");
  2642. ASSERT_EQ(JSON_DATA, json);
  2643. res.set_content(json, "appliation/json");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Get("/streamed-chunked",
  2647. [&](const Request & /*req*/, Response &res) {
  2648. res.set_chunked_content_provider(
  2649. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2650. sink.os << "123";
  2651. sink.os << "456";
  2652. sink.os << "789";
  2653. sink.done();
  2654. return true;
  2655. });
  2656. })
  2657. .Get("/streamed-chunked-with-prohibited-trailer",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. auto i = new int(0);
  2660. // Declare both a prohibited trailer (Content-Length) and an
  2661. // allowed one
  2662. res.set_header("Trailer", "Content-Length, X-Allowed");
  2663. res.set_chunked_content_provider(
  2664. "text/plain",
  2665. [i](size_t /*offset*/, DataSink &sink) {
  2666. switch (*i) {
  2667. case 0: sink.os << "123"; break;
  2668. case 1: sink.os << "456"; break;
  2669. case 2: sink.os << "789"; break;
  2670. case 3: {
  2671. sink.done_with_trailer(
  2672. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2673. } break;
  2674. }
  2675. (*i)++;
  2676. return true;
  2677. },
  2678. [i](bool success) {
  2679. EXPECT_TRUE(success);
  2680. delete i;
  2681. });
  2682. })
  2683. .Get("/streamed-chunked2",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. auto i = new int(0);
  2686. res.set_chunked_content_provider(
  2687. "text/plain",
  2688. [i](size_t /*offset*/, DataSink &sink) {
  2689. switch (*i) {
  2690. case 0: sink.os << "123"; break;
  2691. case 1: sink.os << "456"; break;
  2692. case 2: sink.os << "789"; break;
  2693. case 3: sink.done(); break;
  2694. }
  2695. (*i)++;
  2696. return true;
  2697. },
  2698. [i](bool success) {
  2699. EXPECT_TRUE(success);
  2700. delete i;
  2701. });
  2702. })
  2703. .Get("/streamed-chunked-with-trailer",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. auto i = new int(0);
  2706. res.set_header("Trailer", "Dummy1, Dummy2");
  2707. res.set_chunked_content_provider(
  2708. "text/plain",
  2709. [i](size_t /*offset*/, DataSink &sink) {
  2710. switch (*i) {
  2711. case 0: sink.os << "123"; break;
  2712. case 1: sink.os << "456"; break;
  2713. case 2: sink.os << "789"; break;
  2714. case 3: {
  2715. sink.done_with_trailer(
  2716. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2717. } break;
  2718. }
  2719. (*i)++;
  2720. return true;
  2721. },
  2722. [i](bool success) {
  2723. EXPECT_TRUE(success);
  2724. delete i;
  2725. });
  2726. })
  2727. .Get("/streamed",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_content_provider(
  2730. 6, "text/plain",
  2731. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2732. sink.os << (offset < 3 ? "a" : "b");
  2733. return true;
  2734. });
  2735. })
  2736. .Get("/streamed-with-range",
  2737. [&](const Request &req, Response &res) {
  2738. auto data = new std::string("abcdefg");
  2739. res.set_content_provider(
  2740. data->size(), "text/plain",
  2741. [data](size_t offset, size_t length, DataSink &sink) {
  2742. size_t DATA_CHUNK_SIZE = 4;
  2743. const auto &d = *data;
  2744. auto out_len =
  2745. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2746. auto ret =
  2747. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2748. EXPECT_TRUE(ret);
  2749. return true;
  2750. },
  2751. [data, &req](bool success) {
  2752. EXPECT_EQ(success, !req.has_param("error"));
  2753. delete data;
  2754. });
  2755. })
  2756. .Get("/streamed-cancel",
  2757. [&](const Request & /*req*/, Response &res) {
  2758. res.set_content_provider(
  2759. size_t(-1), "text/plain",
  2760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2761. sink.os << "data_chunk";
  2762. return true;
  2763. });
  2764. })
  2765. .Get("/regex-with-delimiter",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. ASSERT_TRUE(req.has_param("key"));
  2768. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2769. })
  2770. .Get("/with-range",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_content("abcdefg", "text/plain");
  2773. })
  2774. .Get("/test-start-time",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_NE(req.start_time_,
  2777. std::chrono::steady_clock::time_point::min());
  2778. })
  2779. .Get("/with-range-customized-response",
  2780. [&](const Request & /*req*/, Response &res) {
  2781. res.status = StatusCode::BadRequest_400;
  2782. res.set_content(JSON_DATA, "application/json");
  2783. })
  2784. .Post("/chunked",
  2785. [&](const Request &req, Response & /*res*/) {
  2786. EXPECT_EQ(req.body, "dechunked post body");
  2787. })
  2788. .Post("/large-chunked",
  2789. [&](const Request &req, Response & /*res*/) {
  2790. std::string expected(6 * 30 * 1024u, 'a');
  2791. EXPECT_EQ(req.body, expected);
  2792. })
  2793. .Post("/multipart",
  2794. [&](const Request &req, Response & /*res*/) {
  2795. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2796. req.form.get_field_count("text2") +
  2797. req.form.get_field_count("file3") +
  2798. req.form.get_field_count("file4"));
  2799. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2800. req.form.get_file_count("file2"));
  2801. ASSERT_TRUE(!req.form.has_file("???"));
  2802. ASSERT_TRUE(!req.form.has_field("???"));
  2803. ASSERT_TRUE(req.body.empty());
  2804. {
  2805. const auto &text = req.form.get_field("text1");
  2806. EXPECT_EQ("text default", text);
  2807. }
  2808. {
  2809. const auto &text = req.form.get_field("text2");
  2810. EXPECT_EQ("aωb", text);
  2811. }
  2812. {
  2813. const auto &file = req.form.get_file("file1");
  2814. EXPECT_EQ("hello.txt", file.filename);
  2815. EXPECT_EQ("text/plain", file.content_type);
  2816. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2817. }
  2818. {
  2819. const auto &file = req.form.get_file("file2");
  2820. EXPECT_EQ("world.json", file.filename);
  2821. EXPECT_EQ("application/json", file.content_type);
  2822. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2823. }
  2824. {
  2825. const auto &text = req.form.get_field("file3");
  2826. EXPECT_EQ(0u, text.size());
  2827. }
  2828. {
  2829. const auto &text = req.form.get_field("file4");
  2830. EXPECT_EQ(0u, text.size());
  2831. }
  2832. })
  2833. .Post("/multipart/multi_file_values",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2836. req.form.get_field_count("multi_text1"));
  2837. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2838. ASSERT_TRUE(!req.form.has_file("???"));
  2839. ASSERT_TRUE(!req.form.has_field("???"));
  2840. ASSERT_TRUE(req.body.empty());
  2841. {
  2842. const auto &text = req.form.get_field("text");
  2843. EXPECT_EQ("default text", text);
  2844. }
  2845. {
  2846. const auto &text1_values = req.form.get_fields("multi_text1");
  2847. EXPECT_EQ(2u, text1_values.size());
  2848. EXPECT_EQ("aaaaa", text1_values[0]);
  2849. EXPECT_EQ("bbbbb", text1_values[1]);
  2850. }
  2851. {
  2852. const auto &file1_values = req.form.get_files("multi_file1");
  2853. EXPECT_EQ(2u, file1_values.size());
  2854. auto file1 = file1_values[0];
  2855. EXPECT_EQ(file1.filename, "hello.txt");
  2856. EXPECT_EQ(file1.content_type, "text/plain");
  2857. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2858. auto file2 = file1_values[1];
  2859. EXPECT_EQ(file2.filename, "world.json");
  2860. EXPECT_EQ(file2.content_type, "application/json");
  2861. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2862. }
  2863. })
  2864. .Post("/empty",
  2865. [&](const Request &req, Response &res) {
  2866. EXPECT_EQ(req.body, "");
  2867. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2869. res.set_content("empty", "text/plain");
  2870. })
  2871. .Post("/empty-no-content-type",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "");
  2874. EXPECT_FALSE(req.has_header("Content-Type"));
  2875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2876. res.set_content("empty-no-content-type", "text/plain");
  2877. })
  2878. .Post("/path-only",
  2879. [&](const Request &req, Response &res) {
  2880. EXPECT_EQ(req.body, "");
  2881. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2882. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2883. res.set_content("path-only", "text/plain");
  2884. })
  2885. .Post("/path-headers-only",
  2886. [&](const Request &req, Response &res) {
  2887. EXPECT_EQ(req.body, "");
  2888. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2889. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2890. EXPECT_EQ("world", req.get_header_value("hello"));
  2891. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2892. res.set_content("path-headers-only", "text/plain");
  2893. })
  2894. .Post("/post-large",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(req.body, LARGE_DATA);
  2897. res.set_content(req.body, "text/plain");
  2898. })
  2899. .Post("/post-loopback",
  2900. [&](const Request &, Response &res,
  2901. ContentReader const &content_reader) {
  2902. std::string body;
  2903. content_reader([&](const char *data, size_t data_length) {
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. res.set_content(body, "text/plain");
  2908. })
  2909. .Put("/put-loopback",
  2910. [&](const Request &, Response &res,
  2911. ContentReader const &content_reader) {
  2912. std::string body;
  2913. content_reader([&](const char *data, size_t data_length) {
  2914. body.append(data, data_length);
  2915. return true;
  2916. });
  2917. res.set_content(body, "text/plain");
  2918. })
  2919. .Patch("/patch-loopback",
  2920. [&](const Request &, Response &res,
  2921. ContentReader const &content_reader) {
  2922. std::string body;
  2923. content_reader([&](const char *data, size_t data_length) {
  2924. body.append(data, data_length);
  2925. return true;
  2926. });
  2927. res.set_content(body, "text/plain");
  2928. })
  2929. .Put("/empty-no-content-type",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "");
  2932. EXPECT_FALSE(req.has_header("Content-Type"));
  2933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2934. res.set_content("empty-no-content-type", "text/plain");
  2935. })
  2936. .Put("/put",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "PUT");
  2939. res.set_content(req.body, "text/plain");
  2940. })
  2941. .Put("/put-large",
  2942. [&](const Request &req, Response &res) {
  2943. EXPECT_EQ(req.body, LARGE_DATA);
  2944. res.set_content(req.body, "text/plain");
  2945. })
  2946. .Patch("/patch",
  2947. [&](const Request &req, Response &res) {
  2948. EXPECT_EQ(req.body, "PATCH");
  2949. res.set_content(req.body, "text/plain");
  2950. })
  2951. .Delete("/delete",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_content("DELETE", "text/plain");
  2954. })
  2955. .Delete("/delete-body",
  2956. [&](const Request &req, Response &res) {
  2957. EXPECT_EQ(req.body, "content");
  2958. res.set_content(req.body, "text/plain");
  2959. })
  2960. .Options(R"(\*)",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2963. })
  2964. .Get("/request-target",
  2965. [&](const Request &req, Response & /*res*/) {
  2966. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2967. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2968. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2969. })
  2970. .Get("/long-query-value",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2973. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2974. })
  2975. .Get("/too-long-query-value",
  2976. [&](const Request &req, Response & /*res*/) {
  2977. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2978. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2979. })
  2980. .Get("/array-param",
  2981. [&](const Request &req, Response & /*res*/) {
  2982. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2983. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2984. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2985. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2986. })
  2987. .Post("/validate-no-multiple-headers",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2990. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2991. })
  2992. .Post("/content_receiver",
  2993. [&](const Request &req, Response &res,
  2994. const ContentReader &content_reader) {
  2995. if (req.is_multipart_form_data()) {
  2996. std::vector<FormData> items;
  2997. content_reader(
  2998. [&](const FormData &file) {
  2999. items.push_back(file);
  3000. return true;
  3001. },
  3002. [&](const char *data, size_t data_length) {
  3003. items.back().content.append(data, data_length);
  3004. return true;
  3005. });
  3006. EXPECT_EQ(5u, items.size());
  3007. {
  3008. const auto &file = get_file_value(items, "text1");
  3009. EXPECT_TRUE(file.filename.empty());
  3010. EXPECT_EQ("text default", file.content);
  3011. }
  3012. {
  3013. const auto &file = get_file_value(items, "text2");
  3014. EXPECT_TRUE(file.filename.empty());
  3015. EXPECT_EQ("aωb", file.content);
  3016. }
  3017. {
  3018. const auto &file = get_file_value(items, "file1");
  3019. EXPECT_EQ("hello.txt", file.filename);
  3020. EXPECT_EQ("text/plain", file.content_type);
  3021. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3022. }
  3023. {
  3024. const auto &file = get_file_value(items, "file2");
  3025. EXPECT_EQ("world.json", file.filename);
  3026. EXPECT_EQ("application/json", file.content_type);
  3027. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3028. }
  3029. {
  3030. const auto &file = get_file_value(items, "file3");
  3031. EXPECT_TRUE(file.filename.empty());
  3032. EXPECT_EQ("application/octet-stream", file.content_type);
  3033. EXPECT_EQ(0u, file.content.size());
  3034. }
  3035. } else {
  3036. std::string body;
  3037. content_reader([&](const char *data, size_t data_length) {
  3038. EXPECT_EQ(7U, data_length);
  3039. body.append(data, data_length);
  3040. return true;
  3041. });
  3042. EXPECT_EQ(body, "content");
  3043. res.set_content(body, "text/plain");
  3044. }
  3045. })
  3046. .Put("/content_receiver",
  3047. [&](const Request & /*req*/, Response &res,
  3048. const ContentReader &content_reader) {
  3049. std::string body;
  3050. content_reader([&](const char *data, size_t data_length) {
  3051. body.append(data, data_length);
  3052. return true;
  3053. });
  3054. EXPECT_EQ(body, "content");
  3055. res.set_content(body, "text/plain");
  3056. })
  3057. .Patch("/content_receiver",
  3058. [&](const Request & /*req*/, Response &res,
  3059. const ContentReader &content_reader) {
  3060. std::string body;
  3061. content_reader([&](const char *data, size_t data_length) {
  3062. body.append(data, data_length);
  3063. return true;
  3064. });
  3065. EXPECT_EQ(body, "content");
  3066. res.set_content(body, "text/plain");
  3067. })
  3068. .Post("/query-string-and-body",
  3069. [&](const Request &req, Response & /*res*/) {
  3070. ASSERT_TRUE(req.has_param("key"));
  3071. EXPECT_EQ(req.get_param_value("key"), "value");
  3072. EXPECT_EQ(req.body, "content");
  3073. })
  3074. .Get("/last-request",
  3075. [&](const Request &req, Response & /*res*/) {
  3076. EXPECT_EQ("close", req.get_header_value("Connection"));
  3077. })
  3078. .Get(R"(/redirect/(\d+))",
  3079. [&](const Request &req, Response &res) {
  3080. auto num = std::stoi(req.matches[1]) + 1;
  3081. std::string url = "/redirect/" + std::to_string(num);
  3082. res.set_redirect(url);
  3083. })
  3084. .Post("/binary",
  3085. [&](const Request &req, Response &res) {
  3086. EXPECT_EQ(4U, req.body.size());
  3087. EXPECT_EQ("application/octet-stream",
  3088. req.get_header_value("Content-Type"));
  3089. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3090. res.set_content(req.body, "application/octet-stream");
  3091. })
  3092. .Put("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Patch("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Delete("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Get("/issue1772",
  3117. [&](const Request & /*req*/, Response &res) {
  3118. res.status = 401;
  3119. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3120. })
  3121. .Delete("/issue609",
  3122. [](const httplib::Request &, httplib::Response &res,
  3123. const httplib::ContentReader &) {
  3124. res.set_content("ok", "text/plain");
  3125. })
  3126. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3127. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3128. .Get("/compress",
  3129. [&](const Request & /*req*/, Response &res) {
  3130. res.set_content(
  3131. "12345678901234567890123456789012345678901234567890123456789"
  3132. "01234567890123456789012345678901234567890",
  3133. "text/plain");
  3134. })
  3135. .Get("/nocompress",
  3136. [&](const Request & /*req*/, Response &res) {
  3137. res.set_content(
  3138. "12345678901234567890123456789012345678901234567890123456789"
  3139. "01234567890123456789012345678901234567890",
  3140. "application/octet-stream");
  3141. })
  3142. .Post("/compress-multipart",
  3143. [&](const Request &req, Response & /*res*/) {
  3144. EXPECT_EQ(2u, req.form.fields.size());
  3145. ASSERT_TRUE(!req.form.has_field("???"));
  3146. {
  3147. const auto &text = req.form.get_field("key1");
  3148. EXPECT_EQ("test", text);
  3149. }
  3150. {
  3151. const auto &text = req.form.get_field("key2");
  3152. EXPECT_EQ("--abcdefg123", text);
  3153. }
  3154. })
  3155. #endif
  3156. ;
  3157. persons_["john"] = "programmer";
  3158. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3159. svr_.wait_until_ready();
  3160. }
  3161. virtual void TearDown() {
  3162. svr_.stop();
  3163. if (!request_threads_.empty()) {
  3164. std::this_thread::sleep_for(std::chrono::seconds(1));
  3165. for (auto &t : request_threads_) {
  3166. t.join();
  3167. }
  3168. }
  3169. t_.join();
  3170. }
  3171. map<string, string> persons_;
  3172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3173. SSLClient cli_;
  3174. SSLServer svr_;
  3175. #else
  3176. Client cli_;
  3177. Server svr_;
  3178. #endif
  3179. thread t_;
  3180. std::vector<thread> request_threads_;
  3181. };
  3182. TEST_F(ServerTest, GetMethod200) {
  3183. auto res = cli_.Get("/hi");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ("HTTP/1.1", res->version);
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. EXPECT_EQ("OK", res->reason);
  3188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3190. EXPECT_EQ("Hello World!", res->body);
  3191. }
  3192. TEST_F(ServerTest, GetEmptyFile) {
  3193. auto res = cli_.Get("/empty_file");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3198. EXPECT_EQ("", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetFileContent) {
  3201. auto res = cli_.Get("/file_content");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("test.html", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContentWithRange) {
  3209. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3214. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3215. EXPECT_EQ("est", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetFileContentWithContentType) {
  3218. auto res = cli_.Get("/file_content_with_content_type");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("file\n", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetInvalidFileContent) {
  3226. auto res = cli_.Get("/invalid_file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3231. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ("HTTP/1.1", res->version);
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3236. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. TEST_F(ServerTest, GetMethod302) {
  3240. auto res = cli_.Get("/");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::Found_302, res->status);
  3243. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3244. }
  3245. TEST_F(ServerTest, GetMethod302Redirect) {
  3246. cli_.set_follow_location(true);
  3247. auto res = cli_.Get("/");
  3248. ASSERT_TRUE(res);
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. EXPECT_EQ("Hello World!", res->body);
  3251. EXPECT_EQ("/hi", res->location);
  3252. }
  3253. TEST_F(ServerTest, GetMethod404) {
  3254. auto res = cli_.Get("/invalid");
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3257. }
  3258. TEST_F(ServerTest, HeadMethod200) {
  3259. auto res = cli_.Head("/hi");
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. EXPECT_TRUE(res->body.empty());
  3264. }
  3265. TEST_F(ServerTest, HeadMethod200Static) {
  3266. auto res = cli_.Head("/mount/dir/index.html");
  3267. ASSERT_TRUE(res);
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3270. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod404) {
  3274. auto res = cli_.Head("/invalid");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3277. EXPECT_TRUE(res->body.empty());
  3278. }
  3279. TEST_F(ServerTest, GetMethodPersonJohn) {
  3280. auto res = cli_.Get("/person/john");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("programmer", res->body);
  3285. }
  3286. TEST_F(ServerTest, PostMethod1) {
  3287. auto res = cli_.Get("/person/john1");
  3288. ASSERT_TRUE(res);
  3289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3290. res = cli_.Post("/person", "name=john1&note=coder",
  3291. "application/x-www-form-urlencoded");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::OK_200, res->status);
  3294. res = cli_.Get("/person/john1");
  3295. ASSERT_TRUE(res);
  3296. ASSERT_EQ(StatusCode::OK_200, res->status);
  3297. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3298. ASSERT_EQ("coder", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostMethod2) {
  3301. auto res = cli_.Get("/person/john2");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john2");
  3306. params.emplace("note", "coder");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john2");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("coder", res->body);
  3315. }
  3316. TEST_F(ServerTest, PutMethod3) {
  3317. auto res = cli_.Get("/person/john3");
  3318. ASSERT_TRUE(res);
  3319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3320. Params params;
  3321. params.emplace("name", "john3");
  3322. params.emplace("note", "coder");
  3323. res = cli_.Put("/person", params);
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::OK_200, res->status);
  3326. res = cli_.Get("/person/john3");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3330. ASSERT_EQ("coder", res->body);
  3331. }
  3332. TEST_F(ServerTest, DeleteMethod1) {
  3333. auto res = cli_.Get("/person/john4");
  3334. ASSERT_TRUE(res);
  3335. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3336. Params params;
  3337. params.emplace("name", "john4");
  3338. params.emplace("note", "coder");
  3339. res = cli_.Post("/person", params);
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. res = cli_.Get("/person/john4");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3346. ASSERT_EQ("coder", res->body);
  3347. Params delete_params;
  3348. delete_params.emplace("name", "john4");
  3349. res = cli_.Delete("/person", delete_params);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john4");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod2) {
  3358. auto res = cli_.Get("/person/john5");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john5");
  3363. params.emplace("note", "developer");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john5");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("developer", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john5");
  3374. Headers headers;
  3375. headers.emplace("Custom-Header", "test-value");
  3376. res = cli_.Delete("/person", headers, delete_params);
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::OK_200, res->status);
  3379. ASSERT_EQ("DELETED", res->body);
  3380. res = cli_.Get("/person/john5");
  3381. ASSERT_TRUE(res);
  3382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3383. }
  3384. TEST_F(ServerTest, DeleteMethod3) {
  3385. auto res = cli_.Get("/person/john6");
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3388. Params params;
  3389. params.emplace("name", "john6");
  3390. params.emplace("note", "tester");
  3391. res = cli_.Post("/person", params);
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. res = cli_.Get("/person/john6");
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. ASSERT_EQ("tester", res->body);
  3399. Params delete_params;
  3400. delete_params.emplace("name", "john6");
  3401. Headers headers;
  3402. headers.emplace("Custom-Header", "test-value");
  3403. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3404. ASSERT_TRUE(res);
  3405. ASSERT_EQ(StatusCode::OK_200, res->status);
  3406. ASSERT_EQ("DELETED", res->body);
  3407. res = cli_.Get("/person/john6");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3412. Params params;
  3413. params.emplace("json", JSON_DATA);
  3414. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ(JSON_DATA, res->body);
  3418. }
  3419. TEST_F(ServerTest, PostEmptyContent) {
  3420. auto res = cli_.Post("/empty", "", "text/plain");
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::OK_200, res->status);
  3423. ASSERT_EQ("empty", res->body);
  3424. }
  3425. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3426. auto res = cli_.Post("/empty-no-content-type");
  3427. ASSERT_TRUE(res);
  3428. ASSERT_EQ(StatusCode::OK_200, res->status);
  3429. ASSERT_EQ("empty-no-content-type", res->body);
  3430. }
  3431. TEST_F(ServerTest, PostPathOnly) {
  3432. auto res = cli_.Post("/path-only");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::OK_200, res->status);
  3435. ASSERT_EQ("path-only", res->body);
  3436. }
  3437. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3438. auto res = cli_.Post("/path-headers-only",
  3439. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("path-headers-only", res->body);
  3443. }
  3444. TEST_F(ServerTest, PostLarge) {
  3445. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ(LARGE_DATA, res->body);
  3449. }
  3450. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3451. auto res = cli_.Put("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetMethodDir) {
  3457. auto res = cli_.Get("/dir/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. auto body = R"(<html>
  3462. <head>
  3463. </head>
  3464. <body>
  3465. <a href="/dir/test.html">Test</a>
  3466. <a href="/hi">hi</a>
  3467. </body>
  3468. </html>
  3469. )";
  3470. EXPECT_EQ(body, res->body);
  3471. }
  3472. TEST_F(ServerTest, GetMethodDirTest) {
  3473. auto res = cli_.Get("/dir/test.html");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("test.html", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3480. auto res = cli_.Get("/dir/../dir/test.html");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3484. EXPECT_EQ("test.html", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethodInvalidPath) {
  3487. auto res = cli_.Get("/dir/../test.html");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3490. }
  3491. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3492. auto res = cli_.Get("/../www/dir/test.html");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3495. }
  3496. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3497. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3500. }
  3501. TEST_F(ServerTest, GetMethodDirMountTest) {
  3502. auto res = cli_.Get("/mount/dir/test.html");
  3503. ASSERT_TRUE(res);
  3504. EXPECT_EQ(StatusCode::OK_200, res->status);
  3505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3506. EXPECT_EQ("test.html", res->body);
  3507. }
  3508. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3509. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("test.html", res->body);
  3514. }
  3515. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3516. auto res = cli_.Get("/mount/dir/../test.html");
  3517. ASSERT_TRUE(res);
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3521. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. }
  3525. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3526. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3527. ASSERT_TRUE(res);
  3528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3529. }
  3530. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3531. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3534. }
  3535. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3536. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, PostMethod303) {
  3541. auto res = cli_.Post("/1", "body", "text/plain");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3544. EXPECT_EQ("/2", res->get_header_value("Location"));
  3545. }
  3546. TEST_F(ServerTest, PostMethod303Redirect) {
  3547. cli_.set_follow_location(true);
  3548. auto res = cli_.Post("/1", "body", "text/plain");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ(StatusCode::OK_200, res->status);
  3551. EXPECT_EQ("redirected.", res->body);
  3552. EXPECT_EQ("/2", res->location);
  3553. }
  3554. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3555. auto res = cli_.Get("/dir/test.abcde");
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3559. EXPECT_EQ("abcde", res->body);
  3560. }
  3561. TEST_F(ServerTest, StaticFileRange) {
  3562. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3565. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3566. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3567. EXPECT_EQ(true, res->has_header("Content-Range"));
  3568. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3569. EXPECT_EQ(std::string("cd"), res->body);
  3570. }
  3571. TEST_F(ServerTest, StaticFileRanges) {
  3572. auto res =
  3573. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3576. EXPECT_TRUE(
  3577. res->get_header_value("Content-Type")
  3578. .find(
  3579. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3580. 0);
  3581. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3582. }
  3583. TEST_F(ServerTest, StaticFileRangeHead) {
  3584. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3585. ASSERT_TRUE(res);
  3586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3587. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3589. EXPECT_EQ(true, res->has_header("Content-Range"));
  3590. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3591. }
  3592. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3593. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3597. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3598. EXPECT_EQ(true, res->has_header("Content-Range"));
  3599. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3600. res->get_header_value("Content-Range"));
  3601. EXPECT_EQ("LAST\n", res->body);
  3602. }
  3603. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3604. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3609. EXPECT_EQ(true, res->has_header("Content-Range"));
  3610. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3611. }
  3612. TEST_F(ServerTest, StaticFileBigFile) {
  3613. auto res = cli_.Get("/dir/1MB.txt");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3617. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3618. }
  3619. TEST_F(ServerTest, InvalidBaseDirMount) {
  3620. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3621. }
  3622. TEST_F(ServerTest, Binary) {
  3623. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3624. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3625. "application/octet-stream");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ(4U, res->body.size());
  3629. res = cli_.Put("/binary", binary.data(), binary.size(),
  3630. "application/octet-stream");
  3631. ASSERT_TRUE(res);
  3632. ASSERT_EQ(StatusCode::OK_200, res->status);
  3633. ASSERT_EQ(4U, res->body.size());
  3634. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3635. "application/octet-stream");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ(4U, res->body.size());
  3639. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3640. "application/octet-stream");
  3641. ASSERT_TRUE(res);
  3642. ASSERT_EQ(StatusCode::OK_200, res->status);
  3643. ASSERT_EQ(4U, res->body.size());
  3644. }
  3645. TEST_F(ServerTest, BinaryString) {
  3646. auto binary = std::string("\x00\x01\x02\x03", 4);
  3647. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. ASSERT_EQ(4U, res->body.size());
  3651. res = cli_.Put("/binary", binary, "application/octet-stream");
  3652. ASSERT_TRUE(res);
  3653. ASSERT_EQ(StatusCode::OK_200, res->status);
  3654. ASSERT_EQ(4U, res->body.size());
  3655. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. }
  3664. TEST_F(ServerTest, EmptyRequest) {
  3665. auto res = cli_.Get("");
  3666. ASSERT_TRUE(!res);
  3667. EXPECT_EQ(Error::Connection, res.error());
  3668. }
  3669. TEST_F(ServerTest, LongRequest) {
  3670. std::string request;
  3671. for (size_t i = 0; i < 545; i++) {
  3672. request += "/TooLongRequest";
  3673. }
  3674. request += "OK";
  3675. auto res = cli_.Get(request.c_str());
  3676. ASSERT_TRUE(res);
  3677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3678. }
  3679. TEST_F(ServerTest, TooLongRequest) {
  3680. std::string request;
  3681. for (size_t i = 0; i < 546; i++) {
  3682. request += "/TooLongRequest";
  3683. }
  3684. request += "_NG";
  3685. auto start = std::chrono::high_resolution_clock::now();
  3686. cli_.set_keep_alive(true);
  3687. auto res = cli_.Get(request.c_str());
  3688. auto end = std::chrono::high_resolution_clock::now();
  3689. auto elapsed =
  3690. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3691. .count();
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3694. EXPECT_LE(elapsed, 100);
  3695. EXPECT_EQ("close", res->get_header_value("Connection"));
  3696. EXPECT_FALSE(cli_.is_socket_open());
  3697. }
  3698. TEST_F(ServerTest, AlmostTooLongRequest) {
  3699. // test for #2046 - URI length check shouldn't include other content on req
  3700. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3701. // leading /, space, HTTP/1.1)
  3702. std::string request =
  3703. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3704. auto res = cli_.Get(request.c_str());
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3707. }
  3708. TEST_F(ServerTest, LongHeader) {
  3709. Request req;
  3710. req.method = "GET";
  3711. req.path = "/hi";
  3712. std::string host_and_port;
  3713. host_and_port += HOST;
  3714. host_and_port += ":";
  3715. host_and_port += std::to_string(PORT);
  3716. req.headers.emplace("Host", host_and_port.c_str());
  3717. req.headers.emplace("Accept", "*/*");
  3718. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3719. req.headers.emplace(
  3720. "Header-Name",
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@");
  3750. auto res = std::make_shared<Response>();
  3751. auto error = Error::Success;
  3752. auto ret = cli_.send(req, *res, error);
  3753. ASSERT_TRUE(ret);
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST_F(ServerTest, LongQueryValue) {
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3760. auto end = std::chrono::high_resolution_clock::now();
  3761. auto elapsed =
  3762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3763. .count();
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3766. EXPECT_LE(elapsed, 100);
  3767. EXPECT_EQ("close", res->get_header_value("Connection"));
  3768. EXPECT_FALSE(cli_.is_socket_open());
  3769. }
  3770. TEST_F(ServerTest, TooLongQueryValue) {
  3771. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3772. ASSERT_FALSE(res);
  3773. EXPECT_EQ(Error::Read, res.error());
  3774. }
  3775. TEST_F(ServerTest, TooLongHeader) {
  3776. Request req;
  3777. req.method = "GET";
  3778. req.path = "/hi";
  3779. std::string host_and_port;
  3780. host_and_port += HOST;
  3781. host_and_port += ":";
  3782. host_and_port += std::to_string(PORT);
  3783. req.headers.emplace("Host", host_and_port.c_str());
  3784. req.headers.emplace("Accept", "*/*");
  3785. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3786. req.headers.emplace(
  3787. "Header-Name",
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@");
  3817. auto res = std::make_shared<Response>();
  3818. auto error = Error::Success;
  3819. auto ret = cli_.send(req, *res, error);
  3820. ASSERT_TRUE(ret);
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. TEST_F(ServerTest, HeaderCountAtLimit) {
  3824. // Test with headers just under the 100 limit
  3825. httplib::Headers headers;
  3826. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3827. // This should keep us just under the 100 header limit
  3828. for (int i = 0; i < 95; i++) {
  3829. std::string name = "X-Test-Header-" + std::to_string(i);
  3830. std::string value = "value" + std::to_string(i);
  3831. headers.emplace(name, value);
  3832. }
  3833. // This should work fine as we're under the limit
  3834. auto res = cli_.Get("/hi", headers);
  3835. EXPECT_TRUE(res);
  3836. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3837. }
  3838. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3839. // Test with many headers to exceed the 100 limit
  3840. httplib::Headers headers;
  3841. // Add 150 headers to definitely exceed the 100 limit
  3842. for (int i = 0; i < 150; i++) {
  3843. std::string name = "X-Test-Header-" + std::to_string(i);
  3844. std::string value = "value" + std::to_string(i);
  3845. headers.emplace(name, value);
  3846. }
  3847. // This should fail due to exceeding header count limit
  3848. cli_.set_keep_alive(true);
  3849. auto res = cli_.Get("/hi", headers);
  3850. // The request should either fail or return 400 Bad Request
  3851. if (res) {
  3852. // If we get a response, it should be 400 Bad Request
  3853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3854. } else {
  3855. // Or the request should fail entirely
  3856. EXPECT_FALSE(res);
  3857. }
  3858. EXPECT_EQ("close", res->get_header_value("Connection"));
  3859. EXPECT_FALSE(cli_.is_socket_open());
  3860. }
  3861. TEST_F(ServerTest, PercentEncoding) {
  3862. auto res = cli_.Get("/e%6edwith%");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, PercentEncodingUnicode) {
  3867. auto res = cli_.Get("/e%u006edwith%");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, InvalidPercentEncoding) {
  3872. auto res = cli_.Get("/%endwith%");
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3875. }
  3876. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3877. auto res = cli_.Get("/%uendwith%");
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3880. }
  3881. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3882. auto res = cli_.Get("/hello?aaa=bbb%");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3885. }
  3886. TEST_F(ServerTest, PlusSignEncoding) {
  3887. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. EXPECT_EQ("a +b", res->body);
  3891. }
  3892. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3893. // This test simulates a potential DoS attack using many headers
  3894. // to verify our security fix prevents memory exhaustion
  3895. httplib::Headers attack_headers;
  3896. // Attempt to add many headers like an attacker would (200 headers to far
  3897. // exceed limit)
  3898. for (int i = 0; i < 200; i++) {
  3899. std::string name = "X-Attack-Header-" + std::to_string(i);
  3900. std::string value = "attack_payload_" + std::to_string(i);
  3901. attack_headers.emplace(name, value);
  3902. }
  3903. // Try to POST with excessive headers
  3904. cli_.set_keep_alive(true);
  3905. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3906. // Should either fail or return 400 Bad Request due to security limit
  3907. if (res) {
  3908. // If we get a response, it should be 400 Bad Request
  3909. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3910. } else {
  3911. // Request failed, which is the expected behavior for DoS protection
  3912. EXPECT_FALSE(res);
  3913. }
  3914. EXPECT_EQ("close", res->get_header_value("Connection"));
  3915. EXPECT_FALSE(cli_.is_socket_open());
  3916. }
  3917. TEST_F(ServerTest, MultipartFormData) {
  3918. UploadFormDataItems items = {
  3919. {"text1", "text default", "", ""},
  3920. {"text2", "aωb", "", ""},
  3921. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3922. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3923. {"file3", "", "", "application/octet-stream"},
  3924. {"file4", "", "", " application/json tmp-string "}};
  3925. auto res = cli_.Post("/multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3930. UploadFormDataItems items = {
  3931. {"text", "default text", "", ""},
  3932. {"multi_text1", "aaaaa", "", ""},
  3933. {"multi_text1", "bbbbb", "", ""},
  3934. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3935. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3936. "application/json"},
  3937. };
  3938. auto res = cli_.Post("/multipart/multi_file_values", items);
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::OK_200, res->status);
  3941. }
  3942. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3943. auto res = cli_.Get("/hi");
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3947. EXPECT_EQ("Hello World!", res->body);
  3948. }
  3949. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3950. Request req;
  3951. req.method = "POST";
  3952. req.path = "/chunked";
  3953. std::string host_and_port;
  3954. host_and_port += HOST;
  3955. host_and_port += ":";
  3956. host_and_port += std::to_string(PORT);
  3957. req.headers.emplace("Host", host_and_port.c_str());
  3958. req.headers.emplace("Accept", "*/*");
  3959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3960. req.headers.emplace("Content-Type", "text/plain");
  3961. req.headers.emplace("Content-Length", "0");
  3962. req.headers.emplace(
  3963. "Transfer-Encoding",
  3964. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3965. // Client does not chunk, so make a chunked body manually.
  3966. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3967. auto res = std::make_shared<Response>();
  3968. auto error = Error::Success;
  3969. auto ret = cli_.send(req, *res, error);
  3970. ASSERT_TRUE(ret);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, GetStreamed2) {
  3974. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(true, res->has_header("Content-Range"));
  3979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3980. EXPECT_EQ(std::string("ab"), res->body);
  3981. }
  3982. TEST_F(ServerTest, GetStreamed) {
  3983. auto res = cli_.Get("/streamed");
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::OK_200, res->status);
  3986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3987. EXPECT_EQ(std::string("aaabbb"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedWithRange1) {
  3990. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3994. EXPECT_EQ(true, res->has_header("Content-Range"));
  3995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3996. EXPECT_EQ(std::string("def"), res->body);
  3997. }
  3998. TEST_F(ServerTest, GetStreamedWithRange2) {
  3999. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("bcdefg"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4008. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4011. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(true, res->has_header("Content-Range"));
  4013. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4014. EXPECT_EQ(std::string("efg"), res->body);
  4015. }
  4016. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4017. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4020. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4021. EXPECT_EQ(false, res->has_header("Content-Range"));
  4022. EXPECT_EQ(0U, res->body.size());
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4025. auto res = cli_.Get("/streamed-with-range",
  4026. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4027. "92233720368547758079223372036854775807"}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4035. auto res = cli_.Get(
  4036. "/with-range",
  4037. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4038. {"Accept-Encoding", ""}});
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4042. EXPECT_EQ(true, res->has_header("Content-Range"));
  4043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4044. EXPECT_EQ(std::string("abcdefg"), res->body);
  4045. }
  4046. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4047. auto res = cli_.Get("/with-range", {
  4048. {"Range", "bytes=0-"},
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("abcdefg"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4059. auto res =
  4060. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4063. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4064. EXPECT_EQ(false, res->has_header("Content-Range"));
  4065. EXPECT_EQ(267U, res->body.size());
  4066. // Check that both range contents are present
  4067. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4068. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4069. // Check that Content-Range headers are present for both ranges
  4070. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4071. std::string::npos);
  4072. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4073. std::string::npos);
  4074. }
  4075. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4076. Ranges ranges;
  4077. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4078. ranges.emplace_back(0, -1);
  4079. }
  4080. auto res =
  4081. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4084. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(0U, res->body.size());
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(5U, res->body.size());
  4094. // Check that overlapping ranges are coalesced into a single range
  4095. EXPECT_EQ("bcdef", res->body);
  4096. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4097. // Should be single range, not multipart
  4098. EXPECT_TRUE(res->has_header("Content-Range"));
  4099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. }
  4101. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4102. auto res =
  4103. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4106. EXPECT_EQ(268U, res->body.size());
  4107. // Check that both range contents are present
  4108. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4109. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4110. // Check that Content-Range headers are present for both ranges
  4111. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4112. std::string::npos);
  4113. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4114. std::string::npos);
  4115. }
  4116. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4117. auto res =
  4118. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ(269U, res->body.size());
  4122. // Check that both duplicate range contents are present
  4123. size_t first_abc = res->body.find("abc\r\n");
  4124. EXPECT_TRUE(first_abc != std::string::npos);
  4125. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4126. EXPECT_TRUE(second_abc != std::string::npos);
  4127. // Check that Content-Range headers are present for both ranges
  4128. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4129. EXPECT_TRUE(first_range != std::string::npos);
  4130. size_t second_range =
  4131. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4132. EXPECT_TRUE(second_range != std::string::npos);
  4133. }
  4134. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4135. auto res = cli_.Get("/streamed-with-range?error",
  4136. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(0U, res->body.size());
  4142. }
  4143. TEST_F(ServerTest, GetStreamedEndless) {
  4144. uint64_t offset = 0;
  4145. auto res = cli_.Get("/streamed-cancel",
  4146. [&](const char * /*data*/, uint64_t data_length) {
  4147. if (offset < 100) {
  4148. offset += data_length;
  4149. return true;
  4150. }
  4151. return false;
  4152. });
  4153. ASSERT_TRUE(!res);
  4154. EXPECT_EQ(Error::Canceled, res.error());
  4155. }
  4156. TEST_F(ServerTest, ClientStop) {
  4157. std::atomic_size_t count{4};
  4158. std::vector<std::thread> threads;
  4159. for (auto i = count.load(); i != 0; --i) {
  4160. threads.emplace_back([&]() {
  4161. auto res = cli_.Get("/streamed-cancel",
  4162. [&](const char *, uint64_t) { return true; });
  4163. --count;
  4164. ASSERT_TRUE(!res);
  4165. EXPECT_TRUE(res.error() == Error::Canceled ||
  4166. res.error() == Error::Read || res.error() == Error::Write);
  4167. });
  4168. }
  4169. std::this_thread::sleep_for(std::chrono::seconds(2));
  4170. while (count != 0) {
  4171. cli_.stop();
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4173. }
  4174. for (auto &t : threads) {
  4175. t.join();
  4176. }
  4177. }
  4178. TEST_F(ServerTest, GetWithRange1) {
  4179. auto res = cli_.Get("/with-range", {
  4180. make_range_header({{3, 5}}),
  4181. {"Accept-Encoding", ""},
  4182. });
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4185. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(true, res->has_header("Content-Range"));
  4187. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4188. EXPECT_EQ(std::string("def"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetWithRange2) {
  4191. auto res = cli_.Get("/with-range", {
  4192. make_range_header({{1, -1}}),
  4193. {"Accept-Encoding", ""},
  4194. });
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4197. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4198. EXPECT_EQ(true, res->has_header("Content-Range"));
  4199. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4200. EXPECT_EQ(std::string("bcdefg"), res->body);
  4201. }
  4202. TEST_F(ServerTest, GetWithRange3) {
  4203. auto res = cli_.Get("/with-range", {
  4204. make_range_header({{0, 0}}),
  4205. {"Accept-Encoding", ""},
  4206. });
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("a"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetWithRange4) {
  4215. auto res = cli_.Get("/with-range", {
  4216. make_range_header({{-1, 2}}),
  4217. {"Accept-Encoding", ""},
  4218. });
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(true, res->has_header("Content-Range"));
  4223. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4224. EXPECT_EQ(std::string("fg"), res->body);
  4225. }
  4226. TEST_F(ServerTest, GetWithRange5) {
  4227. auto res = cli_.Get("/with-range", {
  4228. make_range_header({{0, 5}}),
  4229. {"Accept-Encoding", ""},
  4230. });
  4231. ASSERT_TRUE(res);
  4232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4233. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4236. EXPECT_EQ(std::string("abcdef"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4239. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4242. }
  4243. TEST_F(ServerTest, GetWithRangeMultipart) {
  4244. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4247. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4248. EXPECT_EQ(false, res->has_header("Content-Range"));
  4249. EXPECT_EQ(267U, res->body.size());
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4252. auto res =
  4253. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4256. }
  4257. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4258. auto res = cli_.Get("/with-range-customized-response",
  4259. {{make_range_header({{1, 2}})}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4262. EXPECT_EQ(true, res->has_header("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(JSON_DATA, res->body);
  4265. }
  4266. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4267. auto res = cli_.Get("/with-range-customized-response",
  4268. {{make_range_header({{1, 2}, {4, 5}})}});
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4271. EXPECT_EQ(true, res->has_header("Content-Length"));
  4272. EXPECT_EQ(false, res->has_header("Content-Range"));
  4273. EXPECT_EQ(JSON_DATA, res->body);
  4274. }
  4275. TEST_F(ServerTest, Issue1772) {
  4276. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4279. }
  4280. TEST_F(ServerTest, Issue609) {
  4281. auto res = cli_.Delete("/issue609");
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ(std::string("ok"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetStreamedChunked) {
  4287. auto res = cli_.Get("/streamed-chunked");
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. EXPECT_EQ(std::string("123456789"), res->body);
  4291. }
  4292. TEST_F(ServerTest, GetStreamedChunked2) {
  4293. auto res = cli_.Get("/streamed-chunked2");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ(std::string("123456789"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4299. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ(std::string("123456789"), res->body);
  4303. EXPECT_TRUE(res->has_header("Trailer"));
  4304. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4305. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4306. // Trailers are now stored separately from headers (security fix)
  4307. EXPECT_EQ(2U, res->trailers.size());
  4308. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4309. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4310. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4311. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4312. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4313. // Verify trailers are NOT in headers (security verification)
  4314. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4315. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4316. }
  4317. TEST_F(ServerTest, LargeChunkedPost) {
  4318. Request req;
  4319. req.method = "POST";
  4320. req.path = "/large-chunked";
  4321. std::string host_and_port;
  4322. host_and_port += HOST;
  4323. host_and_port += ":";
  4324. host_and_port += std::to_string(PORT);
  4325. req.headers.emplace("Host", host_and_port.c_str());
  4326. req.headers.emplace("Accept", "*/*");
  4327. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4328. req.headers.emplace("Content-Type", "text/plain");
  4329. req.headers.emplace("Content-Length", "0");
  4330. req.headers.emplace("Transfer-Encoding", "chunked");
  4331. std::string long_string(30 * 1024u, 'a');
  4332. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4333. // Attempt to make a large enough post to exceed OS buffers, to test that
  4334. // the server handles short reads if the full chunk data isn't available.
  4335. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4336. auto res = std::make_shared<Response>();
  4337. auto error = Error::Success;
  4338. auto ret = cli_.send(req, *res, error);
  4339. ASSERT_TRUE(ret);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. }
  4342. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4343. auto res = cli_.Get("/remote_addr");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4347. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4348. }
  4349. TEST_F(ServerTest, GetMethodLocalAddr) {
  4350. auto res = cli_.Get("/local_addr");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4354. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4355. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4356. }
  4357. TEST_F(ServerTest, HTTPResponseSplitting) {
  4358. auto res = cli_.Get("/http_response_splitting");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. }
  4362. TEST_F(ServerTest, SlowRequest) {
  4363. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4364. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4366. }
  4367. #if 0
  4368. TEST_F(ServerTest, SlowPost) {
  4369. char buffer[64 * 1024];
  4370. memset(buffer, 0x42, sizeof(buffer));
  4371. auto res = cli_.Post(
  4372. "/slowpost", 64 * 1024 * 1024,
  4373. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4374. auto ret = sink.write(buffer, sizeof(buffer));
  4375. EXPECT_TRUE(ret);
  4376. return true;
  4377. },
  4378. "text/plain");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. TEST_F(ServerTest, SlowPostFail) {
  4383. char buffer[64 * 1024];
  4384. memset(buffer, 0x42, sizeof(buffer));
  4385. cli_.set_write_timeout(std::chrono::seconds(0));
  4386. auto res = cli_.Post(
  4387. "/slowpost", 64 * 1024 * 1024,
  4388. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4389. sink.write(buffer, sizeof(buffer));
  4390. return true;
  4391. },
  4392. "text/plain");
  4393. ASSERT_TRUE(!res);
  4394. EXPECT_EQ(Error::Write, res.error());
  4395. }
  4396. #endif
  4397. TEST_F(ServerTest, Put) {
  4398. auto res = cli_.Put("/put", "PUT", "text/plain");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("PUT", res->body);
  4402. }
  4403. TEST_F(ServerTest, PutWithContentProvider) {
  4404. auto res = cli_.Put(
  4405. "/put", 3,
  4406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4407. sink.os << "PUT";
  4408. return true;
  4409. },
  4410. "text/plain");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("PUT", res->body);
  4414. }
  4415. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4416. auto res = cli_.Post(
  4417. "/post", 42,
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4419. return false;
  4420. },
  4421. "text/plain");
  4422. ASSERT_TRUE(!res);
  4423. EXPECT_EQ(Error::Canceled, res.error());
  4424. }
  4425. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4426. auto res = cli_.Put(
  4427. "/put",
  4428. [](size_t /*offset*/, DataSink &sink) {
  4429. sink.os << "PUT";
  4430. sink.done();
  4431. return true;
  4432. },
  4433. "text/plain");
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ("PUT", res->body);
  4437. }
  4438. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4439. auto res = cli_.Post(
  4440. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4441. "text/plain");
  4442. ASSERT_TRUE(!res);
  4443. EXPECT_EQ(Error::Canceled, res.error());
  4444. }
  4445. TEST_F(ServerTest, PostLoopBack) {
  4446. std::string body;
  4447. auto res = cli_.Post(
  4448. "/post-loopback", 9,
  4449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4450. EXPECT_EQ(9u, length);
  4451. sink.write("123", 3);
  4452. sink.write("456", 3);
  4453. sink.write("789", 3);
  4454. return true;
  4455. },
  4456. "text/plain",
  4457. [&body](const char *data, size_t data_length) {
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::OK_200, res->status);
  4463. EXPECT_EQ("123456789", body);
  4464. }
  4465. TEST_F(ServerTest, PutLoopBack) {
  4466. std::string body;
  4467. auto res = cli_.Put(
  4468. "/put-loopback", 9,
  4469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4470. EXPECT_EQ(9u, length);
  4471. sink.write("123", 3);
  4472. sink.write("456", 3);
  4473. sink.write("789", 3);
  4474. return true;
  4475. },
  4476. "text/plain",
  4477. [&body](const char *data, size_t data_length) {
  4478. body.append(data, data_length);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("123456789", body);
  4484. }
  4485. TEST_F(ServerTest, PatchLoopBack) {
  4486. std::string body;
  4487. auto res = cli_.Patch(
  4488. "/patch-loopback", 9,
  4489. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4490. EXPECT_EQ(9u, length);
  4491. sink.write("123", 3);
  4492. sink.write("456", 3);
  4493. sink.write("789", 3);
  4494. return true;
  4495. },
  4496. "text/plain",
  4497. [&body](const char *data, size_t data_length) {
  4498. body.append(data, data_length);
  4499. return true;
  4500. });
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ("123456789", body);
  4504. }
  4505. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4506. std::string body;
  4507. auto res = cli_.Post(
  4508. "/post-loopback",
  4509. [](size_t /*offset*/, DataSink &sink) {
  4510. sink.write("123", 3);
  4511. sink.write("456", 3);
  4512. sink.write("789", 3);
  4513. sink.done();
  4514. return true;
  4515. },
  4516. "text/plain",
  4517. [&body](const char *data, size_t data_length) {
  4518. body.append(data, data_length);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("123456789", body);
  4524. }
  4525. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4526. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4527. cli_.set_compress(true);
  4528. auto res = cli_.Put(
  4529. "/put", 3,
  4530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4531. sink.os << "PUT";
  4532. return true;
  4533. },
  4534. "text/plain");
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("PUT", res->body);
  4538. }
  4539. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4540. cli_.set_compress(true);
  4541. auto res = cli_.Post(
  4542. "/post", 42,
  4543. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4544. return false;
  4545. },
  4546. "text/plain");
  4547. ASSERT_TRUE(!res);
  4548. EXPECT_EQ(Error::Canceled, res.error());
  4549. }
  4550. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4551. cli_.set_compress(true);
  4552. auto res = cli_.Put(
  4553. "/put",
  4554. [](size_t /*offset*/, DataSink &sink) {
  4555. sink.os << "PUT";
  4556. sink.done();
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4568. "text/plain");
  4569. ASSERT_TRUE(!res);
  4570. EXPECT_EQ(Error::Canceled, res.error());
  4571. }
  4572. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ(LARGE_DATA, res->body);
  4578. }
  4579. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4581. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4582. Client cli(s.c_str());
  4583. cli.enable_server_certificate_verification(false);
  4584. #else
  4585. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4586. Client cli(s.c_str());
  4587. #endif
  4588. cli.set_compress(true);
  4589. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ(LARGE_DATA, res->body);
  4593. // The compressed size should be less than a 10th of the original. May vary
  4594. // depending on the zlib library.
  4595. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4596. static_cast<uint64_t>(10 * 1024 * 1024));
  4597. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4598. }
  4599. TEST_F(ServerTest, PutContentWithDeflate) {
  4600. cli_.set_compress(false);
  4601. Headers headers;
  4602. headers.emplace("Content-Encoding", "deflate");
  4603. // PUT in deflate format:
  4604. auto res = cli_.Put("/put", headers,
  4605. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("PUT", res->body);
  4609. }
  4610. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4611. Headers headers;
  4612. headers.emplace("Accept-Encoding", "gzip, deflate");
  4613. auto res = cli_.Get("/streamed-chunked", headers);
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ(std::string("123456789"), res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked2", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4627. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. }
  4631. TEST(GzipDecompressor, ChunkedDecompression) {
  4632. std::string data;
  4633. for (size_t i = 0; i < 32 * 1024; ++i) {
  4634. data.push_back(static_cast<char>('a' + i % 26));
  4635. }
  4636. std::string compressed_data;
  4637. {
  4638. httplib::detail::gzip_compressor compressor;
  4639. bool result = compressor.compress(
  4640. data.data(), data.size(),
  4641. /*last=*/true,
  4642. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4643. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4644. compressed_data_size);
  4645. return true;
  4646. });
  4647. ASSERT_TRUE(result);
  4648. }
  4649. std::string decompressed_data;
  4650. {
  4651. httplib::detail::gzip_decompressor decompressor;
  4652. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4653. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4654. size_t chunk_size = 130;
  4655. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4656. chunk_begin += chunk_size) {
  4657. size_t current_chunk_size =
  4658. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4659. bool result = decompressor.decompress(
  4660. compressed_data.data() + chunk_begin, current_chunk_size,
  4661. [&](const char *decompressed_data_chunk,
  4662. size_t decompressed_data_chunk_size) {
  4663. decompressed_data.insert(decompressed_data.size(),
  4664. decompressed_data_chunk,
  4665. decompressed_data_chunk_size);
  4666. return true;
  4667. });
  4668. ASSERT_TRUE(result);
  4669. }
  4670. }
  4671. ASSERT_EQ(data, decompressed_data);
  4672. }
  4673. TEST(GzipDecompressor, DeflateDecompression) {
  4674. std::string original_text = "Raw deflate without gzip";
  4675. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4676. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4677. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4678. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4679. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4680. std::string decompressed_data;
  4681. {
  4682. httplib::detail::gzip_decompressor decompressor;
  4683. bool result = decompressor.decompress(
  4684. compressed_data.data(), compressed_data.size(),
  4685. [&](const char *decompressed_data_chunk,
  4686. size_t decompressed_data_chunk_size) {
  4687. decompressed_data.insert(decompressed_data.size(),
  4688. decompressed_data_chunk,
  4689. decompressed_data_chunk_size);
  4690. return true;
  4691. });
  4692. ASSERT_TRUE(result);
  4693. }
  4694. ASSERT_EQ(original_text, decompressed_data);
  4695. }
  4696. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4697. std::string original_text = "Raw deflate without gzip";
  4698. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4699. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4700. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4701. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4702. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4703. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4704. std::string decompressed_data;
  4705. {
  4706. httplib::detail::gzip_decompressor decompressor;
  4707. bool result = decompressor.decompress(
  4708. compressed_data.data(), compressed_data.size(),
  4709. [&](const char *decompressed_data_chunk,
  4710. size_t decompressed_data_chunk_size) {
  4711. decompressed_data.insert(decompressed_data.size(),
  4712. decompressed_data_chunk,
  4713. decompressed_data_chunk_size);
  4714. return true;
  4715. });
  4716. ASSERT_TRUE(result);
  4717. }
  4718. ASSERT_EQ(original_text, decompressed_data);
  4719. }
  4720. #ifdef _WIN32
  4721. TEST(GzipDecompressor, LargeRandomData) {
  4722. // prepare large random data that is difficult to be compressed and is
  4723. // expected to have large size even when compressed
  4724. std::random_device seed_gen;
  4725. std::mt19937 random(seed_gen());
  4726. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4727. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4728. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4729. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4730. // compress data over 4GiB
  4731. std::string compressed_data;
  4732. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4733. httplib::detail::gzip_compressor compressor;
  4734. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4735. data.size() * sizeof(std::uint32_t), true,
  4736. [&](const char *data, size_t size) {
  4737. compressed_data.insert(
  4738. compressed_data.size(), data, size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. // FIXME: compressed data size is expected to be greater than 4GiB,
  4743. // but there is no guarantee
  4744. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4745. // decompress data over 4GiB
  4746. std::string decompressed_data;
  4747. decompressed_data.reserve(data_size);
  4748. httplib::detail::gzip_decompressor decompressor;
  4749. result = decompressor.decompress(
  4750. compressed_data.data(), compressed_data.size(),
  4751. [&](const char *data, size_t size) {
  4752. decompressed_data.insert(decompressed_data.size(), data, size);
  4753. return true;
  4754. });
  4755. ASSERT_TRUE(result);
  4756. // compare
  4757. ASSERT_EQ(data_size, decompressed_data.size());
  4758. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4759. 0);
  4760. }
  4761. #endif
  4762. #endif
  4763. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4764. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4765. Headers headers;
  4766. headers.emplace("Accept-Encoding", "br");
  4767. auto res = cli_.Get("/streamed-chunked", headers);
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ(std::string("123456789"), res->body);
  4771. }
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked2", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Patch) {
  4782. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PATCH", res->body);
  4786. }
  4787. TEST_F(ServerTest, Delete) {
  4788. auto res = cli_.Delete("/delete");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("DELETE", res->body);
  4792. }
  4793. TEST_F(ServerTest, DeleteContentReceiver) {
  4794. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("content", res->body);
  4798. }
  4799. TEST_F(ServerTest, Options) {
  4800. auto res = cli_.Options("*");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4804. EXPECT_TRUE(res->body.empty());
  4805. }
  4806. TEST_F(ServerTest, URL) {
  4807. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, ArrayParam) {
  4812. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, NoMultipleHeaders) {
  4817. Headers headers = {{"Content-Length", "5"}};
  4818. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4819. "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. }
  4823. TEST_F(ServerTest, PostContentReceiver) {
  4824. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4830. UploadFormDataItems items = {
  4831. {"text1", "text default", "", ""},
  4832. {"text2", "aωb", "", ""},
  4833. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4834. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4835. {"file3", "", "", "application/octet-stream"},
  4836. };
  4837. auto res = cli_.Post("/content_receiver", items);
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4842. UploadFormDataItems items = {
  4843. {"text1", "text default", "", ""},
  4844. {"text2", "aωb", "", ""},
  4845. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4846. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4847. {"file3", "", "", "application/octet-stream"},
  4848. };
  4849. auto boundary = std::string("+++++");
  4850. std::string body;
  4851. for (const auto &item : items) {
  4852. body += "--" + boundary + "\r\n";
  4853. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4854. if (!item.filename.empty()) {
  4855. body += "; filename=\"" + item.filename + "\"";
  4856. }
  4857. body += "\r\n";
  4858. if (!item.content_type.empty()) {
  4859. body += "Content-Type: " + item.content_type + "\r\n";
  4860. }
  4861. body += "\r\n";
  4862. body += item.content + "\r\n";
  4863. }
  4864. body += "--" + boundary + "--\r\n";
  4865. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4866. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, PostContentReceiverGzip) {
  4871. cli_.set_compress(true);
  4872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4873. ASSERT_TRUE(res);
  4874. ASSERT_EQ(StatusCode::OK_200, res->status);
  4875. ASSERT_EQ("content", res->body);
  4876. }
  4877. TEST_F(ServerTest, PutContentReceiver) {
  4878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4879. ASSERT_TRUE(res);
  4880. ASSERT_EQ(StatusCode::OK_200, res->status);
  4881. ASSERT_EQ("content", res->body);
  4882. }
  4883. TEST_F(ServerTest, PatchContentReceiver) {
  4884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4885. ASSERT_TRUE(res);
  4886. ASSERT_EQ(StatusCode::OK_200, res->status);
  4887. ASSERT_EQ("content", res->body);
  4888. }
  4889. template <typename ClientType>
  4890. void TestWithHeadersAndContentReceiver(
  4891. ClientType &cli,
  4892. std::function<Result(ClientType &, const std::string &, const Headers &,
  4893. const std::string &, const std::string &,
  4894. ContentReceiver, DownloadProgress)>
  4895. request_func) {
  4896. Headers headers;
  4897. headers.emplace("X-Custom-Header", "test-value");
  4898. std::string received_body;
  4899. auto res = request_func(
  4900. cli, "/content_receiver", headers, "content", "application/json",
  4901. [&](const char *data, size_t data_length) {
  4902. received_body.append(data, data_length);
  4903. return true;
  4904. },
  4905. nullptr);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("content", received_body);
  4909. }
  4910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4912. using ClientT = SSLClient;
  4913. #else
  4914. using ClientT = Client;
  4915. #endif
  4916. TestWithHeadersAndContentReceiver<ClientT>(
  4917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4918. const std::string &body, const std::string &content_type,
  4919. ContentReceiver receiver, DownloadProgress progress) {
  4920. return cli.Post(path, headers, body, content_type, receiver, progress);
  4921. });
  4922. }
  4923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4925. using ClientT = SSLClient;
  4926. #else
  4927. using ClientT = Client;
  4928. #endif
  4929. TestWithHeadersAndContentReceiver<ClientT>(
  4930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4931. const std::string &body, const std::string &content_type,
  4932. ContentReceiver receiver, DownloadProgress progress) {
  4933. return cli.Put(path, headers, body, content_type, receiver, progress);
  4934. });
  4935. }
  4936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4937. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4938. using ClientT = SSLClient;
  4939. #else
  4940. using ClientT = Client;
  4941. #endif
  4942. TestWithHeadersAndContentReceiver<ClientT>(
  4943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4944. const std::string &body, const std::string &content_type,
  4945. ContentReceiver receiver, DownloadProgress progress) {
  4946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4947. });
  4948. }
  4949. template <typename ClientType>
  4950. void TestWithHeadersAndContentReceiverWithProgress(
  4951. ClientType &cli,
  4952. std::function<Result(ClientType &, const std::string &, const Headers &,
  4953. const std::string &, const std::string &,
  4954. ContentReceiver, DownloadProgress)>
  4955. request_func) {
  4956. Headers headers;
  4957. headers.emplace("X-Test-Header", "progress-test");
  4958. std::string received_body;
  4959. auto progress_called = false;
  4960. auto res = request_func(
  4961. cli, "/content_receiver", headers, "content", "text/plain",
  4962. [&](const char *data, size_t data_length) {
  4963. received_body.append(data, data_length);
  4964. return true;
  4965. },
  4966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4967. progress_called = true;
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ("content", received_body);
  4973. EXPECT_TRUE(progress_called);
  4974. }
  4975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4977. using ClientT = SSLClient;
  4978. #else
  4979. using ClientT = Client;
  4980. #endif
  4981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4983. const std::string &body, const std::string &content_type,
  4984. ContentReceiver receiver, DownloadProgress progress) {
  4985. return cli.Post(path, headers, body, content_type, receiver, progress);
  4986. });
  4987. }
  4988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4990. using ClientT = SSLClient;
  4991. #else
  4992. using ClientT = Client;
  4993. #endif
  4994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4996. const std::string &body, const std::string &content_type,
  4997. ContentReceiver receiver, DownloadProgress progress) {
  4998. return cli.Put(path, headers, body, content_type, receiver, progress);
  4999. });
  5000. }
  5001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5003. using ClientT = SSLClient;
  5004. #else
  5005. using ClientT = Client;
  5006. #endif
  5007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5009. const std::string &body, const std::string &content_type,
  5010. ContentReceiver receiver, DownloadProgress progress) {
  5011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5012. });
  5013. }
  5014. template <typename ClientType>
  5015. void TestWithHeadersAndContentReceiverError(
  5016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5017. const Headers &, const std::string &,
  5018. const std::string &, ContentReceiver)>
  5019. request_func) {
  5020. Headers headers;
  5021. headers.emplace("X-Error-Test", "true");
  5022. std::string received_body;
  5023. auto receiver_failed = false;
  5024. auto res =
  5025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5026. [&](const char *data, size_t data_length) {
  5027. received_body.append(data, data_length);
  5028. receiver_failed = true;
  5029. return false;
  5030. });
  5031. ASSERT_FALSE(res);
  5032. EXPECT_TRUE(receiver_failed);
  5033. }
  5034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5036. using ClientT = SSLClient;
  5037. #else
  5038. using ClientT = Client;
  5039. #endif
  5040. TestWithHeadersAndContentReceiverError<ClientT>(
  5041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5042. const std::string &body, const std::string &content_type,
  5043. ContentReceiver receiver) {
  5044. return cli.Post(path, headers, body, content_type, receiver);
  5045. });
  5046. }
  5047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverError<ClientT>(
  5054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5055. const std::string &body, const std::string &content_type,
  5056. ContentReceiver receiver) {
  5057. return cli.Put(path, headers, body, content_type, receiver);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverError<ClientT>(
  5067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5068. const std::string &body, const std::string &content_type,
  5069. ContentReceiver receiver) {
  5070. return cli.Patch(path, headers, body, content_type, receiver);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PostQueryStringAndBody) {
  5074. auto res =
  5075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5076. ASSERT_TRUE(res);
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, HTTP2Magic) {
  5080. Request req;
  5081. req.method = "PRI";
  5082. req.path = "*";
  5083. req.body = "SM";
  5084. auto res = std::make_shared<Response>();
  5085. auto error = Error::Success;
  5086. auto ret = cli_.send(req, *res, error);
  5087. ASSERT_TRUE(ret);
  5088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5089. }
  5090. TEST_F(ServerTest, KeepAlive) {
  5091. auto res = cli_.Get("/hi");
  5092. ASSERT_TRUE(res);
  5093. EXPECT_EQ(StatusCode::OK_200, res->status);
  5094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5095. EXPECT_EQ("Hello World!", res->body);
  5096. res = cli_.Get("/hi");
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("Hello World!", res->body);
  5101. res = cli_.Get("/hi");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5105. EXPECT_EQ("Hello World!", res->body);
  5106. res = cli_.Get("/not-exist");
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5109. res = cli_.Post("/empty", "", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("empty", res->body);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. res = cli_.Post(
  5116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5117. "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. cli_.set_keep_alive(false);
  5123. res = cli_.Get("/last-request");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("close", res->get_header_value("Connection"));
  5127. }
  5128. TEST_F(ServerTest, TooManyRedirect) {
  5129. cli_.set_follow_location(true);
  5130. auto res = cli_.Get("/redirect/0");
  5131. ASSERT_TRUE(!res);
  5132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5133. }
  5134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5135. Request req;
  5136. req.method = "FOOBAR";
  5137. req.path = "/hi";
  5138. cli_.set_keep_alive(true);
  5139. auto res = cli_.send(req);
  5140. ASSERT_TRUE(res);
  5141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5142. EXPECT_EQ("close", res->get_header_value("Connection"));
  5143. EXPECT_FALSE(cli_.is_socket_open());
  5144. }
  5145. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5146. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5147. TEST_F(ServerTest, Gzip) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "gzip, deflate");
  5150. auto res = cli_.Get("/compress", headers);
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5156. "7890123456789012345678901234567890",
  5157. res->body);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. }
  5160. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5161. Headers headers;
  5162. headers.emplace("Accept-Encoding", "");
  5163. auto res = cli_.Get("/compress", headers);
  5164. ASSERT_TRUE(res);
  5165. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. res->body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. TEST_F(ServerTest, GzipWithContentReceiver) {
  5174. Headers headers;
  5175. headers.emplace("Accept-Encoding", "gzip, deflate");
  5176. std::string body;
  5177. auto res = cli_.Get("/compress", headers,
  5178. [&](const char *data, uint64_t data_length) {
  5179. EXPECT_EQ(100U, data_length);
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5186. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5188. "7890123456789012345678901234567890",
  5189. body);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. }
  5192. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5193. Headers headers;
  5194. headers.emplace("Accept-Encoding", "gzip, deflate");
  5195. cli_.set_decompress(false);
  5196. auto res = cli_.Get("/compress", headers);
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5200. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5201. EXPECT_EQ(33U, res->body.size());
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. std::string body;
  5208. auto res = cli_.Get("/compress", headers,
  5209. [&](const char *data, uint64_t data_length) {
  5210. EXPECT_EQ(100U, data_length);
  5211. body.append(data, data_length);
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5217. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5218. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5219. "7890123456789012345678901234567890",
  5220. body);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. }
  5223. TEST_F(ServerTest, NoGzip) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "gzip, deflate");
  5226. auto res = cli_.Get("/nocompress", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5229. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. res->body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. std::string body;
  5240. auto res = cli_.Get("/nocompress", headers,
  5241. [&](const char *data, uint64_t data_length) {
  5242. EXPECT_EQ(100U, data_length);
  5243. body.append(data, data_length);
  5244. return true;
  5245. });
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5248. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5250. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5251. "7890123456789012345678901234567890",
  5252. body);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. }
  5255. TEST_F(ServerTest, MultipartFormDataGzip) {
  5256. UploadFormDataItems items = {
  5257. {"key1", "test", "", ""},
  5258. {"key2", "--abcdefg123", "", ""},
  5259. };
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/compress-multipart", items);
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. }
  5265. #endif
  5266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5267. TEST_F(ServerTest, Brotli) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "br");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. #endif
  5281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5282. TEST_F(ServerTest, Zstd) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "zstd");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "");
  5298. auto res = cli_.Get("/compress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "zstd");
  5311. std::string body;
  5312. auto res = cli_.Get("/compress", headers,
  5313. [&](const char *data, uint64_t data_length) {
  5314. EXPECT_EQ(100U, data_length);
  5315. body.append(data, data_length);
  5316. return true;
  5317. });
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5323. "7890123456789012345678901234567890",
  5324. body);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "zstd");
  5330. cli_.set_decompress(false);
  5331. auto res = cli_.Get("/compress", headers);
  5332. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5333. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5334. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5335. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ(26U, res->body.size());
  5342. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5343. 0);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "");
  5348. std::string body;
  5349. auto res = cli_.Get("/compress", headers,
  5350. [&](const char *data, uint64_t data_length) {
  5351. EXPECT_EQ(100U, data_length);
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. ASSERT_TRUE(res);
  5356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoZstd) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "zstd");
  5367. auto res = cli_.Get("/nocompress", headers);
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5370. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5373. "7890123456789012345678901234567890",
  5374. res->body);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. }
  5377. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5378. Headers headers;
  5379. headers.emplace("Accept-Encoding", "zstd");
  5380. std::string body;
  5381. auto res = cli_.Get("/nocompress", headers,
  5382. [&](const char *data, uint64_t data_length) {
  5383. EXPECT_EQ(100U, data_length);
  5384. body.append(data, data_length);
  5385. return true;
  5386. });
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5390. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5391. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5392. "7890123456789012345678901234567890",
  5393. body);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. }
  5396. // TODO: How to enable zstd ??
  5397. TEST_F(ServerTest, MultipartFormDataZstd) {
  5398. UploadFormDataItems items = {
  5399. {"key1", "test", "", ""},
  5400. {"key2", "--abcdefg123", "", ""},
  5401. };
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "zstd");
  5404. cli_.set_compress(true);
  5405. auto res = cli_.Post("/compress-multipart", headers, items);
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Put(
  5414. "/put", headers, 3,
  5415. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5416. sink.os << "PUT";
  5417. return true;
  5418. },
  5419. "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. // Pre-compression logging tests
  5425. TEST_F(ServerTest, PreCompressionLogging) {
  5426. // Test data for compression (matches the actual /compress endpoint content)
  5427. const std::string test_content =
  5428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5429. "3456789012345678901234567890";
  5430. // Variables to capture logging data
  5431. std::string pre_compression_body;
  5432. std::string pre_compression_content_type;
  5433. std::string pre_compression_content_encoding;
  5434. std::string post_compression_body;
  5435. std::string post_compression_content_type;
  5436. std::string post_compression_content_encoding;
  5437. // Set up pre-compression logger
  5438. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5439. const Response &res) {
  5440. pre_compression_body = res.body;
  5441. pre_compression_content_type = res.get_header_value("Content-Type");
  5442. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5443. });
  5444. // Set up post-compression logger
  5445. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5446. post_compression_body = res.body;
  5447. post_compression_content_type = res.get_header_value("Content-Type");
  5448. post_compression_content_encoding =
  5449. res.get_header_value("Content-Encoding");
  5450. });
  5451. // Test with gzip compression
  5452. Headers headers;
  5453. headers.emplace("Accept-Encoding", "gzip");
  5454. auto res = cli_.Get("/compress", headers);
  5455. // Verify response was compressed
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5459. // Verify pre-compression logger captured uncompressed content
  5460. EXPECT_EQ(test_content, pre_compression_body);
  5461. EXPECT_EQ("text/plain", pre_compression_content_type);
  5462. EXPECT_TRUE(pre_compression_content_encoding
  5463. .empty()); // No encoding header before compression
  5464. // Verify post-compression logger captured compressed content
  5465. EXPECT_NE(test_content,
  5466. post_compression_body); // Should be different after compression
  5467. EXPECT_EQ("text/plain", post_compression_content_type);
  5468. EXPECT_EQ("gzip", post_compression_content_encoding);
  5469. // Verify compressed content is smaller
  5470. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5471. }
  5472. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5473. const std::string test_content =
  5474. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5475. "3456789012345678901234567890";
  5476. std::string pre_compression_body;
  5477. std::string post_compression_body;
  5478. svr_.set_pre_compression_logger(
  5479. [&](const Request & /*req*/, const Response &res) {
  5480. pre_compression_body = res.body;
  5481. });
  5482. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5483. post_compression_body = res.body;
  5484. });
  5485. Headers headers;
  5486. headers.emplace("Accept-Encoding", "br");
  5487. auto res = cli_.Get("/compress", headers);
  5488. ASSERT_TRUE(res);
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5491. // Verify pre-compression content is uncompressed
  5492. EXPECT_EQ(test_content, pre_compression_body);
  5493. // Verify post-compression content is compressed
  5494. EXPECT_NE(test_content, post_compression_body);
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. // Request without compression (use /nocompress endpoint)
  5511. Headers headers;
  5512. auto res = cli_.Get("/nocompress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5516. // Pre-compression logger should not be called when no compression is applied
  5517. EXPECT_TRUE(
  5518. pre_compression_body.empty()); // Pre-compression logger not called
  5519. EXPECT_EQ(
  5520. test_content,
  5521. post_compression_body); // Post-compression logger captures final content
  5522. }
  5523. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5524. const std::string test_content =
  5525. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5526. "3456789012345678901234567890";
  5527. std::string pre_compression_body;
  5528. bool pre_logger_called = false;
  5529. // Set only pre-compression logger
  5530. svr_.set_pre_compression_logger(
  5531. [&](const Request & /*req*/, const Response &res) {
  5532. pre_compression_body = res.body;
  5533. pre_logger_called = true;
  5534. });
  5535. Headers headers;
  5536. headers.emplace("Accept-Encoding", "gzip");
  5537. auto res = cli_.Get("/compress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5541. // Verify pre-compression logger was called
  5542. EXPECT_TRUE(pre_logger_called);
  5543. EXPECT_EQ(test_content, pre_compression_body);
  5544. }
  5545. TEST(ZstdDecompressor, ChunkedDecompression) {
  5546. std::string data;
  5547. for (size_t i = 0; i < 32 * 1024; ++i) {
  5548. data.push_back(static_cast<char>('a' + i % 26));
  5549. }
  5550. std::string compressed_data;
  5551. {
  5552. httplib::detail::zstd_compressor compressor;
  5553. bool result = compressor.compress(
  5554. data.data(), data.size(),
  5555. /*last=*/true,
  5556. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5557. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5558. compressed_data_size);
  5559. return true;
  5560. });
  5561. ASSERT_TRUE(result);
  5562. }
  5563. std::string decompressed_data;
  5564. {
  5565. httplib::detail::zstd_decompressor decompressor;
  5566. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5567. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5568. size_t chunk_size = 130;
  5569. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5570. chunk_begin += chunk_size) {
  5571. size_t current_chunk_size =
  5572. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5573. bool result = decompressor.decompress(
  5574. compressed_data.data() + chunk_begin, current_chunk_size,
  5575. [&](const char *decompressed_data_chunk,
  5576. size_t decompressed_data_chunk_size) {
  5577. decompressed_data.insert(decompressed_data.size(),
  5578. decompressed_data_chunk,
  5579. decompressed_data_chunk_size);
  5580. return true;
  5581. });
  5582. ASSERT_TRUE(result);
  5583. }
  5584. }
  5585. ASSERT_EQ(data, decompressed_data);
  5586. }
  5587. TEST(ZstdDecompressor, Decompress) {
  5588. std::string original_text = "Compressed with ZSTD";
  5589. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5590. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5591. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5592. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5593. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5594. std::string decompressed_data;
  5595. {
  5596. httplib::detail::zstd_decompressor decompressor;
  5597. bool result = decompressor.decompress(
  5598. compressed_data.data(), compressed_data.size(),
  5599. [&](const char *decompressed_data_chunk,
  5600. size_t decompressed_data_chunk_size) {
  5601. decompressed_data.insert(decompressed_data.size(),
  5602. decompressed_data_chunk,
  5603. decompressed_data_chunk_size);
  5604. return true;
  5605. });
  5606. ASSERT_TRUE(result);
  5607. }
  5608. ASSERT_EQ(original_text, decompressed_data);
  5609. }
  5610. #endif
  5611. // Sends a raw request to a server listening at HOST:PORT.
  5612. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5613. std::string *resp = nullptr) {
  5614. auto error = Error::Success;
  5615. auto client_sock = detail::create_client_socket(
  5616. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5617. /*connection_timeout_sec=*/5, 0,
  5618. /*read_timeout_sec=*/5, 0,
  5619. /*write_timeout_sec=*/5, 0, std::string(), error);
  5620. if (client_sock == INVALID_SOCKET) { return false; }
  5621. auto ret = detail::process_client_socket(
  5622. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5623. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5624. if (req.size() !=
  5625. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5626. return false;
  5627. }
  5628. char buf[512];
  5629. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5630. while (line_reader.getline()) {
  5631. if (resp) { *resp += line_reader.ptr(); }
  5632. }
  5633. return true;
  5634. });
  5635. detail::close_socket(client_sock);
  5636. return ret;
  5637. }
  5638. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5639. Server svr;
  5640. std::string header_value;
  5641. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5642. header_value = req.get_header_value("foo");
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. thread t = thread([&] { svr.listen(HOST, PORT); });
  5646. auto se = detail::scope_exit([&] {
  5647. svr.stop();
  5648. t.join();
  5649. ASSERT_FALSE(svr.is_running());
  5650. });
  5651. svr.wait_until_ready();
  5652. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5653. // like characters are not treated the same - use vertical tab and escape.
  5654. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5655. "foo: \t \v bar \x1B\t \r\n"
  5656. "Connection: close\r\n"
  5657. "\r\n";
  5658. std::string res;
  5659. ASSERT_TRUE(send_request(5, req, &res));
  5660. EXPECT_EQ(header_value, "");
  5661. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5662. }
  5663. // Sends a raw request and verifies that there isn't a crash or exception.
  5664. static void test_raw_request(const std::string &req,
  5665. std::string *out = nullptr) {
  5666. Server svr;
  5667. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5668. res.set_content("ok", "text/plain");
  5669. });
  5670. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5671. res.set_content("ok", "text/plain");
  5672. });
  5673. svr.Get("/header_field_value_check",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_content("ok", "text/plain");
  5676. });
  5677. // Server read timeout must be longer than the client read timeout for the
  5678. // bug to reproduce, probably to force the server to process a request
  5679. // without a trailing blank line.
  5680. const time_t client_read_timeout_sec = 1;
  5681. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5682. bool listen_thread_ok = false;
  5683. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5684. auto se = detail::scope_exit([&] {
  5685. svr.stop();
  5686. t.join();
  5687. ASSERT_FALSE(svr.is_running());
  5688. EXPECT_TRUE(listen_thread_ok);
  5689. });
  5690. svr.wait_until_ready();
  5691. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5692. }
  5693. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5694. // A certain header line causes an exception if the header property is parsed
  5695. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5696. test_raw_request(
  5697. "GET /hi HTTP/1.1\r\n"
  5698. " : "
  5699. " "
  5700. " ");
  5701. }
  5702. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5703. // A certain header line causes an exception if the header property *name* is
  5704. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5705. // greedy matcher and requires backtracking when there are a lot of ":"
  5706. // characters.
  5707. // This occurs with libc++ but not libstdc++.
  5708. test_raw_request(
  5709. "GET /hi HTTP/1.1\r\n"
  5710. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5711. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5712. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5713. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5714. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5715. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5716. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5717. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5718. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5719. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5720. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5722. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5723. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5724. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5725. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5726. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5727. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5728. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5729. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5730. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5731. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5732. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5733. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5734. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5735. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5736. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5737. "&&&%%%");
  5738. }
  5739. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5740. // Make sure this doesn't crash the server.
  5741. // In a previous version of the header line regex, the "\r" rendered the line
  5742. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5743. // a new position where the leading white space ended and the field value
  5744. // began.
  5745. // The crash occurs with libc++ but not libstdc++.
  5746. test_raw_request("GET /hi HTTP/1.1\r\n"
  5747. "a:" +
  5748. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5749. "\r\n"
  5750. "\r\n");
  5751. }
  5752. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5753. std::string out;
  5754. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5755. "Content-Type: text/plain\r\n"
  5756. "Transfer-Encoding: chunked\r\n"
  5757. "\r\n"
  5758. "nothex\r\n",
  5759. &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5763. std::string out;
  5764. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5765. "Content-Type: text/plain\r\n"
  5766. "Transfer-Encoding: chunked\r\n"
  5767. "\r\n"
  5768. "3\r\n"
  5769. "xyz\r\n"
  5770. "NaN\r\n",
  5771. &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5775. std::string out;
  5776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5777. "Content-Type: text/plain\r\n"
  5778. "Transfer-Encoding: chunked\r\n"
  5779. "\r\n"
  5780. // Length is too large for 64 bits.
  5781. "1ffffffffffffffff\r\n"
  5782. "xyz\r\n",
  5783. &out);
  5784. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5785. }
  5786. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5787. test_raw_request("GET /hi HTTP/1.1\r\n"
  5788. "Content-Type: text/plain\r\n\r");
  5789. }
  5790. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5791. std::string out;
  5792. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5793. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5794. }
  5795. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5796. Server svr;
  5797. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5798. EXPECT_TRUE(!req.remote_addr.empty());
  5799. });
  5800. thread t = thread([&] { svr.listen(HOST, PORT); });
  5801. auto se = detail::scope_exit([&] {
  5802. svr.stop();
  5803. t.join();
  5804. ASSERT_FALSE(svr.is_running());
  5805. });
  5806. svr.wait_until_ready();
  5807. // Send an invalid request line to trigger Bad Request
  5808. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5809. std::string out;
  5810. ASSERT_TRUE(send_request(5, bad_req, &out));
  5811. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5812. }
  5813. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5814. std::string out;
  5815. std::string request(
  5816. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5817. test_raw_request(request, &out);
  5818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5819. }
  5820. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5821. std::string out;
  5822. std::string request(
  5823. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5824. test_raw_request(request, &out);
  5825. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5826. }
  5827. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5828. std::string out;
  5829. std::string request(
  5830. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5831. test_raw_request(request, &out);
  5832. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5833. }
  5834. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5835. std::string out;
  5836. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5837. "Test: \r\n\r\n",
  5838. &out);
  5839. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5840. }
  5841. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5842. Server svr;
  5843. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5844. res.set_header("Cache-Control", "no-cache");
  5845. res.set_chunked_content_provider(
  5846. "text/event-stream", [](size_t offset, DataSink &sink) {
  5847. std::string s = "data:";
  5848. s += std::to_string(offset);
  5849. s += "\n\n";
  5850. auto ret = sink.write(s.data(), s.size());
  5851. EXPECT_TRUE(ret);
  5852. std::this_thread::sleep_for(std::chrono::seconds(1));
  5853. return true;
  5854. });
  5855. });
  5856. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5857. svr.wait_until_ready();
  5858. Client client(HOST, PORT);
  5859. const Headers headers = {{"Accept", "text/event-stream"}};
  5860. auto get_thread = std::thread([&client, &headers]() {
  5861. auto res = client.Get(
  5862. "/events", headers,
  5863. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5864. });
  5865. auto se = detail::scope_exit([&] {
  5866. svr.stop();
  5867. get_thread.join();
  5868. listen_thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. // Give GET time to get a few messages.
  5872. std::this_thread::sleep_for(std::chrono::seconds(2));
  5873. }
  5874. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5875. httplib::Server svr;
  5876. svr.Post("/hi",
  5877. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5878. res.status = StatusCode::OK_200;
  5879. });
  5880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5881. svr.wait_until_ready();
  5882. Client cli(HOST, PORT);
  5883. auto res = cli.Post("/hi", "data", "text/plain");
  5884. ASSERT_TRUE(res);
  5885. EXPECT_EQ(StatusCode::OK_200, res->status);
  5886. svr.stop();
  5887. thread.join();
  5888. ASSERT_FALSE(svr.is_running());
  5889. res = cli.Post("/hi", "data", "text/plain");
  5890. ASSERT_FALSE(res);
  5891. }
  5892. TEST(ServerStopTest, ListenFailure) {
  5893. Server svr;
  5894. auto t = thread([&]() {
  5895. auto ret = svr.listen("????", PORT);
  5896. EXPECT_FALSE(ret);
  5897. });
  5898. svr.wait_until_ready();
  5899. svr.stop();
  5900. t.join();
  5901. }
  5902. TEST(ServerStopTest, Decommision) {
  5903. Server svr;
  5904. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5905. for (int i = 0; i < 4; i++) {
  5906. auto is_even = !(i % 2);
  5907. std::thread t{[&] {
  5908. try {
  5909. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5910. if (is_even) {
  5911. throw std::runtime_error("Some thing that happens to go wrong.");
  5912. }
  5913. svr.listen(HOST, PORT);
  5914. } catch (...) { svr.decommission(); }
  5915. }};
  5916. svr.wait_until_ready();
  5917. // Server is up
  5918. {
  5919. Client cli(HOST, PORT);
  5920. auto res = cli.Get("/hi");
  5921. if (is_even) {
  5922. EXPECT_FALSE(res);
  5923. } else {
  5924. EXPECT_TRUE(res);
  5925. EXPECT_EQ("hi...", res->body);
  5926. }
  5927. }
  5928. svr.stop();
  5929. t.join();
  5930. // Server is down...
  5931. {
  5932. Client cli(HOST, PORT);
  5933. auto res = cli.Get("/hi");
  5934. EXPECT_FALSE(res);
  5935. }
  5936. }
  5937. }
  5938. // Helper function for string body upload progress tests
  5939. template <typename SetupHandler, typename ClientCall>
  5940. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5941. ClientCall &&client_call,
  5942. const string &body) {
  5943. Server svr;
  5944. setup_handler(svr);
  5945. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5946. auto se = detail::scope_exit([&] {
  5947. svr.stop();
  5948. t.join();
  5949. });
  5950. svr.wait_until_ready();
  5951. Client cli(HOST, PORT);
  5952. vector<uint64_t> progress_values;
  5953. bool progress_called = false;
  5954. auto res =
  5955. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5956. progress_values.push_back(current);
  5957. progress_called = true;
  5958. return true;
  5959. });
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ(200, res->status);
  5962. EXPECT_TRUE(progress_called);
  5963. }
  5964. TEST(UploadProgressTest, PostStringBodyBasic) {
  5965. TestStringBodyUploadProgress(
  5966. [](Server &svr) {
  5967. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5968. res.set_content("received", "text/plain");
  5969. });
  5970. },
  5971. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5972. return cli.Post("/test", body, "text/plain", progress_callback);
  5973. },
  5974. "test data for upload progress");
  5975. }
  5976. TEST(UploadProgressTest, PutStringBodyBasic) {
  5977. TestStringBodyUploadProgress(
  5978. [](Server &svr) {
  5979. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5980. res.set_content("put received", "text/plain");
  5981. });
  5982. },
  5983. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5984. return cli.Put("/test", body, "text/plain", progress_callback);
  5985. },
  5986. "put test data for upload progress");
  5987. }
  5988. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5989. TestStringBodyUploadProgress(
  5990. [](Server &svr) {
  5991. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5992. res.set_content("patch received", "text/plain");
  5993. });
  5994. },
  5995. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5996. return cli.Patch("/test", body, "text/plain", progress_callback);
  5997. },
  5998. "patch test data for upload progress");
  5999. }
  6000. // Helper function for content provider upload progress tests
  6001. template <typename SetupHandler, typename ClientCall>
  6002. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6003. ClientCall &&client_call) {
  6004. Server svr;
  6005. setup_handler(svr);
  6006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. vector<uint64_t> progress_values;
  6014. auto res =
  6015. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6016. progress_values.push_back(current);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(200, res->status);
  6021. EXPECT_FALSE(progress_values.empty());
  6022. }
  6023. TEST(UploadProgressTest, PostContentProviderProgress) {
  6024. TestContentProviderUploadProgress(
  6025. [](Server &svr) {
  6026. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6027. res.set_content("provider received", "text/plain");
  6028. });
  6029. },
  6030. [](Client &cli, UploadProgress progress_callback) {
  6031. return cli.Post(
  6032. "/test", 10,
  6033. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6034. sink.os << "test data";
  6035. return true;
  6036. },
  6037. "text/plain", progress_callback);
  6038. });
  6039. }
  6040. // Helper function for multipart upload progress tests
  6041. template <typename SetupHandler, typename ClientCall>
  6042. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6043. ClientCall &&client_call,
  6044. const string &endpoint) {
  6045. Server svr;
  6046. setup_handler(svr);
  6047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. t.join();
  6051. });
  6052. svr.wait_until_ready();
  6053. Client cli(HOST, PORT);
  6054. vector<uint64_t> progress_values;
  6055. UploadFormDataItems items = {
  6056. {"field1", "value1", "", ""},
  6057. {"field2", "longer value for progress tracking test", "", ""},
  6058. {"file1", "file content data for upload progress", "test.txt",
  6059. "text/plain"}};
  6060. auto res = client_call(cli, endpoint, items,
  6061. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6062. progress_values.push_back(current);
  6063. return true;
  6064. });
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(200, res->status);
  6067. EXPECT_FALSE(progress_values.empty());
  6068. }
  6069. TEST(UploadProgressTest, PostMultipartProgress) {
  6070. TestMultipartUploadProgress(
  6071. [](Server &svr) {
  6072. svr.Post("/multipart", [](const Request &req, Response &res) {
  6073. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6074. res.set_content("multipart received", "text/plain");
  6075. });
  6076. },
  6077. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6078. UploadProgress progress_callback) {
  6079. return cli.Post(endpoint, items, progress_callback);
  6080. },
  6081. "/multipart");
  6082. }
  6083. // Helper function for basic download progress tests
  6084. template <typename SetupHandler, typename ClientCall>
  6085. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6086. ClientCall &&client_call, const string &endpoint,
  6087. size_t expected_content_size) {
  6088. Server svr;
  6089. setup_handler(svr);
  6090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6091. auto se = detail::scope_exit([&] {
  6092. svr.stop();
  6093. t.join();
  6094. });
  6095. svr.wait_until_ready();
  6096. Client cli(HOST, PORT);
  6097. vector<uint64_t> progress_values;
  6098. auto res = client_call(cli, endpoint,
  6099. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6100. progress_values.push_back(current);
  6101. return true;
  6102. });
  6103. ASSERT_TRUE(res);
  6104. EXPECT_EQ(200, res->status);
  6105. EXPECT_FALSE(progress_values.empty());
  6106. EXPECT_EQ(expected_content_size, res->body.size());
  6107. }
  6108. TEST(DownloadProgressTest, GetBasic) {
  6109. TestBasicDownloadProgress(
  6110. [](Server &svr) {
  6111. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6112. string content(1000, 'D');
  6113. res.set_content(content, "text/plain");
  6114. });
  6115. },
  6116. [](Client &cli, const string &endpoint,
  6117. DownloadProgress progress_callback) {
  6118. return cli.Get(endpoint, progress_callback);
  6119. },
  6120. "/download", 1000u);
  6121. }
  6122. // Helper function for content receiver download progress tests
  6123. template <typename SetupHandler, typename ClientCall>
  6124. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6125. ClientCall &&client_call,
  6126. const string &endpoint,
  6127. size_t expected_content_size) {
  6128. Server svr;
  6129. setup_handler(svr);
  6130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6131. auto se = detail::scope_exit([&] {
  6132. svr.stop();
  6133. t.join();
  6134. });
  6135. svr.wait_until_ready();
  6136. Client cli(HOST, PORT);
  6137. vector<uint64_t> progress_values;
  6138. string received_body;
  6139. auto res = client_call(
  6140. cli, endpoint,
  6141. [&](const char *data, size_t data_length) -> bool {
  6142. received_body.append(data, data_length);
  6143. return true;
  6144. },
  6145. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(res);
  6150. EXPECT_EQ(200, res->status);
  6151. EXPECT_FALSE(progress_values.empty());
  6152. EXPECT_EQ(expected_content_size, received_body.size());
  6153. EXPECT_TRUE(res->body.empty());
  6154. }
  6155. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6156. TestContentReceiverDownloadProgress(
  6157. [](Server &svr) {
  6158. svr.Get("/download-receiver",
  6159. [](const Request & /*req*/, Response &res) {
  6160. string content(2000, 'R');
  6161. res.set_content(content, "text/plain");
  6162. });
  6163. },
  6164. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6165. DownloadProgress progress_callback) {
  6166. return cli.Get(endpoint, content_receiver, progress_callback);
  6167. },
  6168. "/download-receiver", 2000u);
  6169. }
  6170. TEST(StreamingTest, NoContentLengthStreaming) {
  6171. Server svr;
  6172. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6173. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6174. if (offset < 6) {
  6175. sink.os << (offset < 3 ? "a" : "b");
  6176. } else {
  6177. sink.done();
  6178. }
  6179. return true;
  6180. });
  6181. });
  6182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6183. auto listen_se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. listen_thread.join();
  6186. ASSERT_FALSE(svr.is_running());
  6187. });
  6188. svr.wait_until_ready();
  6189. Client client(HOST, PORT);
  6190. auto get_thread = std::thread([&client]() {
  6191. std::string s;
  6192. auto res =
  6193. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6194. s += std::string(data, len);
  6195. return true;
  6196. });
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("aaabbb", s);
  6200. });
  6201. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6202. // Give GET time to get a few messages.
  6203. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6204. }
  6205. TEST(MountTest, Unmount) {
  6206. Server svr;
  6207. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6208. auto se = detail::scope_exit([&] {
  6209. svr.stop();
  6210. listen_thread.join();
  6211. ASSERT_FALSE(svr.is_running());
  6212. });
  6213. svr.wait_until_ready();
  6214. Client cli("localhost", PORT);
  6215. svr.set_mount_point("/mount2", "./www2");
  6216. auto res = cli.Get("/");
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6219. res = cli.Get("/mount2/dir/test.html");
  6220. ASSERT_TRUE(res);
  6221. EXPECT_EQ(StatusCode::OK_200, res->status);
  6222. svr.set_mount_point("/", "./www");
  6223. res = cli.Get("/dir/");
  6224. ASSERT_TRUE(res);
  6225. EXPECT_EQ(StatusCode::OK_200, res->status);
  6226. svr.remove_mount_point("/");
  6227. res = cli.Get("/dir/");
  6228. ASSERT_TRUE(res);
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. svr.remove_mount_point("/mount2");
  6231. res = cli.Get("/mount2/dir/test.html");
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6234. }
  6235. TEST(MountTest, Redicect) {
  6236. Server svr;
  6237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. listen_thread.join();
  6241. ASSERT_FALSE(svr.is_running());
  6242. });
  6243. svr.set_mount_point("/", "./www");
  6244. svr.wait_until_ready();
  6245. Client cli("localhost", PORT);
  6246. auto res = cli.Get("/dir/");
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. res = cli.Get("/dir");
  6250. ASSERT_TRUE(res);
  6251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6252. res = cli.Get("/file");
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. res = cli.Get("/file/");
  6256. ASSERT_TRUE(res);
  6257. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6258. cli.set_follow_location(true);
  6259. res = cli.Get("/dir");
  6260. ASSERT_TRUE(res);
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. }
  6263. TEST(MountTest, MultibytesPathName) {
  6264. Server svr;
  6265. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6266. auto se = detail::scope_exit([&] {
  6267. svr.stop();
  6268. listen_thread.join();
  6269. ASSERT_FALSE(svr.is_running());
  6270. });
  6271. svr.set_mount_point("/", "./www");
  6272. svr.wait_until_ready();
  6273. Client cli("localhost", PORT);
  6274. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6278. }
  6279. TEST(KeepAliveTest, ReadTimeout) {
  6280. Server svr;
  6281. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6282. std::this_thread::sleep_for(std::chrono::seconds(2));
  6283. res.set_content("a", "text/plain");
  6284. });
  6285. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6286. res.set_content("b", "text/plain");
  6287. });
  6288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6289. auto se = detail::scope_exit([&] {
  6290. svr.stop();
  6291. listen_thread.join();
  6292. ASSERT_FALSE(svr.is_running());
  6293. });
  6294. svr.wait_until_ready();
  6295. Client cli("localhost", PORT);
  6296. cli.set_keep_alive(true);
  6297. cli.set_read_timeout(std::chrono::seconds(1));
  6298. auto resa = cli.Get("/a");
  6299. ASSERT_FALSE(resa);
  6300. EXPECT_EQ(Error::Read, resa.error());
  6301. auto resb = cli.Get("/b");
  6302. ASSERT_TRUE(resb);
  6303. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6304. EXPECT_EQ("b", resb->body);
  6305. }
  6306. TEST(KeepAliveTest, MaxCount) {
  6307. size_t keep_alive_max_count = 3;
  6308. Server svr;
  6309. svr.set_keep_alive_max_count(keep_alive_max_count);
  6310. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6311. res.set_content("Hello World!", "text/plain");
  6312. });
  6313. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6314. auto se = detail::scope_exit([&] {
  6315. svr.stop();
  6316. listen_thread.join();
  6317. ASSERT_FALSE(svr.is_running());
  6318. });
  6319. svr.wait_until_ready();
  6320. Client cli(HOST, PORT);
  6321. cli.set_keep_alive(true);
  6322. for (size_t i = 0; i < 5; i++) {
  6323. auto result = cli.Get("/hi");
  6324. ASSERT_TRUE(result);
  6325. EXPECT_EQ(StatusCode::OK_200, result->status);
  6326. if (i == keep_alive_max_count - 1) {
  6327. EXPECT_EQ("close", result->get_header_value("Connection"));
  6328. } else {
  6329. EXPECT_FALSE(result->has_header("Connection"));
  6330. }
  6331. }
  6332. }
  6333. TEST(KeepAliveTest, Issue1041) {
  6334. Server svr;
  6335. svr.set_keep_alive_timeout(3);
  6336. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6337. res.set_content("Hello World!", "text/plain");
  6338. });
  6339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6340. auto se = detail::scope_exit([&] {
  6341. svr.stop();
  6342. listen_thread.join();
  6343. ASSERT_FALSE(svr.is_running());
  6344. });
  6345. svr.wait_until_ready();
  6346. Client cli(HOST, PORT);
  6347. cli.set_keep_alive(true);
  6348. auto result = cli.Get("/hi");
  6349. ASSERT_TRUE(result);
  6350. EXPECT_EQ(StatusCode::OK_200, result->status);
  6351. std::this_thread::sleep_for(std::chrono::seconds(5));
  6352. result = cli.Get("/hi");
  6353. ASSERT_TRUE(result);
  6354. EXPECT_EQ(StatusCode::OK_200, result->status);
  6355. }
  6356. TEST(KeepAliveTest, Issue1959) {
  6357. Server svr;
  6358. svr.set_keep_alive_timeout(5);
  6359. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6360. res.set_content("a", "text/plain");
  6361. });
  6362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6363. auto se = detail::scope_exit([&] {
  6364. if (!svr.is_running()) return;
  6365. svr.stop();
  6366. listen_thread.join();
  6367. ASSERT_FALSE(svr.is_running());
  6368. });
  6369. svr.wait_until_ready();
  6370. Client cli("localhost", PORT);
  6371. cli.set_keep_alive(true);
  6372. using namespace std::chrono;
  6373. auto start = steady_clock::now();
  6374. cli.Get("/a");
  6375. svr.stop();
  6376. listen_thread.join();
  6377. auto end = steady_clock::now();
  6378. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6379. EXPECT_LT(elapsed, 5000);
  6380. }
  6381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6382. TEST(KeepAliveTest, SSLClientReconnection) {
  6383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6384. ASSERT_TRUE(svr.is_valid());
  6385. svr.set_keep_alive_timeout(1);
  6386. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6387. res.set_content("Hello World!", "text/plain");
  6388. });
  6389. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6390. auto se = detail::scope_exit([&] {
  6391. svr.stop();
  6392. listen_thread.join();
  6393. ASSERT_FALSE(svr.is_running());
  6394. });
  6395. svr.wait_until_ready();
  6396. SSLClient cli(HOST, PORT);
  6397. cli.enable_server_certificate_verification(false);
  6398. cli.set_keep_alive(true);
  6399. auto result = cli.Get("/hi");
  6400. ASSERT_TRUE(result);
  6401. EXPECT_EQ(StatusCode::OK_200, result->status);
  6402. result = cli.Get("/hi");
  6403. ASSERT_TRUE(result);
  6404. EXPECT_EQ(StatusCode::OK_200, result->status);
  6405. std::this_thread::sleep_for(std::chrono::seconds(2));
  6406. // Recoonect
  6407. result = cli.Get("/hi");
  6408. ASSERT_TRUE(result);
  6409. EXPECT_EQ(StatusCode::OK_200, result->status);
  6410. result = cli.Get("/hi");
  6411. ASSERT_TRUE(result);
  6412. EXPECT_EQ(StatusCode::OK_200, result->status);
  6413. }
  6414. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6416. ASSERT_TRUE(svr.is_valid());
  6417. svr.set_keep_alive_timeout(1);
  6418. std::string content = "reconnect";
  6419. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6420. res.set_content("Hello World!", "text/plain");
  6421. });
  6422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6423. auto se = detail::scope_exit([&] {
  6424. svr.stop();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. svr.wait_until_ready();
  6429. SSLClient cli(HOST, PORT);
  6430. cli.enable_server_certificate_verification(false);
  6431. cli.set_keep_alive(true);
  6432. auto result = cli.Post(
  6433. "/hi", content.size(),
  6434. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6435. sink.write(content.c_str(), content.size());
  6436. return true;
  6437. },
  6438. "text/plain");
  6439. ASSERT_TRUE(result);
  6440. EXPECT_EQ(200, result->status);
  6441. std::this_thread::sleep_for(std::chrono::seconds(2));
  6442. // Recoonect
  6443. result = cli.Post(
  6444. "/hi", content.size(),
  6445. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6446. sink.write(content.c_str(), content.size());
  6447. return true;
  6448. },
  6449. "text/plain");
  6450. ASSERT_TRUE(result);
  6451. EXPECT_EQ(200, result->status);
  6452. result = cli.Post(
  6453. "/hi", content.size(),
  6454. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6455. sink.write(content.c_str(), content.size());
  6456. return true;
  6457. },
  6458. "text/plain");
  6459. ASSERT_TRUE(result);
  6460. EXPECT_EQ(200, result->status);
  6461. }
  6462. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6463. {
  6464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6465. ASSERT_TRUE(svr.is_valid());
  6466. svr.Get("/sni", [&](const Request &req, Response &res) {
  6467. std::string expected;
  6468. if (req.ssl) {
  6469. if (const char *sni =
  6470. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6471. expected = sni;
  6472. }
  6473. }
  6474. EXPECT_EQ(expected, req.get_param_value("expected"));
  6475. res.set_content("ok", "text/plain");
  6476. });
  6477. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6478. auto se = detail::scope_exit([&] {
  6479. svr.stop();
  6480. listen_thread.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. svr.wait_until_ready();
  6484. {
  6485. SSLClient cli("localhost", PORT);
  6486. cli.enable_server_certificate_verification(false);
  6487. auto res = cli.Get("/sni?expected=localhost");
  6488. ASSERT_TRUE(res);
  6489. }
  6490. {
  6491. SSLClient cli("::1", PORT);
  6492. cli.enable_server_certificate_verification(false);
  6493. auto res = cli.Get("/sni?expected=");
  6494. // NOTE: This may fail if the server is listening on IPv4 only
  6495. // (e.g., when localhost resolves to 127.0.0.1 only)
  6496. if (res) {
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. } else {
  6499. EXPECT_EQ(Error::Connection, res.error());
  6500. }
  6501. }
  6502. }
  6503. }
  6504. #endif
  6505. TEST(ClientProblemDetectionTest, ContentProvider) {
  6506. Server svr;
  6507. size_t content_length = 1024 * 1024;
  6508. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6509. res.set_content_provider(
  6510. content_length, "text/plain",
  6511. [&](size_t offset, size_t length, DataSink &sink) {
  6512. auto out_len = std::min(length, static_cast<size_t>(1024));
  6513. std::string out(out_len, '@');
  6514. sink.write(out.data(), out_len);
  6515. return offset < 4096;
  6516. },
  6517. [](bool success) { ASSERT_FALSE(success); });
  6518. });
  6519. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6520. res.set_content_provider(
  6521. 0, "text/plain",
  6522. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6523. EXPECT_TRUE(false);
  6524. return true;
  6525. },
  6526. [](bool success) { ASSERT_FALSE(success); });
  6527. });
  6528. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. listen_thread.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", PORT);
  6536. {
  6537. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6538. size_t /*data_length*/) { return false; });
  6539. ASSERT_FALSE(res);
  6540. }
  6541. {
  6542. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6543. size_t /*data_length*/) { return false; });
  6544. ASSERT_TRUE(res);
  6545. }
  6546. }
  6547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6548. Server svr;
  6549. svr.set_error_handler([](Request const &, Response &res) -> void {
  6550. res.set_chunked_content_provider(
  6551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6552. sink.os << "hello";
  6553. sink.os << "world";
  6554. sink.done();
  6555. return true;
  6556. });
  6557. });
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.wait_until_ready();
  6565. Client cli("localhost", PORT);
  6566. auto res = cli.Get("/");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6569. EXPECT_EQ("helloworld", res->body);
  6570. }
  6571. TEST(LongPollingTest, ClientCloseDetection) {
  6572. Server svr;
  6573. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6574. res.set_chunked_content_provider(
  6575. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6576. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6577. sink.os << "hello";
  6578. auto count = 10;
  6579. while (count > 0 && sink.is_writable()) {
  6580. this_thread::sleep_for(chrono::milliseconds(10));
  6581. count--;
  6582. }
  6583. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6584. return true;
  6585. });
  6586. });
  6587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6588. auto se = detail::scope_exit([&] {
  6589. svr.stop();
  6590. listen_thread.join();
  6591. ASSERT_FALSE(svr.is_running());
  6592. });
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6596. EXPECT_EQ("hello", string(data, data_length));
  6597. return false; // close the socket immediately.
  6598. });
  6599. ASSERT_FALSE(res);
  6600. }
  6601. TEST(GetWithParametersTest, GetWithParameters) {
  6602. Server svr;
  6603. svr.Get("/", [&](const Request &req, Response &) {
  6604. EXPECT_EQ("world", req.get_param_value("hello"));
  6605. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6606. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6607. });
  6608. svr.Get("/params", [&](const Request &req, Response &) {
  6609. EXPECT_EQ("world", req.get_param_value("hello"));
  6610. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6611. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6612. });
  6613. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6614. EXPECT_EQ("resource-id", req.matches[1]);
  6615. EXPECT_EQ("foo", req.get_param_value("param1"));
  6616. EXPECT_EQ("bar", req.get_param_value("param2"));
  6617. });
  6618. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6619. EXPECT_EQ("user-id", req.path_params.at("id"));
  6620. EXPECT_EQ("foo", req.get_param_value("param1"));
  6621. EXPECT_EQ("bar", req.get_param_value("param2"));
  6622. });
  6623. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6624. auto se = detail::scope_exit([&] {
  6625. svr.stop();
  6626. listen_thread.join();
  6627. ASSERT_FALSE(svr.is_running());
  6628. });
  6629. svr.wait_until_ready();
  6630. {
  6631. Client cli(HOST, PORT);
  6632. Params params;
  6633. params.emplace("hello", "world");
  6634. params.emplace("hello2", "world2");
  6635. params.emplace("hello3", "world3");
  6636. auto res = cli.Get("/", params, Headers{});
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. {
  6641. Client cli(HOST, PORT);
  6642. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6643. ASSERT_TRUE(res);
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. }
  6646. {
  6647. Client cli(HOST, PORT);
  6648. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6649. ASSERT_TRUE(res);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. {
  6653. Client cli(HOST, PORT);
  6654. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. }
  6658. }
  6659. TEST(GetWithParametersTest, GetWithParameters2) {
  6660. Server svr;
  6661. svr.Get("/", [&](const Request &req, Response &res) {
  6662. auto text = req.get_param_value("hello");
  6663. res.set_content(text, "text/plain");
  6664. });
  6665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6666. auto se = detail::scope_exit([&] {
  6667. svr.stop();
  6668. listen_thread.join();
  6669. ASSERT_FALSE(svr.is_running());
  6670. });
  6671. svr.wait_until_ready();
  6672. Client cli("localhost", PORT);
  6673. Params params;
  6674. params.emplace("hello", "world");
  6675. std::string body;
  6676. auto res = cli.Get("/", params, Headers{},
  6677. [&](const char *data, size_t data_length) {
  6678. body.append(data, data_length);
  6679. return true;
  6680. });
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("world", body);
  6684. }
  6685. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6686. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6687. auto host = "httpcan.org";
  6688. auto path = std::string{"/range/32"};
  6689. #else
  6690. auto host = "nghttp2.org";
  6691. auto path = std::string{"/httpbin/range/32"};
  6692. #endif
  6693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6694. SSLClient cli(host);
  6695. #else
  6696. Client cli(host);
  6697. #endif
  6698. cli.set_default_headers({make_range_header({{1, 10}})});
  6699. cli.set_connection_timeout(5);
  6700. {
  6701. auto res = cli.Get(path);
  6702. ASSERT_TRUE(res);
  6703. EXPECT_EQ("bcdefghijk", res->body);
  6704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6705. }
  6706. {
  6707. auto res = cli.Get(path);
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ("bcdefghijk", res->body);
  6710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6711. }
  6712. }
  6713. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6714. Server svr;
  6715. svr.set_default_headers({{"Hello", "World"}});
  6716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6717. res.set_content("ok", "text/plain");
  6718. });
  6719. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6720. auto se = detail::scope_exit([&] {
  6721. svr.stop();
  6722. listen_thread.join();
  6723. ASSERT_FALSE(svr.is_running());
  6724. });
  6725. svr.wait_until_ready();
  6726. Client cli("localhost", PORT);
  6727. auto res = cli.Get("/");
  6728. ASSERT_TRUE(res);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("ok", res->body);
  6731. EXPECT_EQ("World", res->get_header_value("Hello"));
  6732. }
  6733. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6734. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6736. ASSERT_TRUE(svr.is_valid());
  6737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6738. std::this_thread::sleep_for(std::chrono::seconds(2));
  6739. res.set_content("a", "text/plain");
  6740. });
  6741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6742. res.set_content("b", "text/plain");
  6743. });
  6744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. listen_thread.join();
  6748. ASSERT_FALSE(svr.is_running());
  6749. });
  6750. svr.wait_until_ready();
  6751. SSLClient cli("localhost", PORT);
  6752. cli.enable_server_certificate_verification(false);
  6753. cli.set_keep_alive(true);
  6754. cli.set_read_timeout(std::chrono::seconds(1));
  6755. auto resa = cli.Get("/a");
  6756. ASSERT_TRUE(!resa);
  6757. EXPECT_EQ(Error::Read, resa.error());
  6758. auto resb = cli.Get("/b");
  6759. ASSERT_TRUE(resb);
  6760. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6761. EXPECT_EQ("b", resb->body);
  6762. }
  6763. #endif
  6764. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6765. protected:
  6766. ServerTestWithAI_PASSIVE()
  6767. : cli_(HOST, PORT)
  6768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6769. ,
  6770. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6771. #endif
  6772. {
  6773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6774. cli_.enable_server_certificate_verification(false);
  6775. #endif
  6776. }
  6777. virtual void SetUp() {
  6778. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6779. res.set_content("Hello World!", "text/plain");
  6780. });
  6781. t_ = thread(
  6782. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6783. svr_.wait_until_ready();
  6784. }
  6785. virtual void TearDown() {
  6786. svr_.stop();
  6787. t_.join();
  6788. }
  6789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6790. SSLClient cli_;
  6791. SSLServer svr_;
  6792. #else
  6793. Client cli_;
  6794. Server svr_;
  6795. #endif
  6796. thread t_;
  6797. };
  6798. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6799. auto res = cli_.Get("/hi");
  6800. ASSERT_TRUE(res);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6803. EXPECT_EQ("Hello World!", res->body);
  6804. }
  6805. class ServerUpDownTest : public ::testing::Test {
  6806. protected:
  6807. ServerUpDownTest() : cli_(HOST, PORT) {}
  6808. virtual void SetUp() {
  6809. t_ = thread([&]() {
  6810. svr_.bind_to_any_port(HOST);
  6811. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6812. ASSERT_TRUE(svr_.listen_after_bind());
  6813. });
  6814. svr_.wait_until_ready();
  6815. }
  6816. virtual void TearDown() {
  6817. svr_.stop();
  6818. t_.join();
  6819. }
  6820. Client cli_;
  6821. Server svr_;
  6822. thread t_;
  6823. };
  6824. TEST_F(ServerUpDownTest, QuickStartStop) {
  6825. // Should not crash, especially when run with
  6826. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6827. }
  6828. class PayloadMaxLengthTest : public ::testing::Test {
  6829. protected:
  6830. PayloadMaxLengthTest()
  6831. : cli_(HOST, PORT)
  6832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6833. ,
  6834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6835. #endif
  6836. {
  6837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6838. cli_.enable_server_certificate_verification(false);
  6839. #endif
  6840. }
  6841. virtual void SetUp() {
  6842. svr_.set_payload_max_length(8);
  6843. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6844. res.set_content("test", "text/plain");
  6845. });
  6846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6847. svr_.wait_until_ready();
  6848. }
  6849. virtual void TearDown() {
  6850. svr_.stop();
  6851. t_.join();
  6852. }
  6853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6854. SSLClient cli_;
  6855. SSLServer svr_;
  6856. #else
  6857. Client cli_;
  6858. Server svr_;
  6859. #endif
  6860. thread t_;
  6861. };
  6862. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6863. auto res = cli_.Post("/test", "123456789", "text/plain");
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6866. res = cli_.Post("/test", "12345678", "text/plain");
  6867. ASSERT_TRUE(res);
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6871. // Test chunked encoding with payload exceeding the 8-byte limit
  6872. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6873. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6874. ASSERT_TRUE(res);
  6875. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6876. }
  6877. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6878. // Test chunked encoding with payload within the 8-byte limit
  6879. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6880. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6881. ASSERT_TRUE(res);
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6885. // Test using send_request to send chunked data exceeding payload limit
  6886. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6887. "Host: " +
  6888. std::string(HOST) + ":" + std::to_string(PORT) +
  6889. "\r\n"
  6890. "Transfer-Encoding: chunked\r\n"
  6891. "Connection: close\r\n"
  6892. "\r\n"
  6893. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6894. "0123456789\r\n"
  6895. "0\r\n" // End chunk
  6896. "\r\n";
  6897. std::string response;
  6898. bool result = send_request(1, chunked_request, &response);
  6899. if (!result) {
  6900. // If send_request fails, it might be because the server closed the
  6901. // connection due to payload limit enforcement, which is acceptable
  6902. SUCCEED()
  6903. << "Server rejected oversized chunked request (connection closed)";
  6904. } else {
  6905. // If we got a response, check if it's an error response or connection was
  6906. // closed early Short response length indicates connection was closed due to
  6907. // payload limit
  6908. if (response.length() <= 10) {
  6909. SUCCEED() << "Server closed connection for oversized chunked request";
  6910. } else {
  6911. // Check for error status codes
  6912. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6913. response.find("Payload Too Large") != std::string::npos ||
  6914. response.find("400") != std::string::npos);
  6915. }
  6916. }
  6917. }
  6918. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6919. // Test request without Content-Length header exceeding payload limit
  6920. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6921. "Host: " +
  6922. std::string(HOST) + ":" +
  6923. std::to_string(PORT) +
  6924. "\r\n"
  6925. "Connection: close\r\n"
  6926. "\r\n";
  6927. // Add payload exceeding the 8-byte limit
  6928. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6929. request_without_content_length += large_payload;
  6930. std::string response;
  6931. bool result = send_request(1, request_without_content_length, &response);
  6932. if (!result) {
  6933. // If send_request fails, server likely closed connection due to payload
  6934. // limit
  6935. SUCCEED() << "Server rejected oversized request without Content-Length "
  6936. "(connection closed)";
  6937. } else {
  6938. // Check if server responded with error or closed connection early
  6939. if (response.length() <= 10) {
  6940. SUCCEED() << "Server closed connection for oversized request without "
  6941. "Content-Length";
  6942. } else {
  6943. // Check for error status codes
  6944. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6945. response.find("Payload Too Large") != std::string::npos ||
  6946. response.find("400") != std::string::npos);
  6947. }
  6948. }
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6951. // Test request without Content-Length header within payload limit
  6952. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6953. "Host: " +
  6954. std::string(HOST) + ":" +
  6955. std::to_string(PORT) +
  6956. "\r\n"
  6957. "Connection: close\r\n"
  6958. "\r\n";
  6959. // Add payload within the 8-byte limit
  6960. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6961. request_without_content_length += small_payload;
  6962. std::string response;
  6963. bool result = send_request(1, request_without_content_length, &response);
  6964. // For requests without Content-Length, the server may have different behavior
  6965. // The key is that it should not reject due to payload limit for small
  6966. // payloads
  6967. if (result) {
  6968. // Check for any HTTP response (success or error, but not connection closed)
  6969. if (response.length() > 10) {
  6970. SUCCEED()
  6971. << "Server processed request without Content-Length within limit";
  6972. } else {
  6973. // Short response might indicate connection closed, which is acceptable
  6974. SUCCEED() << "Server closed connection for request without "
  6975. "Content-Length (acceptable behavior)";
  6976. }
  6977. } else {
  6978. // Connection failure might be due to protocol requirements
  6979. SUCCEED() << "Connection issue with request without Content-Length "
  6980. "(environment-specific)";
  6981. }
  6982. }
  6983. class LargePayloadMaxLengthTest : public ::testing::Test {
  6984. protected:
  6985. LargePayloadMaxLengthTest()
  6986. : cli_(HOST, PORT)
  6987. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6988. ,
  6989. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6990. #endif
  6991. {
  6992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6993. cli_.enable_server_certificate_verification(false);
  6994. #endif
  6995. }
  6996. virtual void SetUp() {
  6997. // Set 10MB payload limit
  6998. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6999. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7000. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7001. res.set_content("Large payload test", "text/plain");
  7002. });
  7003. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7004. svr_.wait_until_ready();
  7005. }
  7006. virtual void TearDown() {
  7007. svr_.stop();
  7008. t_.join();
  7009. }
  7010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7011. SSLClient cli_;
  7012. SSLServer svr_;
  7013. #else
  7014. Client cli_;
  7015. Server svr_;
  7016. #endif
  7017. thread t_;
  7018. };
  7019. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7020. // Test chunked encoding with payload within 10MB limit
  7021. std::string medium_payload(5 * 1024 * 1024,
  7022. 'A'); // 5MB payload, within 10MB limit
  7023. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. }
  7027. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7028. // Test chunked encoding with payload exceeding 10MB limit
  7029. std::string large_payload(12 * 1024 * 1024,
  7030. 'B'); // 12MB payload, exceeds 10MB limit
  7031. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7032. ASSERT_TRUE(res);
  7033. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7034. }
  7035. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7036. // Test request without Content-Length header within 10MB limit
  7037. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7038. "Host: " +
  7039. std::string(HOST) + ":" +
  7040. std::to_string(PORT) +
  7041. "\r\n"
  7042. "Connection: close\r\n"
  7043. "\r\n";
  7044. // Add 1MB payload (within 10MB limit)
  7045. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7046. request_without_content_length += medium_payload;
  7047. std::string response;
  7048. bool result = send_request(5, request_without_content_length, &response);
  7049. if (result) {
  7050. // Should get a proper HTTP response for payloads within limit
  7051. if (response.length() > 10) {
  7052. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7053. "10MB limit";
  7054. } else {
  7055. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7056. "Content-Length)";
  7057. }
  7058. } else {
  7059. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7060. }
  7061. }
  7062. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7063. // Test request without Content-Length header exceeding 10MB limit
  7064. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7065. "Host: " +
  7066. std::string(HOST) + ":" +
  7067. std::to_string(PORT) +
  7068. "\r\n"
  7069. "Connection: close\r\n"
  7070. "\r\n";
  7071. // Add 12MB payload (exceeds 10MB limit)
  7072. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7073. request_without_content_length += large_payload;
  7074. std::string response;
  7075. bool result = send_request(10, request_without_content_length, &response);
  7076. if (!result) {
  7077. // Server should close connection due to payload limit
  7078. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7079. "(connection closed)";
  7080. } else {
  7081. // Check for error response
  7082. if (response.length() <= 10) {
  7083. SUCCEED()
  7084. << "Server closed connection for 12MB request exceeding 10MB limit";
  7085. } else {
  7086. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7087. response.find("Payload Too Large") != std::string::npos ||
  7088. response.find("400") != std::string::npos);
  7089. }
  7090. }
  7091. }
  7092. TEST(HostAndPortPropertiesTest, NoSSL) {
  7093. httplib::Client cli("www.google.com", 1234);
  7094. ASSERT_EQ("www.google.com", cli.host());
  7095. ASSERT_EQ(1234, cli.port());
  7096. }
  7097. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7098. httplib::Client cli("www.google.com:1234");
  7099. ASSERT_EQ("www.google.com", cli.host());
  7100. ASSERT_EQ(1234, cli.port());
  7101. }
  7102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7103. TEST(HostAndPortPropertiesTest, SSL) {
  7104. httplib::SSLClient cli("www.google.com");
  7105. ASSERT_EQ("www.google.com", cli.host());
  7106. ASSERT_EQ(443, cli.port());
  7107. }
  7108. #endif
  7109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7110. TEST(SSLClientTest, UpdateCAStore) {
  7111. httplib::SSLClient httplib_client("www.google.com");
  7112. auto ca_store_1 = X509_STORE_new();
  7113. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7114. nullptr);
  7115. httplib_client.set_ca_cert_store(ca_store_1);
  7116. auto ca_store_2 = X509_STORE_new();
  7117. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7118. nullptr);
  7119. httplib_client.set_ca_cert_store(ca_store_2);
  7120. }
  7121. TEST(SSLClientTest, ServerNameIndication_Online) {
  7122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7123. auto host = "httpcan.org";
  7124. auto path = std::string{"/get"};
  7125. #else
  7126. auto host = "nghttp2.org";
  7127. auto path = std::string{"/httpbin/get"};
  7128. #endif
  7129. SSLClient cli(host, 443);
  7130. auto res = cli.Get(path);
  7131. ASSERT_TRUE(res);
  7132. ASSERT_EQ(StatusCode::OK_200, res->status);
  7133. }
  7134. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7135. // Use a site that will cause SSL verification failure due to self-signed cert
  7136. SSLClient cli("self-signed.badssl.com", 443);
  7137. cli.enable_server_certificate_verification(true);
  7138. auto res = cli.Get("/");
  7139. ASSERT_TRUE(!res);
  7140. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7141. // For SSL server verification errors, ssl_error should be 0, only
  7142. // ssl_openssl_error should be set
  7143. EXPECT_EQ(0, res.ssl_error());
  7144. // Verify OpenSSL error is captured for SSLServerVerification
  7145. // This occurs when SSL_get_verify_result() returns a verification failure
  7146. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7147. res.ssl_openssl_error());
  7148. }
  7149. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7150. // Use a site where hostname doesn't match the certificate
  7151. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7152. SSLClient cli("wrong.host.badssl.com", 443);
  7153. cli.enable_server_certificate_verification(true);
  7154. cli.enable_server_hostname_verification(true);
  7155. auto res = cli.Get("/");
  7156. ASSERT_TRUE(!res);
  7157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7158. // For SSL hostname verification errors, ssl_error should be 0, only
  7159. // ssl_openssl_error should be set
  7160. EXPECT_EQ(0, res.ssl_error());
  7161. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7162. // This occurs when verify_host() fails due to hostname mismatch
  7163. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7164. res.ssl_openssl_error());
  7165. }
  7166. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7167. Client cli("https://google.com");
  7168. auto res = cli.Get("/");
  7169. ASSERT_TRUE(res);
  7170. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7171. }
  7172. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7173. SSLClient cli("google.com");
  7174. cli.set_ca_cert_path(CA_CERT_FILE);
  7175. auto res = cli.Get("/");
  7176. ASSERT_TRUE(res);
  7177. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7178. }
  7179. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7180. SSLClient cli("google.com");
  7181. cli.enable_server_certificate_verification(true);
  7182. cli.set_ca_cert_path("hello");
  7183. auto res = cli.Get("/");
  7184. ASSERT_TRUE(!res);
  7185. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7186. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7187. // should be set
  7188. EXPECT_EQ(0, res.ssl_error());
  7189. // Verify OpenSSL error is captured for SSLLoadingCerts
  7190. // This error occurs when SSL_CTX_load_verify_locations() fails
  7191. // > openssl errstr 0x80000002
  7192. // error:80000002:system library::No such file or directory
  7193. // > openssl errstr 0xA000126
  7194. // error:0A000126:SSL routines::unexpected eof while reading
  7195. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7196. res.ssl_openssl_error() == 0xA000126);
  7197. }
  7198. TEST(SSLClientTest, ServerCertificateVerification4) {
  7199. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7200. ASSERT_TRUE(svr.is_valid());
  7201. svr.Get("/test", [&](const Request &, Response &res) {
  7202. res.set_content("test", "text/plain");
  7203. svr.stop();
  7204. ASSERT_TRUE(true);
  7205. });
  7206. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7207. auto se = detail::scope_exit([&] {
  7208. t.join();
  7209. ASSERT_FALSE(svr.is_running());
  7210. });
  7211. svr.wait_until_ready();
  7212. SSLClient cli("127.0.0.1", PORT);
  7213. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7214. cli.enable_server_certificate_verification(true);
  7215. cli.set_connection_timeout(30);
  7216. auto res = cli.Get("/test");
  7217. ASSERT_TRUE(res);
  7218. ASSERT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7221. std::string cert;
  7222. read_file(CA_CERT_FILE, cert);
  7223. SSLClient cli("google.com");
  7224. cli.load_ca_cert_store(cert.data(), cert.size());
  7225. const auto res = cli.Get("/");
  7226. ASSERT_TRUE(res);
  7227. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7228. }
  7229. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7230. // clang-format off
  7231. static constexpr char cert[] =
  7232. "GlobalSign Root CA\n"
  7233. "==================\n"
  7234. "-----BEGIN CERTIFICATE-----\n"
  7235. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7236. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7237. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7238. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7239. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7240. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7241. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7242. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7243. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7244. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7245. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7246. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7247. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7248. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7249. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7250. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7251. "-----END CERTIFICATE-----\n";
  7252. // clang-format on
  7253. SSLClient cli("google.com");
  7254. cli.load_ca_cert_store(cert, sizeof(cert));
  7255. const auto res = cli.Get("/");
  7256. ASSERT_TRUE(res);
  7257. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7258. }
  7259. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7260. SSLClient cli("www.youtube.com");
  7261. cli.set_ca_cert_path(CA_CERT_FILE);
  7262. cli.enable_server_certificate_verification(true);
  7263. cli.set_follow_location(true);
  7264. auto res = cli.Get("/");
  7265. ASSERT_TRUE(res);
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST(SSLClientTest, Issue2004_Online) {
  7269. Client client("https://google.com");
  7270. client.set_follow_location(true);
  7271. auto res = client.Get("/");
  7272. ASSERT_TRUE(res);
  7273. ASSERT_EQ(StatusCode::OK_200, res->status);
  7274. auto body = res->body;
  7275. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7276. }
  7277. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7278. // Create SSLClient with invalid cert/key to make is_valid() return false
  7279. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7280. "nonexistent_key.pem");
  7281. // is_valid() should be false due to cert loading failure
  7282. ASSERT_FALSE(cli.is_valid());
  7283. auto res = cli.Get("/");
  7284. ASSERT_FALSE(res);
  7285. EXPECT_EQ(Error::SSLConnection, res.error());
  7286. }
  7287. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7288. // Test for Issue #2251: SSL error not properly reported when client cert
  7289. // and key paths are swapped or mismatched
  7290. // This simulates the scenario where user accidentally swaps the cert and key
  7291. // files
  7292. // Using client cert file as private key and vice versa (completely wrong)
  7293. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7294. // Should fail validation due to cert/key mismatch
  7295. ASSERT_FALSE(cli.is_valid());
  7296. // Attempt to make a request should fail with proper error
  7297. auto res = cli.Get("/");
  7298. ASSERT_FALSE(res);
  7299. EXPECT_EQ(Error::SSLConnection, res.error());
  7300. // SSL error should be recorded in the Result object (this is the key fix for
  7301. // Issue #2251)
  7302. auto openssl_error = res.ssl_openssl_error();
  7303. EXPECT_NE(0u, openssl_error);
  7304. }
  7305. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7306. // Another variant: using valid file paths but with mismatched cert/key pair
  7307. // This tests the case where files exist but contain incompatible key material
  7308. // Using client cert with wrong key (cert2 key)
  7309. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7310. // Should fail validation
  7311. ASSERT_FALSE(cli.is_valid());
  7312. auto res = cli.Get("/");
  7313. ASSERT_FALSE(res);
  7314. // Must report error properly, not appear as success
  7315. EXPECT_EQ(Error::SSLConnection, res.error());
  7316. // OpenSSL error should be captured in Result
  7317. EXPECT_NE(0u, res.ssl_openssl_error());
  7318. }
  7319. #if 0
  7320. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7321. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7322. ASSERT_TRUE(cli != nullptr);
  7323. cli->set_address_family(AF_INET6);
  7324. cli->set_interface("en0");
  7325. auto res = cli->Get("/get");
  7326. ASSERT_TRUE(res);
  7327. ASSERT_EQ(StatusCode::OK_200, res->status);
  7328. }
  7329. #endif
  7330. void ClientCertPresent(
  7331. const std::string &client_cert_file,
  7332. const std::string &client_private_key_file,
  7333. const std::string &client_encrypted_private_key_pass = std::string()) {
  7334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7335. CLIENT_CA_CERT_DIR);
  7336. ASSERT_TRUE(svr.is_valid());
  7337. svr.Get("/test", [&](const Request &req, Response &res) {
  7338. res.set_content("test", "text/plain");
  7339. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7340. ASSERT_TRUE(peer_cert != nullptr);
  7341. auto subject_name = X509_get_subject_name(peer_cert);
  7342. ASSERT_TRUE(subject_name != nullptr);
  7343. std::string common_name;
  7344. {
  7345. char name[BUFSIZ];
  7346. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7347. name, sizeof(name));
  7348. common_name.assign(name, static_cast<size_t>(name_len));
  7349. }
  7350. EXPECT_EQ("Common Name", common_name);
  7351. X509_free(peer_cert);
  7352. });
  7353. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7354. auto se = detail::scope_exit([&] {
  7355. svr.stop();
  7356. t.join();
  7357. ASSERT_FALSE(svr.is_running());
  7358. });
  7359. svr.wait_until_ready();
  7360. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7361. client_encrypted_private_key_pass);
  7362. cli.enable_server_certificate_verification(false);
  7363. cli.set_connection_timeout(30);
  7364. auto res = cli.Get("/test");
  7365. ASSERT_TRUE(res);
  7366. ASSERT_EQ(StatusCode::OK_200, res->status);
  7367. }
  7368. TEST(SSLClientServerTest, ClientCertPresent) {
  7369. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7370. }
  7371. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7372. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7373. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7374. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7375. }
  7376. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7377. void MemoryClientCertPresent(
  7378. const std::string &client_cert_file,
  7379. const std::string &client_private_key_file,
  7380. const std::string &client_encrypted_private_key_pass = std::string()) {
  7381. auto f = fopen(SERVER_CERT_FILE, "r+");
  7382. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7383. fclose(f);
  7384. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7385. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7386. fclose(f);
  7387. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7388. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7389. auto client_ca_cert_store = X509_STORE_new();
  7390. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7391. X509_free(client_cert);
  7392. fclose(f);
  7393. f = fopen(client_cert_file.c_str(), "r+");
  7394. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7395. fclose(f);
  7396. f = fopen(client_private_key_file.c_str(), "r+");
  7397. auto client_private_key = PEM_read_PrivateKey(
  7398. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7399. fclose(f);
  7400. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7401. ASSERT_TRUE(svr.is_valid());
  7402. svr.Get("/test", [&](const Request &req, Response &res) {
  7403. res.set_content("test", "text/plain");
  7404. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7405. ASSERT_TRUE(peer_cert != nullptr);
  7406. auto subject_name = X509_get_subject_name(peer_cert);
  7407. ASSERT_TRUE(subject_name != nullptr);
  7408. std::string common_name;
  7409. {
  7410. char name[BUFSIZ];
  7411. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7412. name, sizeof(name));
  7413. common_name.assign(name, static_cast<size_t>(name_len));
  7414. }
  7415. EXPECT_EQ("Common Name", common_name);
  7416. X509_free(peer_cert);
  7417. });
  7418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7419. auto se = detail::scope_exit([&] {
  7420. svr.stop();
  7421. t.join();
  7422. ASSERT_FALSE(svr.is_running());
  7423. });
  7424. svr.wait_until_ready();
  7425. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7426. client_encrypted_private_key_pass);
  7427. cli.enable_server_certificate_verification(false);
  7428. cli.set_connection_timeout(30);
  7429. auto res = cli.Get("/test");
  7430. ASSERT_TRUE(res);
  7431. ASSERT_EQ(StatusCode::OK_200, res->status);
  7432. X509_free(server_cert);
  7433. EVP_PKEY_free(server_private_key);
  7434. X509_free(client_cert);
  7435. EVP_PKEY_free(client_private_key);
  7436. }
  7437. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7438. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7439. }
  7440. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7441. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7442. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7443. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7444. }
  7445. #endif
  7446. TEST(SSLClientServerTest, ClientCertMissing) {
  7447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7448. CLIENT_CA_CERT_DIR);
  7449. ASSERT_TRUE(svr.is_valid());
  7450. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7452. auto se = detail::scope_exit([&] {
  7453. svr.stop();
  7454. t.join();
  7455. ASSERT_FALSE(svr.is_running());
  7456. });
  7457. svr.wait_until_ready();
  7458. SSLClient cli(HOST, PORT);
  7459. cli.set_connection_timeout(30);
  7460. auto res = cli.Get("/test");
  7461. ASSERT_TRUE(!res);
  7462. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7463. // For SSL server verification errors, ssl_error should be 0, only
  7464. // ssl_openssl_error should be set
  7465. EXPECT_EQ(0, res.ssl_error());
  7466. // Verify OpenSSL error is captured for SSLServerVerification
  7467. // Note: This test may have different error codes depending on the exact
  7468. // verification failure
  7469. EXPECT_NE(0UL, res.ssl_openssl_error());
  7470. }
  7471. TEST(SSLClientServerTest, TrustDirOptional) {
  7472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7473. ASSERT_TRUE(svr.is_valid());
  7474. svr.Get("/test", [&](const Request &, Response &res) {
  7475. res.set_content("test", "text/plain");
  7476. });
  7477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7478. auto se = detail::scope_exit([&] {
  7479. svr.stop();
  7480. t.join();
  7481. ASSERT_FALSE(svr.is_running());
  7482. });
  7483. svr.wait_until_ready();
  7484. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7485. cli.enable_server_certificate_verification(false);
  7486. cli.set_connection_timeout(30);
  7487. auto res = cli.Get("/test");
  7488. ASSERT_TRUE(res);
  7489. ASSERT_EQ(StatusCode::OK_200, res->status);
  7490. }
  7491. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7492. class NoListenSSLServer : public SSLServer {
  7493. public:
  7494. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7495. const char *client_ca_cert_file_path,
  7496. const char *client_ca_cert_dir_path = nullptr)
  7497. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7498. client_ca_cert_dir_path),
  7499. stop_(false) {}
  7500. std::atomic_bool stop_;
  7501. private:
  7502. bool process_and_close_socket(socket_t /*sock*/) override {
  7503. // Don't create SSL context
  7504. while (!stop_.load()) {
  7505. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7506. }
  7507. return true;
  7508. }
  7509. };
  7510. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7511. CLIENT_CA_CERT_FILE);
  7512. ASSERT_TRUE(svr.is_valid());
  7513. svr.Get("/test", [&](const Request &, Response &res) {
  7514. res.set_content("test", "text/plain");
  7515. });
  7516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7517. auto se = detail::scope_exit([&] {
  7518. svr.stop_ = true;
  7519. svr.stop();
  7520. t.join();
  7521. ASSERT_FALSE(svr.is_running());
  7522. });
  7523. svr.wait_until_ready();
  7524. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7525. cli.enable_server_certificate_verification(false);
  7526. cli.set_connection_timeout(1);
  7527. auto res = cli.Get("/test");
  7528. ASSERT_TRUE(!res);
  7529. EXPECT_EQ(Error::SSLConnection, res.error());
  7530. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7531. }
  7532. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7533. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7534. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7535. SSL_CTX_set_options(&ssl_ctx,
  7536. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7537. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7538. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7539. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7540. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7541. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7542. "ECDHE-DSS-AES128-SHA256:"
  7543. "ECDHE-RSA-AES256-SHA256:"
  7544. "ECDHE-DSS-AES256-SHA256:";
  7545. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7546. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7547. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7548. SSL_FILETYPE_PEM) != 1) {
  7549. return false;
  7550. }
  7551. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7552. CLIENT_CA_CERT_DIR);
  7553. SSL_CTX_set_verify(
  7554. &ssl_ctx,
  7555. SSL_VERIFY_PEER |
  7556. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7557. nullptr);
  7558. return true;
  7559. };
  7560. SSLServer svr(setup_ssl_ctx_callback);
  7561. ASSERT_TRUE(svr.is_valid());
  7562. svr.Get("/test", [&](const Request &req, Response &res) {
  7563. res.set_content("test", "text/plain");
  7564. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7565. ASSERT_TRUE(peer_cert != nullptr);
  7566. auto subject_name = X509_get_subject_name(peer_cert);
  7567. ASSERT_TRUE(subject_name != nullptr);
  7568. std::string common_name;
  7569. {
  7570. char name[BUFSIZ];
  7571. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7572. name, sizeof(name));
  7573. common_name.assign(name, static_cast<size_t>(name_len));
  7574. }
  7575. EXPECT_EQ("Common Name", common_name);
  7576. X509_free(peer_cert);
  7577. });
  7578. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7579. auto se = detail::scope_exit([&] {
  7580. svr.stop();
  7581. t.join();
  7582. ASSERT_FALSE(svr.is_running());
  7583. });
  7584. svr.wait_until_ready();
  7585. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7586. cli.enable_server_certificate_verification(false);
  7587. cli.set_connection_timeout(30);
  7588. auto res = cli.Get("/test");
  7589. ASSERT_TRUE(res);
  7590. ASSERT_EQ(StatusCode::OK_200, res->status);
  7591. }
  7592. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7594. ASSERT_TRUE(svr.is_valid());
  7595. // Set up a handler to verify client certificate is present
  7596. bool client_cert_verified = false;
  7597. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7598. // Verify that client certificate was provided
  7599. client_cert_verified = true;
  7600. res.set_content("success", "text/plain");
  7601. });
  7602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7603. auto se = detail::scope_exit([&] {
  7604. svr.stop();
  7605. t.join();
  7606. ASSERT_FALSE(svr.is_running());
  7607. });
  7608. svr.wait_until_ready();
  7609. // Client with certificate
  7610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7611. cli.enable_server_certificate_verification(false);
  7612. cli.set_connection_timeout(30);
  7613. auto res = cli.Get("/test");
  7614. ASSERT_TRUE(res);
  7615. ASSERT_EQ(StatusCode::OK_200, res->status);
  7616. ASSERT_TRUE(client_cert_verified);
  7617. EXPECT_EQ("success", res->body);
  7618. }
  7619. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7620. // Test that when client CA cert file is provided,
  7621. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7622. // Create a server with client authentication
  7623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7624. ASSERT_TRUE(svr.is_valid());
  7625. // We can't directly access the SSL_CTX from SSLServer to verify,
  7626. // but we can test that the server properly requests client certificates
  7627. // and accepts valid ones from the specified CA
  7628. bool handler_called = false;
  7629. svr.Get("/test", [&](const Request &req, Response &res) {
  7630. handler_called = true;
  7631. // Verify that a client certificate was provided
  7632. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7633. ASSERT_TRUE(peer_cert != nullptr);
  7634. // Get the issuer name
  7635. auto issuer_name = X509_get_issuer_name(peer_cert);
  7636. ASSERT_TRUE(issuer_name != nullptr);
  7637. char issuer_buf[256];
  7638. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7639. // The client certificate should be issued by our test CA
  7640. std::string issuer_str(issuer_buf);
  7641. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7642. X509_free(peer_cert);
  7643. res.set_content("authenticated", "text/plain");
  7644. });
  7645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7646. auto se = detail::scope_exit([&] {
  7647. svr.stop();
  7648. t.join();
  7649. ASSERT_FALSE(svr.is_running());
  7650. });
  7651. svr.wait_until_ready();
  7652. // Connect with a client certificate issued by the CA
  7653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7654. cli.enable_server_certificate_verification(false);
  7655. cli.set_connection_timeout(30);
  7656. auto res = cli.Get("/test");
  7657. ASSERT_TRUE(res);
  7658. ASSERT_EQ(StatusCode::OK_200, res->status);
  7659. ASSERT_TRUE(handler_called);
  7660. EXPECT_EQ("authenticated", res->body);
  7661. }
  7662. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7663. // Test 1: Valid CA file - no error should be recorded
  7664. {
  7665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7666. CLIENT_CA_CERT_FILE);
  7667. ASSERT_TRUE(svr.is_valid());
  7668. // With valid setup, last_ssl_error should be 0
  7669. EXPECT_EQ(0, svr.ssl_last_error());
  7670. }
  7671. // Test 2: Invalid CA file content
  7672. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7673. {
  7674. // Create a temporary file with completely invalid content
  7675. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7676. {
  7677. std::ofstream ofs(temp_invalid_ca);
  7678. ofs << "This is not a certificate file at all\n";
  7679. ofs << "Just plain text content\n";
  7680. }
  7681. // Create server with invalid CA file
  7682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7683. // Clean up temporary file
  7684. std::remove(temp_invalid_ca);
  7685. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7686. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7687. // Note: SSL_CTX_load_verify_locations typically fails first,
  7688. // but our error handling code path is still exercised
  7689. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7690. }
  7691. }
  7692. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7693. // Test SSL server using X509_STORE constructor with client CA certificates
  7694. // This test verifies that Phase 2 implementation correctly extracts CA names
  7695. // from an X509_STORE and sets them in the SSL context
  7696. // Load the CA certificate into memory
  7697. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7698. ASSERT_NE(nullptr, bio);
  7699. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7700. BIO_free(bio);
  7701. ASSERT_NE(nullptr, ca_cert);
  7702. // Create an X509_STORE and add the CA certificate
  7703. auto store = X509_STORE_new();
  7704. ASSERT_NE(nullptr, store);
  7705. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7706. // Load server certificate and private key
  7707. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7708. ASSERT_NE(nullptr, cert_bio);
  7709. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7710. BIO_free(cert_bio);
  7711. ASSERT_NE(nullptr, server_cert);
  7712. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7713. ASSERT_NE(nullptr, key_bio);
  7714. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7715. BIO_free(key_bio);
  7716. ASSERT_NE(nullptr, server_key);
  7717. // Create SSLServer with X509_STORE constructor
  7718. // Note: X509_STORE ownership is transferred to SSL_CTX
  7719. SSLServer svr(server_cert, server_key, store);
  7720. ASSERT_TRUE(svr.is_valid());
  7721. // No SSL error should be recorded for valid setup
  7722. EXPECT_EQ(0, svr.ssl_last_error());
  7723. // Set up server endpoints
  7724. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7725. res.set_content("ok", "text/plain");
  7726. });
  7727. // Start server in a thread
  7728. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7729. svr.wait_until_ready();
  7730. // Connect with client certificate (using constructor with paths)
  7731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7732. cli.enable_server_certificate_verification(false);
  7733. auto res = cli.Get("/test-x509store");
  7734. ASSERT_TRUE(res);
  7735. EXPECT_EQ(200, res->status);
  7736. EXPECT_EQ("ok", res->body);
  7737. // Clean up
  7738. X509_free(server_cert);
  7739. EVP_PKEY_free(server_key);
  7740. X509_free(ca_cert);
  7741. svr.stop();
  7742. server_thread.join();
  7743. }
  7744. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7745. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7746. // prepare large data
  7747. std::random_device seed_gen;
  7748. std::mt19937 random(seed_gen());
  7749. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7750. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7751. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7752. // server
  7753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7754. ASSERT_TRUE(svr.is_valid());
  7755. svr.Post("/binary", [&](const Request &req, Response &res) {
  7756. EXPECT_EQ(large_size_byte, req.body.size());
  7757. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7758. res.set_content(req.body, "application/octet-stream");
  7759. });
  7760. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7761. auto se = detail::scope_exit([&] {
  7762. svr.stop();
  7763. listen_thread.join();
  7764. ASSERT_FALSE(svr.is_running());
  7765. });
  7766. svr.wait_until_ready();
  7767. // client POST
  7768. SSLClient cli("localhost", PORT);
  7769. cli.enable_server_certificate_verification(false);
  7770. cli.set_read_timeout(std::chrono::seconds(100));
  7771. cli.set_write_timeout(std::chrono::seconds(100));
  7772. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7773. large_size_byte, "application/octet-stream");
  7774. // compare
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ(large_size_byte, res->body.size());
  7777. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7778. }
  7779. #endif
  7780. #ifdef _WIN32
  7781. TEST(CleanupTest, WSACleanup) {
  7782. int ret = WSACleanup();
  7783. ASSERT_EQ(0, ret);
  7784. }
  7785. #endif
  7786. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7787. TEST(NoSSLSupport, SimpleInterface) {
  7788. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7789. }
  7790. #endif
  7791. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7792. TEST(InvalidScheme, SimpleInterface) {
  7793. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7794. }
  7795. #endif
  7796. TEST(NoScheme, SimpleInterface) {
  7797. Client cli("yahoo.com:80");
  7798. ASSERT_TRUE(cli.is_valid());
  7799. }
  7800. TEST(SendAPI, SimpleInterface_Online) {
  7801. Client cli("http://yahoo.com");
  7802. Request req;
  7803. req.method = "GET";
  7804. req.path = "/";
  7805. auto res = cli.send(req);
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7808. }
  7809. TEST(SendAPI, WithParamsInRequest) {
  7810. Server svr;
  7811. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7812. EXPECT_TRUE(req.has_param("test"));
  7813. EXPECT_EQ("test_value", req.get_param_value("test"));
  7814. });
  7815. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7816. auto se = detail::scope_exit([&] {
  7817. svr.stop();
  7818. t.join();
  7819. ASSERT_FALSE(svr.is_running());
  7820. });
  7821. svr.wait_until_ready();
  7822. Client cli(HOST, PORT);
  7823. {
  7824. Request req;
  7825. req.method = "GET";
  7826. req.path = "/";
  7827. req.params.emplace("test", "test_value");
  7828. auto res = cli.send(req);
  7829. ASSERT_TRUE(res);
  7830. }
  7831. {
  7832. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7833. ASSERT_TRUE(res);
  7834. }
  7835. }
  7836. TEST(ClientImplMethods, GetSocketTest) {
  7837. httplib::Server svr;
  7838. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7839. res.status = StatusCode::OK_200;
  7840. });
  7841. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7842. auto se = detail::scope_exit([&] {
  7843. svr.stop();
  7844. thread.join();
  7845. ASSERT_FALSE(svr.is_running());
  7846. });
  7847. svr.wait_until_ready();
  7848. {
  7849. httplib::Client cli("http://127.0.0.1:3333");
  7850. cli.set_keep_alive(true);
  7851. // Use the behavior of cpp-httplib of opening the connection
  7852. // only when the first request happens. If that changes,
  7853. // this test would be obsolete.
  7854. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7855. // This also implicitly tests the server. But other tests would fail much
  7856. // earlier than this one to be considered.
  7857. auto res = cli.Get("/");
  7858. ASSERT_TRUE(res);
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7861. }
  7862. }
  7863. // Disabled due to out-of-memory problem on GitHub Actions
  7864. #ifdef _WIN64
  7865. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7866. // allocate content size larger than 2GB in memory
  7867. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7868. char *content = (char *)malloc(content_size);
  7869. ASSERT_TRUE(content);
  7870. Server svr;
  7871. svr.Get("/foo",
  7872. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7873. res.set_content(content, content_size, "application/octet-stream");
  7874. });
  7875. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7876. auto se = detail::scope_exit([&] {
  7877. svr.stop();
  7878. listen_thread.join();
  7879. if (content) free(content);
  7880. ASSERT_FALSE(svr.is_running());
  7881. });
  7882. svr.wait_until_ready();
  7883. Client cli(HOST, PORT);
  7884. auto res = cli.Get("/foo");
  7885. ASSERT_TRUE(res);
  7886. EXPECT_EQ(StatusCode::OK_200, res->status);
  7887. EXPECT_EQ(content_size, res->body.length());
  7888. }
  7889. #endif
  7890. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7891. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7892. Client cli("http://yahoo.com");
  7893. auto res = cli.Get("/");
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7896. cli.set_follow_location(true);
  7897. res = cli.Get("/");
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7901. }
  7902. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7903. Client cli("https://yahoo.com");
  7904. auto res = cli.Get("/");
  7905. ASSERT_TRUE(res);
  7906. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7907. cli.set_follow_location(true);
  7908. res = cli.Get("/");
  7909. ASSERT_TRUE(res);
  7910. EXPECT_EQ(StatusCode::OK_200, res->status);
  7911. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7912. }
  7913. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7914. Client cli("https://yahoo.com");
  7915. auto res = cli.Get("/");
  7916. ASSERT_TRUE(res);
  7917. ASSERT_FALSE(!res);
  7918. ASSERT_TRUE(res);
  7919. ASSERT_FALSE(res == nullptr);
  7920. ASSERT_TRUE(res != nullptr);
  7921. EXPECT_EQ(Error::Success, res.error());
  7922. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7923. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7925. cli.set_follow_location(true);
  7926. res = cli.Get("/");
  7927. ASSERT_TRUE(res);
  7928. EXPECT_EQ(Error::Success, res.error());
  7929. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7930. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7933. }
  7934. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7935. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7936. Client cli("https://cdnjs.cloudflare.com");
  7937. auto res =
  7938. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7939. ASSERT_TRUE(res);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. EXPECT_EQ(287630U, res->body.size());
  7942. EXPECT_EQ("application/javascript; charset=utf-8",
  7943. res->get_header_value("Content-Type"));
  7944. }
  7945. #endif
  7946. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7947. #undef REDIR_HOST // Silence compiler warning
  7948. #define REDIR_HOST "https://httpbingo.org"
  7949. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7950. Client cli(REDIR_HOST);
  7951. cli.set_follow_location(true);
  7952. auto res =
  7953. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7954. ASSERT_TRUE(res);
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. }
  7957. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7958. Client cli(REDIR_HOST);
  7959. cli.set_follow_location(true);
  7960. Params params;
  7961. params.emplace("url", "http://example.com");
  7962. params.emplace("status_code", "302");
  7963. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7964. ASSERT_TRUE(res);
  7965. EXPECT_EQ(StatusCode::OK_200, res->status);
  7966. }
  7967. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7968. Client cli(REDIR_HOST);
  7969. cli.set_follow_location(true);
  7970. Params params;
  7971. params.emplace("url", "http://example.com");
  7972. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7973. ASSERT_TRUE(res);
  7974. EXPECT_EQ(StatusCode::OK_200, res->status);
  7975. }
  7976. TEST(HttpToHttpsRedirectTest, CertFile) {
  7977. Server svr;
  7978. ASSERT_TRUE(svr.is_valid());
  7979. svr.Get("/index", [&](const Request &, Response &res) {
  7980. res.set_redirect("https://127.0.0.1:1235/index");
  7981. svr.stop();
  7982. });
  7983. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7984. ASSERT_TRUE(ssl_svr.is_valid());
  7985. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7986. res.set_content("test", "text/plain");
  7987. ssl_svr.stop();
  7988. });
  7989. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7990. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7991. auto se = detail::scope_exit([&] {
  7992. t2.join();
  7993. t.join();
  7994. ASSERT_FALSE(svr.is_running());
  7995. });
  7996. svr.wait_until_ready();
  7997. ssl_svr.wait_until_ready();
  7998. Client cli("127.0.0.1", PORT);
  7999. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8000. cli.enable_server_certificate_verification(true);
  8001. cli.set_follow_location(true);
  8002. cli.set_connection_timeout(30);
  8003. auto res = cli.Get("/index");
  8004. ASSERT_TRUE(res);
  8005. ASSERT_EQ(StatusCode::OK_200, res->status);
  8006. }
  8007. TEST(SSLClientRedirectTest, CertFile) {
  8008. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8009. ASSERT_TRUE(ssl_svr1.is_valid());
  8010. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8011. res.set_redirect("https://127.0.0.1:1235/index");
  8012. ssl_svr1.stop();
  8013. });
  8014. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8015. ASSERT_TRUE(ssl_svr2.is_valid());
  8016. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8017. res.set_content("test", "text/plain");
  8018. ssl_svr2.stop();
  8019. });
  8020. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8021. thread t2 =
  8022. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8023. auto se = detail::scope_exit([&] {
  8024. t2.join();
  8025. t.join();
  8026. ASSERT_FALSE(ssl_svr1.is_running());
  8027. });
  8028. ssl_svr1.wait_until_ready();
  8029. ssl_svr2.wait_until_ready();
  8030. SSLClient cli("127.0.0.1", PORT);
  8031. std::string cert;
  8032. read_file(SERVER_CERT2_FILE, cert);
  8033. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8034. cli.enable_server_certificate_verification(true);
  8035. cli.set_follow_location(true);
  8036. cli.set_connection_timeout(30);
  8037. auto res = cli.Get("/index");
  8038. ASSERT_TRUE(res);
  8039. ASSERT_EQ(StatusCode::OK_200, res->status);
  8040. }
  8041. TEST(MultipartFormDataTest, LargeData) {
  8042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8043. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8044. const ContentReader &content_reader) {
  8045. if (req.is_multipart_form_data()) {
  8046. std::vector<FormData> items;
  8047. content_reader(
  8048. [&](const FormData &file) {
  8049. items.push_back(file);
  8050. return true;
  8051. },
  8052. [&](const char *data, size_t data_length) {
  8053. items.back().content.append(data, data_length);
  8054. return true;
  8055. });
  8056. EXPECT_TRUE(std::string(items[0].name) == "document");
  8057. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8058. EXPECT_TRUE(items[0].filename == "2MB_data");
  8059. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8060. EXPECT_TRUE(items[1].name == "hello");
  8061. EXPECT_TRUE(items[1].content == "world");
  8062. EXPECT_TRUE(items[1].filename == "");
  8063. EXPECT_TRUE(items[1].content_type == "");
  8064. } else {
  8065. std::string body;
  8066. content_reader([&](const char *data, size_t data_length) {
  8067. body.append(data, data_length);
  8068. return true;
  8069. });
  8070. }
  8071. });
  8072. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8073. auto se = detail::scope_exit([&] {
  8074. svr.stop();
  8075. t.join();
  8076. ASSERT_FALSE(svr.is_running());
  8077. });
  8078. svr.wait_until_ready();
  8079. {
  8080. std::string data(1024 * 1024 * 2, '.');
  8081. std::stringstream buffer;
  8082. buffer << data;
  8083. Client cli("https://localhost:8080");
  8084. cli.enable_server_certificate_verification(false);
  8085. UploadFormDataItems items{
  8086. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8087. {"hello", "world", "", ""},
  8088. };
  8089. auto res = cli.Post("/post", items);
  8090. ASSERT_TRUE(res);
  8091. ASSERT_EQ(StatusCode::OK_200, res->status);
  8092. }
  8093. }
  8094. TEST(MultipartFormDataTest, DataProviderItems) {
  8095. std::random_device seed_gen;
  8096. std::mt19937 random(seed_gen());
  8097. std::string rand1;
  8098. rand1.resize(1000);
  8099. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8100. std::string rand2;
  8101. rand2.resize(3000);
  8102. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8104. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8105. const ContentReader &content_reader) {
  8106. ASSERT_FALSE(req.is_multipart_form_data());
  8107. std::string body;
  8108. content_reader([&](const char *data, size_t data_length) {
  8109. body.append(data, data_length);
  8110. return true;
  8111. });
  8112. EXPECT_EQ(body, "");
  8113. });
  8114. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8115. const ContentReader &content_reader) {
  8116. ASSERT_TRUE(req.is_multipart_form_data());
  8117. std::vector<FormData> items;
  8118. content_reader(
  8119. [&](const FormData &file) {
  8120. items.push_back(file);
  8121. return true;
  8122. },
  8123. [&](const char *data, size_t data_length) {
  8124. items.back().content.append(data, data_length);
  8125. return true;
  8126. });
  8127. ASSERT_TRUE(items.size() == 2);
  8128. EXPECT_EQ(std::string(items[0].name), "name1");
  8129. EXPECT_EQ(items[0].content, "Testing123");
  8130. EXPECT_EQ(items[0].filename, "filename1");
  8131. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8132. EXPECT_EQ(items[1].name, "name2");
  8133. EXPECT_EQ(items[1].content, "Testing456");
  8134. EXPECT_EQ(items[1].filename, "");
  8135. EXPECT_EQ(items[1].content_type, "");
  8136. });
  8137. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8138. const ContentReader &content_reader) {
  8139. ASSERT_TRUE(req.is_multipart_form_data());
  8140. std::vector<FormData> items;
  8141. content_reader(
  8142. [&](const FormData &file) {
  8143. items.push_back(file);
  8144. return true;
  8145. },
  8146. [&](const char *data, size_t data_length) {
  8147. items.back().content.append(data, data_length);
  8148. return true;
  8149. });
  8150. ASSERT_TRUE(items.size() == 2);
  8151. EXPECT_EQ(items[0].name, "name3");
  8152. EXPECT_EQ(items[0].content, rand1);
  8153. EXPECT_EQ(items[0].filename, "filename3");
  8154. EXPECT_EQ(items[0].content_type, "");
  8155. EXPECT_EQ(items[1].name, "name4");
  8156. EXPECT_EQ(items[1].content, rand2);
  8157. EXPECT_EQ(items[1].filename, "filename4");
  8158. EXPECT_EQ(items[1].content_type, "");
  8159. });
  8160. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8161. const ContentReader &content_reader) {
  8162. ASSERT_TRUE(req.is_multipart_form_data());
  8163. std::vector<FormData> items;
  8164. content_reader(
  8165. [&](const FormData &file) {
  8166. items.push_back(file);
  8167. return true;
  8168. },
  8169. [&](const char *data, size_t data_length) {
  8170. items.back().content.append(data, data_length);
  8171. return true;
  8172. });
  8173. ASSERT_TRUE(items.size() == 4);
  8174. EXPECT_EQ(std::string(items[0].name), "name1");
  8175. EXPECT_EQ(items[0].content, "Testing123");
  8176. EXPECT_EQ(items[0].filename, "filename1");
  8177. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8178. EXPECT_EQ(items[1].name, "name2");
  8179. EXPECT_EQ(items[1].content, "Testing456");
  8180. EXPECT_EQ(items[1].filename, "");
  8181. EXPECT_EQ(items[1].content_type, "");
  8182. EXPECT_EQ(items[2].name, "name3");
  8183. EXPECT_EQ(items[2].content, rand1);
  8184. EXPECT_EQ(items[2].filename, "filename3");
  8185. EXPECT_EQ(items[2].content_type, "");
  8186. EXPECT_EQ(items[3].name, "name4");
  8187. EXPECT_EQ(items[3].content, rand2);
  8188. EXPECT_EQ(items[3].filename, "filename4");
  8189. EXPECT_EQ(items[3].content_type, "");
  8190. });
  8191. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8192. auto se = detail::scope_exit([&] {
  8193. svr.stop();
  8194. t.join();
  8195. ASSERT_FALSE(svr.is_running());
  8196. });
  8197. svr.wait_until_ready();
  8198. {
  8199. Client cli("https://localhost:8080");
  8200. cli.enable_server_certificate_verification(false);
  8201. UploadFormDataItems items{
  8202. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8203. {"name2", "Testing456", "", ""}, // not a file
  8204. };
  8205. {
  8206. auto res = cli.Post("/post-none", {}, {}, {});
  8207. ASSERT_TRUE(res);
  8208. ASSERT_EQ(StatusCode::OK_200, res->status);
  8209. }
  8210. FormDataProviderItems providers;
  8211. {
  8212. auto res =
  8213. cli.Post("/post-items", {}, items, providers); // empty providers
  8214. ASSERT_TRUE(res);
  8215. ASSERT_EQ(StatusCode::OK_200, res->status);
  8216. }
  8217. providers.push_back({"name3",
  8218. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8219. // test the offset is given correctly at each step
  8220. if (!offset)
  8221. sink.os.write(rand1.data(), 30);
  8222. else if (offset == 30)
  8223. sink.os.write(rand1.data() + 30, 300);
  8224. else if (offset == 330)
  8225. sink.os.write(rand1.data() + 330, 670);
  8226. else if (offset == rand1.size())
  8227. sink.done();
  8228. return true;
  8229. },
  8230. "filename3",
  8231. {}});
  8232. providers.push_back({"name4",
  8233. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8234. // test the offset is given correctly at each step
  8235. if (!offset)
  8236. sink.os.write(rand2.data(), 2000);
  8237. else if (offset == 2000)
  8238. sink.os.write(rand2.data() + 2000, 1);
  8239. else if (offset == 2001)
  8240. sink.os.write(rand2.data() + 2001, 999);
  8241. else if (offset == rand2.size())
  8242. sink.done();
  8243. return true;
  8244. },
  8245. "filename4",
  8246. {}});
  8247. {
  8248. auto res = cli.Post("/post-providers", {}, {}, providers);
  8249. ASSERT_TRUE(res);
  8250. ASSERT_EQ(StatusCode::OK_200, res->status);
  8251. }
  8252. {
  8253. auto res = cli.Post("/post-both", {}, items, providers);
  8254. ASSERT_TRUE(res);
  8255. ASSERT_EQ(StatusCode::OK_200, res->status);
  8256. }
  8257. }
  8258. }
  8259. TEST(MultipartFormDataTest, BadHeader) {
  8260. Server svr;
  8261. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8262. res.set_content("ok", "text/plain");
  8263. });
  8264. thread t = thread([&] { svr.listen(HOST, PORT); });
  8265. auto se = detail::scope_exit([&] {
  8266. svr.stop();
  8267. t.join();
  8268. ASSERT_FALSE(svr.is_running());
  8269. });
  8270. svr.wait_until_ready();
  8271. const std::string body =
  8272. "This is the preamble. It is to be ignored, though it\r\n"
  8273. "is a handy place for composition agents to include an\r\n"
  8274. "explanatory note to non-MIME conformant readers.\r\n"
  8275. "\r\n"
  8276. "\r\n"
  8277. "--simple boundary\r\n"
  8278. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8279. ": BAD...\r\n"
  8280. "\r\n"
  8281. "value1\r\n"
  8282. "--simple boundary\r\n"
  8283. "Content-Disposition: form-data; name=\"field2\"; "
  8284. "filename=\"example.txt\"\r\n"
  8285. "\r\n"
  8286. "value2\r\n"
  8287. "--simple boundary--\r\n"
  8288. "This is the epilogue. It is also to be ignored.\r\n";
  8289. std::string content_type =
  8290. R"(multipart/form-data; boundary="simple boundary")";
  8291. Client cli(HOST, PORT);
  8292. auto res = cli.Post("/post", body, content_type.c_str());
  8293. ASSERT_TRUE(res);
  8294. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8295. }
  8296. TEST(MultipartFormDataTest, WithPreamble) {
  8297. Server svr;
  8298. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8299. res.set_content("ok", "text/plain");
  8300. });
  8301. thread t = thread([&] { svr.listen(HOST, PORT); });
  8302. auto se = detail::scope_exit([&] {
  8303. svr.stop();
  8304. t.join();
  8305. ASSERT_FALSE(svr.is_running());
  8306. });
  8307. svr.wait_until_ready();
  8308. const std::string body =
  8309. "This is the preamble. It is to be ignored, though it\r\n"
  8310. "is a handy place for composition agents to include an\r\n"
  8311. "explanatory note to non-MIME conformant readers.\r\n"
  8312. "\r\n"
  8313. "\r\n"
  8314. "--simple boundary\r\n"
  8315. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8316. "\r\n"
  8317. "value1\r\n"
  8318. "--simple boundary\r\n"
  8319. "Content-Disposition: form-data; name=\"field2\"; "
  8320. "filename=\"example.txt\"\r\n"
  8321. "\r\n"
  8322. "value2\r\n"
  8323. "--simple boundary--\r\n"
  8324. "This is the epilogue. It is also to be ignored.\r\n";
  8325. std::string content_type =
  8326. R"(multipart/form-data; boundary="simple boundary")";
  8327. Client cli(HOST, PORT);
  8328. auto res = cli.Post("/post", body, content_type.c_str());
  8329. ASSERT_TRUE(res);
  8330. EXPECT_EQ(StatusCode::OK_200, res->status);
  8331. }
  8332. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8335. const ContentReader &content_reader) {
  8336. if (req.is_multipart_form_data()) {
  8337. std::vector<FormData> items;
  8338. content_reader(
  8339. [&](const FormData &file) {
  8340. items.push_back(file);
  8341. return true;
  8342. },
  8343. [&](const char *data, size_t data_length) {
  8344. items.back().content.append(data, data_length);
  8345. return true;
  8346. });
  8347. EXPECT_TRUE(std::string(items[0].name) == "document");
  8348. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8349. EXPECT_TRUE(items[0].filename == "2MB_data");
  8350. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8351. EXPECT_TRUE(items[1].name == "hello");
  8352. EXPECT_TRUE(items[1].content == "world");
  8353. EXPECT_TRUE(items[1].filename == "");
  8354. EXPECT_TRUE(items[1].content_type == "");
  8355. } else {
  8356. std::string body;
  8357. content_reader([&](const char *data, size_t data_length) {
  8358. body.append(data, data_length);
  8359. return true;
  8360. });
  8361. }
  8362. });
  8363. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8364. auto se = detail::scope_exit([&] {
  8365. svr.stop();
  8366. t.join();
  8367. ASSERT_FALSE(svr.is_running());
  8368. });
  8369. svr.wait_until_ready();
  8370. {
  8371. std::string data(1024 * 1024 * 2, '.');
  8372. std::stringstream buffer;
  8373. buffer << data;
  8374. Client cli("https://localhost:8080");
  8375. cli.enable_server_certificate_verification(false);
  8376. UploadFormDataItems items{
  8377. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8378. {"hello", "world", "", ""},
  8379. };
  8380. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8381. ASSERT_TRUE(res);
  8382. ASSERT_EQ(StatusCode::OK_200, res->status);
  8383. }
  8384. }
  8385. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8386. std::string data(1024 * 1024 * 2, '&');
  8387. std::stringstream buffer;
  8388. buffer << data;
  8389. Client cli("https://localhost:8080");
  8390. UploadFormDataItems items{
  8391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8392. {"hello", "world", "", ""},
  8393. };
  8394. for (const char &c : " \t\r\n") {
  8395. auto res =
  8396. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8397. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8398. ASSERT_FALSE(res);
  8399. }
  8400. }
  8401. TEST(MultipartFormDataTest, PutFormData) {
  8402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8403. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8404. const ContentReader &content_reader) {
  8405. if (req.is_multipart_form_data()) {
  8406. std::vector<FormData> items;
  8407. content_reader(
  8408. [&](const FormData &file) {
  8409. items.push_back(file);
  8410. return true;
  8411. },
  8412. [&](const char *data, size_t data_length) {
  8413. items.back().content.append(data, data_length);
  8414. return true;
  8415. });
  8416. EXPECT_TRUE(std::string(items[0].name) == "document");
  8417. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8418. EXPECT_TRUE(items[0].filename == "2MB_data");
  8419. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8420. EXPECT_TRUE(items[1].name == "hello");
  8421. EXPECT_TRUE(items[1].content == "world");
  8422. EXPECT_TRUE(items[1].filename == "");
  8423. EXPECT_TRUE(items[1].content_type == "");
  8424. } else {
  8425. std::string body;
  8426. content_reader([&](const char *data, size_t data_length) {
  8427. body.append(data, data_length);
  8428. return true;
  8429. });
  8430. }
  8431. });
  8432. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8433. auto se = detail::scope_exit([&] {
  8434. svr.stop();
  8435. t.join();
  8436. ASSERT_FALSE(svr.is_running());
  8437. });
  8438. svr.wait_until_ready();
  8439. {
  8440. std::string data(1024 * 1024 * 2, '&');
  8441. std::stringstream buffer;
  8442. buffer << data;
  8443. Client cli("https://localhost:8080");
  8444. cli.enable_server_certificate_verification(false);
  8445. UploadFormDataItems items{
  8446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8447. {"hello", "world", "", ""},
  8448. };
  8449. auto res = cli.Put("/put", items);
  8450. ASSERT_TRUE(res);
  8451. ASSERT_EQ(StatusCode::OK_200, res->status);
  8452. }
  8453. }
  8454. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8456. svr.Put("/put_customboundary",
  8457. [&](const Request &req, const Response & /*res*/,
  8458. const ContentReader &content_reader) {
  8459. if (req.is_multipart_form_data()) {
  8460. std::vector<FormData> items;
  8461. content_reader(
  8462. [&](const FormData &file) {
  8463. items.push_back(file);
  8464. return true;
  8465. },
  8466. [&](const char *data, size_t data_length) {
  8467. items.back().content.append(data, data_length);
  8468. return true;
  8469. });
  8470. EXPECT_TRUE(std::string(items[0].name) == "document");
  8471. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8472. EXPECT_TRUE(items[0].filename == "2MB_data");
  8473. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8474. EXPECT_TRUE(items[1].name == "hello");
  8475. EXPECT_TRUE(items[1].content == "world");
  8476. EXPECT_TRUE(items[1].filename == "");
  8477. EXPECT_TRUE(items[1].content_type == "");
  8478. } else {
  8479. std::string body;
  8480. content_reader([&](const char *data, size_t data_length) {
  8481. body.append(data, data_length);
  8482. return true;
  8483. });
  8484. }
  8485. });
  8486. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8487. auto se = detail::scope_exit([&] {
  8488. svr.stop();
  8489. t.join();
  8490. ASSERT_FALSE(svr.is_running());
  8491. });
  8492. svr.wait_until_ready();
  8493. {
  8494. std::string data(1024 * 1024 * 2, '&');
  8495. std::stringstream buffer;
  8496. buffer << data;
  8497. Client cli("https://localhost:8080");
  8498. cli.enable_server_certificate_verification(false);
  8499. UploadFormDataItems items{
  8500. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8501. {"hello", "world", "", ""},
  8502. };
  8503. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8504. ASSERT_TRUE(res);
  8505. ASSERT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. }
  8508. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8509. std::string data(1024 * 1024 * 2, '&');
  8510. std::stringstream buffer;
  8511. buffer << data;
  8512. Client cli("https://localhost:8080");
  8513. cli.enable_server_certificate_verification(false);
  8514. UploadFormDataItems items{
  8515. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8516. {"hello", "world", "", ""},
  8517. };
  8518. for (const char &c : " \t\r\n") {
  8519. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8520. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8521. ASSERT_FALSE(res);
  8522. }
  8523. }
  8524. TEST(MultipartFormDataTest, AlternateFilename) {
  8525. auto handled = false;
  8526. Server svr;
  8527. svr.Post("/test", [&](const Request &req, Response &res) {
  8528. ASSERT_EQ(2u, req.form.files.size());
  8529. ASSERT_EQ(1u, req.form.fields.size());
  8530. // Test files
  8531. const auto &file1 = req.form.get_file("file1");
  8532. ASSERT_EQ("file1", file1.name);
  8533. ASSERT_EQ("A.txt", file1.filename);
  8534. ASSERT_EQ("text/plain", file1.content_type);
  8535. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8536. const auto &file2 = req.form.get_file("file2");
  8537. ASSERT_EQ("file2", file2.name);
  8538. ASSERT_EQ("a.html", file2.filename);
  8539. ASSERT_EQ("text/html", file2.content_type);
  8540. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8541. file2.content);
  8542. // Test text field
  8543. const auto &text = req.form.get_field("text");
  8544. ASSERT_EQ("text default", text);
  8545. res.set_content("ok", "text/plain");
  8546. handled = true;
  8547. });
  8548. thread t = thread([&] { svr.listen(HOST, PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. t.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. ASSERT_TRUE(handled);
  8554. });
  8555. svr.wait_until_ready();
  8556. auto req = "POST /test HTTP/1.1\r\n"
  8557. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8558. "Content-Length: 399\r\n"
  8559. "\r\n"
  8560. "----------\r\n"
  8561. "Content-Disposition: form-data; name=\"text\"\r\n"
  8562. "\r\n"
  8563. "text default\r\n"
  8564. "----------\r\n"
  8565. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8566. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8567. "Content-Type: text/plain\r\n"
  8568. "\r\n"
  8569. "Content of a.txt.\r\n"
  8570. "\r\n"
  8571. "----------\r\n"
  8572. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8573. "\"a.html\"\r\n"
  8574. "Content-Type: text/html\r\n"
  8575. "\r\n"
  8576. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8577. "\r\n"
  8578. "------------\r\n";
  8579. ASSERT_TRUE(send_request(1, req));
  8580. }
  8581. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8582. auto handled = false;
  8583. Server svr;
  8584. svr.Post("/test", [&](const Request &req, Response &) {
  8585. ASSERT_EQ(2u, req.form.fields.size());
  8586. const auto &text1 = req.form.get_field("text1");
  8587. ASSERT_EQ("text1", text1);
  8588. const auto &text2 = req.form.get_field("text2");
  8589. ASSERT_EQ("text2", text2);
  8590. handled = true;
  8591. });
  8592. thread t = thread([&] { svr.listen(HOST, PORT); });
  8593. auto se = detail::scope_exit([&] {
  8594. svr.stop();
  8595. t.join();
  8596. ASSERT_FALSE(svr.is_running());
  8597. ASSERT_TRUE(handled);
  8598. });
  8599. svr.wait_until_ready();
  8600. auto req = "POST /test HTTP/1.1\r\n"
  8601. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8602. "Content-Length: 146\r\n"
  8603. "\r\n----------\r\n"
  8604. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8605. "\r\n"
  8606. "text1"
  8607. "\r\n----------\r\n"
  8608. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8609. "\r\n"
  8610. "text2"
  8611. "\r\n------------";
  8612. std::string response;
  8613. ASSERT_TRUE(send_request(1, req, &response));
  8614. ASSERT_EQ("200", response.substr(9, 3));
  8615. }
  8616. TEST(MultipartFormDataTest, ContentLength) {
  8617. auto handled = false;
  8618. Server svr;
  8619. svr.Post("/test", [&](const Request &req, Response &) {
  8620. ASSERT_EQ(2u, req.form.fields.size());
  8621. const auto &text1 = req.form.get_field("text1");
  8622. ASSERT_EQ("text1", text1);
  8623. const auto &text2 = req.form.get_field("text2");
  8624. ASSERT_EQ("text2", text2);
  8625. handled = true;
  8626. });
  8627. thread t = thread([&] { svr.listen(HOST, PORT); });
  8628. auto se = detail::scope_exit([&] {
  8629. svr.stop();
  8630. t.join();
  8631. ASSERT_FALSE(svr.is_running());
  8632. ASSERT_TRUE(handled);
  8633. });
  8634. svr.wait_until_ready();
  8635. auto req = "POST /test HTTP/1.1\r\n"
  8636. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8637. "Content-Length: 167\r\n"
  8638. "\r\n----------\r\n"
  8639. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8640. "Content-Length: 5\r\n"
  8641. "\r\n"
  8642. "text1"
  8643. "\r\n----------\r\n"
  8644. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8645. "\r\n"
  8646. "text2"
  8647. "\r\n------------\r\n";
  8648. std::string response;
  8649. ASSERT_TRUE(send_request(1, req, &response));
  8650. ASSERT_EQ("200", response.substr(9, 3));
  8651. }
  8652. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8653. auto handled = false;
  8654. Server svr;
  8655. svr.Post("/test", [&](const Request &req, Response &) {
  8656. ASSERT_EQ(2u, req.form.fields.size());
  8657. const auto &text1 = req.form.get_field("text1");
  8658. ASSERT_EQ("text1", text1);
  8659. // TODO: Add header access for text fields if needed
  8660. const auto &text2 = req.form.get_field("text2");
  8661. ASSERT_EQ("text2", text2);
  8662. // TODO: Header access for text fields needs to be implemented
  8663. // auto &headers = it->second.headers;
  8664. // ASSERT_EQ(3U, headers.size());
  8665. // auto custom_header = headers.find("x-whatever");
  8666. // ASSERT_TRUE(custom_header != headers.end());
  8667. // ASSERT_NE("customvalue", custom_header->second);
  8668. // ASSERT_EQ("CustomValue", custom_header->second);
  8669. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8670. handled = true;
  8671. });
  8672. thread t = thread([&] { svr.listen(HOST, PORT); });
  8673. auto se = detail::scope_exit([&] {
  8674. svr.stop();
  8675. t.join();
  8676. ASSERT_FALSE(svr.is_running());
  8677. ASSERT_TRUE(handled);
  8678. });
  8679. svr.wait_until_ready();
  8680. auto req = "POST /test HTTP/1.1\r\n"
  8681. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8682. "Content-Length: 232\r\n"
  8683. "\r\n----------\r\n"
  8684. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8685. "Content-Length: 5\r\n"
  8686. "X-Test: 1\r\n"
  8687. "\r\n"
  8688. "text1"
  8689. "\r\n----------\r\n"
  8690. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8691. "Content-Type: text/plain\r\n"
  8692. "X-Whatever: CustomValue\r\n"
  8693. "\r\n"
  8694. "text2"
  8695. "\r\n------------\r\n"
  8696. "That should be disregarded. Not even read";
  8697. std::string response;
  8698. ASSERT_TRUE(send_request(1, req, &response));
  8699. ASSERT_EQ("200", response.substr(9, 3));
  8700. }
  8701. #endif
  8702. TEST(MultipartFormDataTest, LargeHeader) {
  8703. auto handled = false;
  8704. Server svr;
  8705. svr.Post("/test", [&](const Request &req, Response &) {
  8706. ASSERT_EQ(1u, req.form.fields.size());
  8707. const auto &text = req.form.get_field("name1");
  8708. ASSERT_EQ("text1", text);
  8709. handled = true;
  8710. });
  8711. thread t = thread([&] { svr.listen(HOST, PORT); });
  8712. auto se = detail::scope_exit([&] {
  8713. svr.stop();
  8714. t.join();
  8715. ASSERT_FALSE(svr.is_running());
  8716. ASSERT_TRUE(handled);
  8717. });
  8718. svr.wait_until_ready();
  8719. auto boundary = std::string("cpp-httplib-multipart-data");
  8720. std::string content = "--" + boundary +
  8721. "\r\n"
  8722. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8723. "\r\n"
  8724. "text1\r\n"
  8725. "--" +
  8726. boundary + "--\r\n";
  8727. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8728. "Content-Type: multipart/form-data;boundary=" +
  8729. boundary +
  8730. "\r\n"
  8731. "Content-Length: " +
  8732. std::to_string(content.size()) +
  8733. "\r\n"
  8734. "Dummy-Header: ";
  8735. std::string header_suffix = "\r\n"
  8736. "\r\n";
  8737. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8738. size_t header_dummy_size =
  8739. read_buff_size -
  8740. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8741. auto header_dummy = std::string(header_dummy_size, '@');
  8742. auto req = header_prefix + header_dummy + header_suffix + content;
  8743. std::string response;
  8744. ASSERT_TRUE(send_request(1, req, &response));
  8745. ASSERT_EQ("200", response.substr(9, 3));
  8746. }
  8747. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8748. static constexpr unsigned int number_of_tasks{1000000};
  8749. std::atomic_uint count{0};
  8750. std::unique_ptr<TaskQueue> task_queue{
  8751. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8752. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8753. auto queued = task_queue->enqueue(
  8754. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8755. EXPECT_TRUE(queued);
  8756. }
  8757. EXPECT_NO_THROW(task_queue->shutdown());
  8758. EXPECT_EQ(number_of_tasks, count.load());
  8759. }
  8760. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8761. static constexpr unsigned int number_of_tasks{1000000};
  8762. static constexpr unsigned int qlimit{2};
  8763. unsigned int queued_count{0};
  8764. std::atomic_uint count{0};
  8765. std::unique_ptr<TaskQueue> task_queue{
  8766. new ThreadPool{/*num_threads=*/1, qlimit}};
  8767. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8768. if (task_queue->enqueue(
  8769. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8770. queued_count++;
  8771. }
  8772. }
  8773. EXPECT_NO_THROW(task_queue->shutdown());
  8774. EXPECT_EQ(queued_count, count.load());
  8775. EXPECT_TRUE(queued_count <= number_of_tasks);
  8776. EXPECT_TRUE(queued_count >= qlimit);
  8777. }
  8778. TEST(TaskQueueTest, MaxQueuedRequests) {
  8779. static constexpr unsigned int qlimit{3};
  8780. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8781. std::condition_variable sem_cv;
  8782. std::mutex sem_mtx;
  8783. int credits = 0;
  8784. bool queued;
  8785. /* Fill up the queue with tasks that will block until we give them credits to
  8786. * complete. */
  8787. for (unsigned int n = 0; n <= qlimit;) {
  8788. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8789. std::unique_lock<std::mutex> lock(sem_mtx);
  8790. while (credits <= 0) {
  8791. sem_cv.wait(lock);
  8792. }
  8793. /* Consume the credit and signal the test code if they are all gone. */
  8794. if (--credits == 0) { sem_cv.notify_one(); }
  8795. });
  8796. if (n < qlimit) {
  8797. /* The first qlimit enqueues must succeed. */
  8798. EXPECT_TRUE(queued);
  8799. } else {
  8800. /* The last one will succeed only when the worker thread
  8801. * starts and dequeues the first blocking task. Although
  8802. * not necessary for the correctness of this test, we sleep for
  8803. * a short while to avoid busy waiting. */
  8804. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8805. }
  8806. if (queued) { n++; }
  8807. }
  8808. /* Further enqueues must fail since the queue is full. */
  8809. for (auto i = 0; i < 4; i++) {
  8810. queued = task_queue->enqueue([] {});
  8811. EXPECT_FALSE(queued);
  8812. }
  8813. /* Give the credits to allow the previous tasks to complete. */
  8814. {
  8815. std::unique_lock<std::mutex> lock(sem_mtx);
  8816. credits += qlimit + 1;
  8817. }
  8818. sem_cv.notify_all();
  8819. /* Wait for all the credits to be consumed. */
  8820. {
  8821. std::unique_lock<std::mutex> lock(sem_mtx);
  8822. while (credits > 0) {
  8823. sem_cv.wait(lock);
  8824. }
  8825. }
  8826. /* Check that we are able again to enqueue at least qlimit tasks. */
  8827. for (unsigned int i = 0; i < qlimit; i++) {
  8828. queued = task_queue->enqueue([] {});
  8829. EXPECT_TRUE(queued);
  8830. }
  8831. EXPECT_NO_THROW(task_queue->shutdown());
  8832. }
  8833. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8834. Server svr;
  8835. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8836. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8837. });
  8838. svr.Get("/hello", [](const Request &req, Response &res) {
  8839. res.set_content(req.get_param_value("key"), "text/plain");
  8840. });
  8841. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. thread.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. {
  8849. Client cli(HOST, PORT);
  8850. cli.set_follow_location(true);
  8851. auto res = cli.Get("/");
  8852. ASSERT_TRUE(res);
  8853. EXPECT_EQ(StatusCode::OK_200, res->status);
  8854. EXPECT_EQ("val&key2=val2", res->body);
  8855. }
  8856. }
  8857. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8858. Server svr;
  8859. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8860. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8861. });
  8862. svr.Get("/hello", [](const Request &req, Response &res) {
  8863. res.set_content(req.get_param_value("key"), "text/plain");
  8864. });
  8865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8866. auto se = detail::scope_exit([&] {
  8867. svr.stop();
  8868. thread.join();
  8869. ASSERT_FALSE(svr.is_running());
  8870. });
  8871. svr.wait_until_ready();
  8872. {
  8873. Client cli(HOST, PORT);
  8874. cli.set_follow_location(true);
  8875. auto res = cli.Get("/");
  8876. ASSERT_TRUE(res);
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8879. }
  8880. }
  8881. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8882. TEST(RedirectTest, Issue2185_Online) {
  8883. SSLClient client("github.com");
  8884. client.set_follow_location(true);
  8885. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8886. "Coollab-Windows.zip");
  8887. ASSERT_TRUE(res);
  8888. EXPECT_EQ(StatusCode::OK_200, res->status);
  8889. EXPECT_EQ(9920427U, res->body.size());
  8890. }
  8891. #endif
  8892. TEST(VulnerabilityTest, CRLFInjection) {
  8893. Server svr;
  8894. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8895. res.set_content("Hello 1", "text/plain");
  8896. });
  8897. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8898. res.set_content("Hello 2", "text/plain");
  8899. });
  8900. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8901. res.set_content("Hello 3", "text/plain");
  8902. });
  8903. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8904. res.set_content("Hello 4", "text/plain");
  8905. });
  8906. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8907. for (const auto &x : req.headers) {
  8908. auto key = x.first;
  8909. EXPECT_STRNE("evil", key.c_str());
  8910. }
  8911. });
  8912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8913. auto se = detail::scope_exit([&] {
  8914. svr.stop();
  8915. thread.join();
  8916. ASSERT_FALSE(svr.is_running());
  8917. });
  8918. svr.wait_until_ready();
  8919. {
  8920. Client cli(HOST, PORT);
  8921. cli.Post("/test1", "A=B",
  8922. "application/x-www-form-urlencoded\r\nevil: hello1");
  8923. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8924. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8925. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8926. }
  8927. }
  8928. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  8929. auto server_thread = std::thread([] {
  8930. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8931. default_socket_options(srv);
  8932. sockaddr_in addr{};
  8933. addr.sin_family = AF_INET;
  8934. addr.sin_port = htons(PORT + 1);
  8935. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8936. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8937. ::listen(srv, 1);
  8938. sockaddr_in cli_addr{};
  8939. socklen_t cli_len = sizeof(cli_addr);
  8940. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8941. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  8942. std::string buf_all;
  8943. char buf[2048];
  8944. ssize_t n;
  8945. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  8946. buf_all.append(buf, static_cast<size_t>(n));
  8947. size_t pos;
  8948. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  8949. auto request_block = buf_all.substr(0, pos + 4); // include separator
  8950. auto e = request_block.find("\r\n");
  8951. if (e != std::string::npos) {
  8952. auto request_line = request_block.substr(0, e);
  8953. std::string msg =
  8954. "CRLF injection detected in request line: '" + request_line + "'";
  8955. EXPECT_FALSE(true) << msg;
  8956. }
  8957. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  8958. ::send(cli, resp.c_str(), resp.size(), 0);
  8959. buf_all.erase(0, pos + 4);
  8960. }
  8961. }
  8962. detail::close_socket(cli);
  8963. detail::close_socket(srv);
  8964. });
  8965. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8966. auto cli = Client("127.0.0.1", PORT + 1);
  8967. auto headers = Headers{
  8968. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  8969. {"Connection", "keep-alive"}};
  8970. auto res = cli.Get("/hi", headers);
  8971. EXPECT_FALSE(res);
  8972. EXPECT_EQ(Error::InvalidHeaders, res.error());
  8973. server_thread.join();
  8974. }
  8975. TEST(PathParamsTest, StaticMatch) {
  8976. const auto pattern = "/users/all";
  8977. detail::PathParamsMatcher matcher(pattern);
  8978. Request request;
  8979. request.path = "/users/all";
  8980. ASSERT_TRUE(matcher.match(request));
  8981. std::unordered_map<std::string, std::string> expected_params = {};
  8982. EXPECT_EQ(request.path_params, expected_params);
  8983. }
  8984. TEST(PathParamsTest, StaticMismatch) {
  8985. const auto pattern = "/users/all";
  8986. detail::PathParamsMatcher matcher(pattern);
  8987. Request request;
  8988. request.path = "/users/1";
  8989. ASSERT_FALSE(matcher.match(request));
  8990. }
  8991. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8992. const auto pattern = "/users/:id/subscriptions";
  8993. detail::PathParamsMatcher matcher(pattern);
  8994. Request request;
  8995. request.path = "/users/42/subscriptions";
  8996. ASSERT_TRUE(matcher.match(request));
  8997. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8998. EXPECT_EQ(request.path_params, expected_params);
  8999. }
  9000. TEST(PathParamsTest, SingleParamInTheEnd) {
  9001. const auto pattern = "/users/:id";
  9002. detail::PathParamsMatcher matcher(pattern);
  9003. Request request;
  9004. request.path = "/users/24";
  9005. ASSERT_TRUE(matcher.match(request));
  9006. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9007. EXPECT_EQ(request.path_params, expected_params);
  9008. }
  9009. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9010. const auto pattern = "/users/:id/";
  9011. detail::PathParamsMatcher matcher(pattern);
  9012. Request request;
  9013. request.path = "/users/42/";
  9014. ASSERT_TRUE(matcher.match(request));
  9015. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9016. EXPECT_EQ(request.path_params, expected_params);
  9017. }
  9018. TEST(PathParamsTest, EmptyParam) {
  9019. const auto pattern = "/users/:id/";
  9020. detail::PathParamsMatcher matcher(pattern);
  9021. Request request;
  9022. request.path = "/users//";
  9023. ASSERT_TRUE(matcher.match(request));
  9024. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9025. EXPECT_EQ(request.path_params, expected_params);
  9026. }
  9027. TEST(PathParamsTest, FragmentMismatch) {
  9028. const auto pattern = "/users/:id/";
  9029. detail::PathParamsMatcher matcher(pattern);
  9030. Request request;
  9031. request.path = "/admins/24/";
  9032. ASSERT_FALSE(matcher.match(request));
  9033. }
  9034. TEST(PathParamsTest, ExtraFragments) {
  9035. const auto pattern = "/users/:id";
  9036. detail::PathParamsMatcher matcher(pattern);
  9037. Request request;
  9038. request.path = "/users/42/subscriptions";
  9039. ASSERT_FALSE(matcher.match(request));
  9040. }
  9041. TEST(PathParamsTest, MissingTrailingParam) {
  9042. const auto pattern = "/users/:id";
  9043. detail::PathParamsMatcher matcher(pattern);
  9044. Request request;
  9045. request.path = "/users";
  9046. ASSERT_FALSE(matcher.match(request));
  9047. }
  9048. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9049. const auto pattern = "/users/:id/subscriptions";
  9050. detail::PathParamsMatcher matcher(pattern);
  9051. Request request;
  9052. request.path = "/users/subscriptions";
  9053. ASSERT_FALSE(matcher.match(request));
  9054. }
  9055. TEST(PathParamsTest, MultipleParams) {
  9056. const auto pattern = "/users/:userid/subscriptions/:subid";
  9057. detail::PathParamsMatcher matcher(pattern);
  9058. Request request;
  9059. request.path = "/users/42/subscriptions/2";
  9060. ASSERT_TRUE(matcher.match(request));
  9061. std::unordered_map<std::string, std::string> expected_params = {
  9062. {"userid", "42"}, {"subid", "2"}};
  9063. EXPECT_EQ(request.path_params, expected_params);
  9064. }
  9065. TEST(PathParamsTest, SequenceOfParams) {
  9066. const auto pattern = "/values/:x/:y/:z";
  9067. detail::PathParamsMatcher matcher(pattern);
  9068. Request request;
  9069. request.path = "/values/1/2/3";
  9070. ASSERT_TRUE(matcher.match(request));
  9071. std::unordered_map<std::string, std::string> expected_params = {
  9072. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9073. EXPECT_EQ(request.path_params, expected_params);
  9074. }
  9075. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9076. const auto pattern = "/prefix:suffix";
  9077. detail::PathParamsMatcher matcher(pattern);
  9078. Request request;
  9079. request.path = "/prefix:suffix";
  9080. ASSERT_TRUE(matcher.match(request));
  9081. const std::unordered_map<std::string, std::string> expected_params = {};
  9082. EXPECT_EQ(request.path_params, expected_params);
  9083. }
  9084. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9085. // If ipv6 regex working, regex match codepath is taken.
  9086. // else port will default to 80 in Client impl
  9087. int clientImplMagicPort = 80;
  9088. int port = 4321;
  9089. // above ports must be different to avoid false negative
  9090. EXPECT_NE(clientImplMagicPort, port);
  9091. std::string ipV6TestURL = "http://[ff06::c3]";
  9092. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9093. CLIENT_PRIVATE_KEY_FILE);
  9094. EXPECT_EQ(cli.port(), port);
  9095. }
  9096. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9097. auto file_path = "./www/dir/index.html";
  9098. auto dir_path = "./www/dir";
  9099. detail::FileStat stat_file(file_path);
  9100. EXPECT_TRUE(stat_file.is_file());
  9101. EXPECT_FALSE(stat_file.is_dir());
  9102. detail::FileStat stat_dir(dir_path);
  9103. EXPECT_FALSE(stat_dir.is_file());
  9104. EXPECT_TRUE(stat_dir.is_dir());
  9105. }
  9106. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9107. // IPv4 with default HTTP port (80)
  9108. EXPECT_EQ("example.com",
  9109. detail::make_host_and_port_string("example.com", 80, false));
  9110. // IPv4 with default HTTPS port (443)
  9111. EXPECT_EQ("example.com",
  9112. detail::make_host_and_port_string("example.com", 443, true));
  9113. // IPv4 with non-default HTTP port
  9114. EXPECT_EQ("example.com:8080",
  9115. detail::make_host_and_port_string("example.com", 8080, false));
  9116. // IPv4 with non-default HTTPS port
  9117. EXPECT_EQ("example.com:8443",
  9118. detail::make_host_and_port_string("example.com", 8443, true));
  9119. // IPv6 with default HTTP port (80)
  9120. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9121. // IPv6 with default HTTPS port (443)
  9122. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9123. // IPv6 with non-default HTTP port
  9124. EXPECT_EQ("[::1]:8080",
  9125. detail::make_host_and_port_string("::1", 8080, false));
  9126. // IPv6 with non-default HTTPS port
  9127. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9128. // IPv6 full address with default port
  9129. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9130. detail::make_host_and_port_string(
  9131. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9132. // IPv6 full address with non-default port
  9133. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9134. detail::make_host_and_port_string(
  9135. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9136. // IPv6 localhost with non-default port
  9137. EXPECT_EQ("[::1]:3000",
  9138. detail::make_host_and_port_string("::1", 3000, false));
  9139. // IPv6 with zone ID (link-local address) with default port
  9140. EXPECT_EQ("[fe80::1%eth0]",
  9141. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9142. // IPv6 with zone ID (link-local address) with non-default port
  9143. EXPECT_EQ("[fe80::1%eth0]:8080",
  9144. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9145. // Edge case: Port 443 with is_ssl=false (should add port)
  9146. EXPECT_EQ("example.com:443",
  9147. detail::make_host_and_port_string("example.com", 443, false));
  9148. // Edge case: Port 80 with is_ssl=true (should add port)
  9149. EXPECT_EQ("example.com:80",
  9150. detail::make_host_and_port_string("example.com", 80, true));
  9151. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9152. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9153. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9154. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9155. // Security fix: Already bracketed IPv6 should not get double brackets
  9156. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9157. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9158. EXPECT_EQ("[::1]:8080",
  9159. detail::make_host_and_port_string("[::1]", 8080, false));
  9160. EXPECT_EQ("[2001:db8::1]:8080",
  9161. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9162. EXPECT_EQ("[fe80::1%eth0]",
  9163. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9164. EXPECT_EQ("[fe80::1%eth0]:8080",
  9165. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9166. // Edge case: Empty host (should return as-is)
  9167. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9168. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9169. // This is a known limitation but shouldn't crash
  9170. EXPECT_EQ("[host:name]",
  9171. detail::make_host_and_port_string("host:name", 80, false));
  9172. // Port number edge cases (no validation, but should not crash)
  9173. EXPECT_EQ("example.com:0",
  9174. detail::make_host_and_port_string("example.com", 0, false));
  9175. EXPECT_EQ("example.com:-1",
  9176. detail::make_host_and_port_string("example.com", -1, false));
  9177. EXPECT_EQ("example.com:65535",
  9178. detail::make_host_and_port_string("example.com", 65535, false));
  9179. EXPECT_EQ("example.com:65536",
  9180. detail::make_host_and_port_string("example.com", 65536, false));
  9181. }
  9182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9183. TEST(SSLClientHostHeaderTest, Issue2301) {
  9184. httplib::SSLClient cli("roblox.com", 443);
  9185. cli.set_follow_location(true);
  9186. auto res = cli.Get("/");
  9187. ASSERT_TRUE(res);
  9188. EXPECT_EQ(StatusCode::OK_200, res->status);
  9189. }
  9190. #endif
  9191. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9192. Server svr;
  9193. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9194. EXPECT_EQ(res.status, 400);
  9195. });
  9196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9197. auto se = detail::scope_exit([&] {
  9198. svr.stop();
  9199. thread.join();
  9200. ASSERT_FALSE(svr.is_running());
  9201. });
  9202. svr.wait_until_ready();
  9203. Client cli(HOST, PORT);
  9204. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9205. }
  9206. TEST(InvalidHeaderCharsTest, is_field_name) {
  9207. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9208. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9209. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9210. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9211. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9212. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9213. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9214. EXPECT_FALSE(detail::fields::is_field_name(""));
  9215. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9216. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9217. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9218. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9219. }
  9220. TEST(InvalidHeaderCharsTest, is_field_value) {
  9221. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9222. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9223. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9224. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9225. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9226. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9227. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9228. EXPECT_TRUE(detail::fields::is_field_value(""));
  9229. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9230. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9231. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9232. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9233. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9234. }
  9235. TEST(InvalidHeaderCharsTest, OnServer) {
  9236. Server svr;
  9237. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9238. std::string header = "Not Set";
  9239. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9240. res.set_header(header, "value");
  9241. res.set_content("Page Content Page Content", "text/plain");
  9242. });
  9243. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9244. std::string header = "Not Set";
  9245. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9246. res.set_header("X-Test", header);
  9247. res.set_content("Page Content Page Content", "text/plain");
  9248. });
  9249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9250. auto se = detail::scope_exit([&] {
  9251. svr.stop();
  9252. thread.join();
  9253. ASSERT_FALSE(svr.is_running());
  9254. });
  9255. svr.wait_until_ready();
  9256. Client cli(HOST, PORT);
  9257. {
  9258. auto res = cli.Get(
  9259. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9260. ASSERT_TRUE(res);
  9261. EXPECT_EQ("Page Content Page Content", res->body);
  9262. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9263. }
  9264. {
  9265. auto res = cli.Get(
  9266. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9267. ASSERT_TRUE(res);
  9268. EXPECT_EQ("Page Content Page Content", res->body);
  9269. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9270. }
  9271. }
  9272. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9273. auto handled = false;
  9274. Server svr;
  9275. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9276. thread t = thread([&] { svr.listen(HOST, PORT); });
  9277. auto se = detail::scope_exit([&] {
  9278. svr.stop();
  9279. t.join();
  9280. ASSERT_FALSE(svr.is_running());
  9281. ASSERT_FALSE(handled);
  9282. });
  9283. svr.wait_until_ready();
  9284. auto req = "POST /test HTTP/1.1\r\n"
  9285. "Content-Length: x\r\n"
  9286. "\r\n";
  9287. std::string response;
  9288. ASSERT_TRUE(send_request(1, req, &response));
  9289. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9290. response.substr(0, response.find("\r\n")));
  9291. }
  9292. #ifndef _WIN32
  9293. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9294. static constexpr char reject[] = "Unauthorized";
  9295. static constexpr char accept[] = "Upload accepted";
  9296. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9297. Server svr;
  9298. svr.set_expect_100_continue_handler(
  9299. [](const Request & /*req*/, Response &res) {
  9300. res.status = StatusCode::Unauthorized_401;
  9301. res.set_content(reject, "text/plain");
  9302. return res.status;
  9303. });
  9304. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9305. res.set_content(accept, "text/plain");
  9306. });
  9307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9308. auto se = detail::scope_exit([&] {
  9309. svr.stop();
  9310. thread.join();
  9311. ASSERT_FALSE(svr.is_running());
  9312. });
  9313. svr.wait_until_ready();
  9314. {
  9315. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9316. curl_easy_init(), &curl_easy_cleanup};
  9317. ASSERT_NE(curl, nullptr);
  9318. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9319. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9320. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9321. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9322. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9323. &curl_slist_free_all};
  9324. ASSERT_NE(list, nullptr);
  9325. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9326. struct read_data {
  9327. size_t read_size;
  9328. size_t total_size;
  9329. } data = {0, total_size};
  9330. using read_callback_t =
  9331. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9332. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9333. void *userdata) -> size_t {
  9334. read_data *data = (read_data *)userdata;
  9335. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9336. std::fill_n(ptr, size * nmemb, 'A');
  9337. data->read_size += size * nmemb;
  9338. return size * nmemb;
  9339. };
  9340. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9341. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9342. std::vector<char> buffer;
  9343. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9344. using write_callback_t =
  9345. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9346. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9347. void *userdata) -> size_t {
  9348. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9349. buffer->reserve(buffer->size() + size * nmemb + 1);
  9350. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9351. return size * nmemb;
  9352. };
  9353. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9354. {
  9355. const auto res = curl_easy_perform(curl.get());
  9356. ASSERT_EQ(res, CURLE_OK);
  9357. }
  9358. {
  9359. auto response_code = long{};
  9360. const auto res =
  9361. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9362. ASSERT_EQ(res, CURLE_OK);
  9363. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9364. }
  9365. {
  9366. auto dl = curl_off_t{};
  9367. const auto res =
  9368. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9369. ASSERT_EQ(res, CURLE_OK);
  9370. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9371. }
  9372. {
  9373. buffer.push_back('\0');
  9374. ASSERT_STRCASEEQ(buffer.data(), reject);
  9375. }
  9376. }
  9377. }
  9378. #endif
  9379. template <typename S, typename C>
  9380. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9381. svr.Get("/stream", [&](const Request &, Response &res) {
  9382. auto data = new std::string("01234567890123456789");
  9383. res.set_content_provider(
  9384. data->size(), "text/plain",
  9385. [&, data](size_t offset, size_t length, DataSink &sink) {
  9386. const size_t DATA_CHUNK_SIZE = 4;
  9387. const auto &d = *data;
  9388. std::this_thread::sleep_for(std::chrono::seconds(1));
  9389. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9390. return true;
  9391. },
  9392. [data](bool success) {
  9393. EXPECT_FALSE(success);
  9394. delete data;
  9395. });
  9396. });
  9397. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9398. auto i = new size_t(0);
  9399. res.set_content_provider(
  9400. "text/plain",
  9401. [i](size_t, DataSink &sink) {
  9402. if (*i < 5) {
  9403. std::this_thread::sleep_for(std::chrono::seconds(1));
  9404. sink.write("abcd", 4);
  9405. (*i)++;
  9406. } else {
  9407. sink.done();
  9408. }
  9409. return true;
  9410. },
  9411. [i](bool success) {
  9412. EXPECT_FALSE(success);
  9413. delete i;
  9414. });
  9415. });
  9416. svr.Get("/chunked", [&](const Request &, Response &res) {
  9417. auto i = new size_t(0);
  9418. res.set_chunked_content_provider(
  9419. "text/plain",
  9420. [i](size_t, DataSink &sink) {
  9421. if (*i < 5) {
  9422. std::this_thread::sleep_for(std::chrono::seconds(1));
  9423. sink.os << "abcd";
  9424. (*i)++;
  9425. } else {
  9426. sink.done();
  9427. }
  9428. return true;
  9429. },
  9430. [i](bool success) {
  9431. EXPECT_FALSE(success);
  9432. delete i;
  9433. });
  9434. });
  9435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9436. auto se = detail::scope_exit([&] {
  9437. svr.stop();
  9438. listen_thread.join();
  9439. ASSERT_FALSE(svr.is_running());
  9440. });
  9441. svr.wait_until_ready();
  9442. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9443. {
  9444. auto start = std::chrono::steady_clock::now();
  9445. auto res = cli.Get("/stream");
  9446. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9447. std::chrono::steady_clock::now() - start)
  9448. .count();
  9449. ASSERT_FALSE(res);
  9450. EXPECT_EQ(Error::Read, res.error());
  9451. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9452. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9453. }
  9454. {
  9455. auto start = std::chrono::steady_clock::now();
  9456. auto res = cli.Get("/stream_without_length");
  9457. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9458. std::chrono::steady_clock::now() - start)
  9459. .count();
  9460. ASSERT_FALSE(res);
  9461. EXPECT_EQ(Error::Read, res.error());
  9462. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9463. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9464. }
  9465. {
  9466. auto start = std::chrono::steady_clock::now();
  9467. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9468. EXPECT_EQ("abcd", string(data, data_length));
  9469. return true;
  9470. });
  9471. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9472. std::chrono::steady_clock::now() - start)
  9473. .count();
  9474. ASSERT_FALSE(res);
  9475. EXPECT_EQ(Error::Read, res.error());
  9476. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9477. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9478. }
  9479. }
  9480. TEST(MaxTimeoutTest, ContentStream) {
  9481. time_t timeout = 2000;
  9482. time_t threshold = 200;
  9483. Server svr;
  9484. Client cli("localhost", PORT);
  9485. max_timeout_test(svr, cli, timeout, threshold);
  9486. }
  9487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9488. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9489. time_t timeout = 2000;
  9490. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9491. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9492. SSLClient cli("localhost", PORT);
  9493. cli.enable_server_certificate_verification(false);
  9494. max_timeout_test(svr, cli, timeout, threshold);
  9495. }
  9496. #endif
  9497. class EventDispatcher {
  9498. public:
  9499. EventDispatcher() {}
  9500. bool wait_event(DataSink *sink) {
  9501. unique_lock<mutex> lk(m_);
  9502. int id = id_;
  9503. // Wait with timeout to prevent hanging if client disconnects
  9504. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9505. [&] { return cid_ == id; })) {
  9506. return false; // Timeout occurred
  9507. }
  9508. sink->write(message_.data(), message_.size());
  9509. return true;
  9510. }
  9511. void send_event(const string &message) {
  9512. lock_guard<mutex> lk(m_);
  9513. cid_ = id_++;
  9514. message_ = message;
  9515. cv_.notify_all();
  9516. }
  9517. private:
  9518. mutex m_;
  9519. condition_variable cv_;
  9520. atomic_int id_{0};
  9521. atomic_int cid_{-1};
  9522. string message_;
  9523. };
  9524. TEST(ClientInThreadTest, Issue2068) {
  9525. EventDispatcher ed;
  9526. Server svr;
  9527. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9528. res.set_chunked_content_provider("text/event-stream",
  9529. [&](size_t /*offset*/, DataSink &sink) {
  9530. return ed.wait_event(&sink);
  9531. });
  9532. });
  9533. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9534. svr.wait_until_ready();
  9535. thread event_thread([&] {
  9536. int id = 0;
  9537. while (svr.is_running()) {
  9538. this_thread::sleep_for(chrono::milliseconds(500));
  9539. std::stringstream ss;
  9540. ss << "data: " << id << "\n\n";
  9541. ed.send_event(ss.str());
  9542. id++;
  9543. }
  9544. });
  9545. auto se = detail::scope_exit([&] {
  9546. svr.stop();
  9547. listen_thread.join();
  9548. event_thread.join();
  9549. ASSERT_FALSE(svr.is_running());
  9550. });
  9551. {
  9552. auto client = detail::make_unique<Client>(HOST, PORT);
  9553. client->set_read_timeout(std::chrono::minutes(10));
  9554. std::atomic<bool> stop{false};
  9555. std::thread t([&] {
  9556. client->Get("/event1",
  9557. [&](const char *, size_t) -> bool { return !stop; });
  9558. });
  9559. std::this_thread::sleep_for(std::chrono::seconds(2));
  9560. stop = true;
  9561. client->stop();
  9562. t.join();
  9563. // Reset client after thread has finished
  9564. client.reset();
  9565. }
  9566. }
  9567. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9568. Server svr;
  9569. svr.Get("/", [](const Request &req, Response &res) {
  9570. EXPECT_EQ(2U, req.trailers.size());
  9571. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9572. // Denied
  9573. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9574. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9575. // Accepted
  9576. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9577. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9578. EXPECT_TRUE(req.has_trailer("X-World"));
  9579. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9580. res.set_content("ok", "text/plain");
  9581. });
  9582. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9583. auto se = detail::scope_exit([&] {
  9584. svr.stop();
  9585. t.join();
  9586. ASSERT_FALSE(svr.is_running());
  9587. });
  9588. svr.wait_until_ready();
  9589. const std::string req = "GET / HTTP/1.1\r\n"
  9590. "Transfer-Encoding: chunked\r\n"
  9591. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9592. "\r\n"
  9593. "0\r\n"
  9594. "Content-Length: 10\r\n"
  9595. "Host: internal.local\r\n"
  9596. "Content-Type: malicious/content\r\n"
  9597. "Cookie: any\r\n"
  9598. "Set-Cookie: any\r\n"
  9599. "X-Forwarded-For: attacker.com\r\n"
  9600. "X-Real-Ip: 1.1.1.1\r\n"
  9601. "X-Hello: hello\r\n"
  9602. "X-World: world\r\n"
  9603. "\r\n";
  9604. std::string res;
  9605. ASSERT_TRUE(send_request(1, req, &res));
  9606. }
  9607. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9608. Server svr;
  9609. std::string observed_remote_addr;
  9610. std::string observed_xff;
  9611. svr.Get("/ip", [&](const Request &req, Response &res) {
  9612. observed_remote_addr = req.remote_addr;
  9613. observed_xff = req.get_header_value("X-Forwarded-For");
  9614. res.set_content("ok", "text/plain");
  9615. });
  9616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop();
  9619. t.join();
  9620. ASSERT_FALSE(svr.is_running());
  9621. });
  9622. svr.wait_until_ready();
  9623. Client cli(HOST, PORT);
  9624. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9625. ASSERT_TRUE(res);
  9626. EXPECT_EQ(StatusCode::OK_200, res->status);
  9627. EXPECT_EQ(observed_xff, "203.0.113.66");
  9628. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9629. observed_remote_addr == "127.0.0.1");
  9630. }
  9631. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9632. Server svr;
  9633. svr.set_trusted_proxies({"203.0.113.66"});
  9634. std::string observed_remote_addr;
  9635. std::string observed_xff;
  9636. svr.Get("/ip", [&](const Request &req, Response &res) {
  9637. observed_remote_addr = req.remote_addr;
  9638. observed_xff = req.get_header_value("X-Forwarded-For");
  9639. res.set_content("ok", "text/plain");
  9640. });
  9641. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9642. auto se = detail::scope_exit([&] {
  9643. svr.stop();
  9644. t.join();
  9645. ASSERT_FALSE(svr.is_running());
  9646. });
  9647. svr.wait_until_ready();
  9648. Client cli(HOST, PORT);
  9649. auto res = cli.Get("/ip");
  9650. ASSERT_TRUE(res);
  9651. EXPECT_EQ(StatusCode::OK_200, res->status);
  9652. EXPECT_EQ(observed_xff, "");
  9653. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9654. observed_remote_addr == "127.0.0.1");
  9655. }
  9656. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9657. Server svr;
  9658. svr.set_trusted_proxies({"203.0.113.66"});
  9659. std::string observed_remote_addr;
  9660. std::string observed_xff;
  9661. svr.Get("/ip", [&](const Request &req, Response &res) {
  9662. observed_remote_addr = req.remote_addr;
  9663. observed_xff = req.get_header_value("X-Forwarded-For");
  9664. res.set_content("ok", "text/plain");
  9665. });
  9666. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. t.join();
  9670. ASSERT_FALSE(svr.is_running());
  9671. });
  9672. svr.wait_until_ready();
  9673. Client cli(HOST, PORT);
  9674. auto res =
  9675. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9676. ASSERT_TRUE(res);
  9677. EXPECT_EQ(StatusCode::OK_200, res->status);
  9678. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9679. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9680. }
  9681. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9682. Server svr;
  9683. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9684. std::string observed_remote_addr;
  9685. std::string observed_xff;
  9686. svr.Get("/ip", [&](const Request &req, Response &res) {
  9687. observed_remote_addr = req.remote_addr;
  9688. observed_xff = req.get_header_value("X-Forwarded-For");
  9689. res.set_content("ok", "text/plain");
  9690. });
  9691. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9692. auto se = detail::scope_exit([&] {
  9693. svr.stop();
  9694. t.join();
  9695. ASSERT_FALSE(svr.is_running());
  9696. });
  9697. svr.wait_until_ready();
  9698. Client cli(HOST, PORT);
  9699. auto res = cli.Get(
  9700. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9701. ASSERT_TRUE(res);
  9702. EXPECT_EQ(StatusCode::OK_200, res->status);
  9703. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9704. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9705. }
  9706. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9707. Server svr;
  9708. svr.set_trusted_proxies({"192.0.2.45"});
  9709. std::string observed_remote_addr;
  9710. std::string observed_xff;
  9711. svr.Get("/ip", [&](const Request &req, Response &res) {
  9712. observed_remote_addr = req.remote_addr;
  9713. observed_xff = req.get_header_value("X-Forwarded-For");
  9714. res.set_content("ok", "text/plain");
  9715. });
  9716. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9717. auto se = detail::scope_exit([&] {
  9718. svr.stop();
  9719. t.join();
  9720. ASSERT_FALSE(svr.is_running());
  9721. });
  9722. svr.wait_until_ready();
  9723. Client cli(HOST, PORT);
  9724. auto res =
  9725. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9726. ASSERT_TRUE(res);
  9727. EXPECT_EQ(StatusCode::OK_200, res->status);
  9728. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9729. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9730. }
  9731. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9732. Server svr;
  9733. svr.set_trusted_proxies({"192.0.2.45"});
  9734. std::string observed_remote_addr;
  9735. std::string observed_xff;
  9736. svr.Get("/ip", [&](const Request &req, Response &res) {
  9737. observed_remote_addr = req.remote_addr;
  9738. observed_xff = req.get_header_value("X-Forwarded-For");
  9739. res.set_content("ok", "text/plain");
  9740. });
  9741. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9742. auto se = detail::scope_exit([&] {
  9743. svr.stop();
  9744. t.join();
  9745. ASSERT_FALSE(svr.is_running());
  9746. });
  9747. svr.wait_until_ready();
  9748. Client cli(HOST, PORT);
  9749. auto res = cli.Get(
  9750. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9751. ASSERT_TRUE(res);
  9752. EXPECT_EQ(StatusCode::OK_200, res->status);
  9753. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9754. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9755. }
  9756. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9757. Server svr;
  9758. svr.set_trusted_proxies({"192.0.2.45"});
  9759. std::string observed_remote_addr;
  9760. std::string observed_xff;
  9761. svr.Get("/ip", [&](const Request &req, Response &res) {
  9762. observed_remote_addr = req.remote_addr;
  9763. observed_xff = req.get_header_value("X-Forwarded-For");
  9764. res.set_content("ok", "text/plain");
  9765. });
  9766. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9767. auto se = detail::scope_exit([&] {
  9768. svr.stop();
  9769. t.join();
  9770. ASSERT_FALSE(svr.is_running());
  9771. });
  9772. svr.wait_until_ready();
  9773. std::string raw_req =
  9774. "GET /ip HTTP/1.1\r\n"
  9775. "Host: localhost\r\n"
  9776. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9777. "Connection: close\r\n"
  9778. "\r\n";
  9779. std::string out;
  9780. ASSERT_TRUE(send_request(5, raw_req, &out));
  9781. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9782. // Header parser trims surrounding whitespace of the header value
  9783. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9784. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9785. }
  9786. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9787. Server svr;
  9788. svr.Post("/post", [&](const Request &req, Response &res) {
  9789. res.set_content(req.body, "text/plain");
  9790. });
  9791. svr.Put("/put", [&](const Request &req, Response &res) {
  9792. res.set_content(req.body, "text/plain");
  9793. });
  9794. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9795. res.set_content(req.body, "text/plain");
  9796. });
  9797. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9798. res.set_content(req.body, "text/plain");
  9799. });
  9800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9801. auto se = detail::scope_exit([&] {
  9802. svr.stop();
  9803. t.join();
  9804. ASSERT_FALSE(svr.is_running());
  9805. });
  9806. svr.wait_until_ready();
  9807. std::string resp;
  9808. // POST without Content-Length
  9809. ASSERT_TRUE(send_request(5,
  9810. "POST /post HTTP/1.1\r\n"
  9811. "Host: localhost\r\n"
  9812. "Connection: close\r\n"
  9813. "\r\n",
  9814. &resp));
  9815. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9816. // PUT without Content-Length
  9817. resp.clear();
  9818. ASSERT_TRUE(send_request(5,
  9819. "PUT /put HTTP/1.1\r\n"
  9820. "Host: localhost\r\n"
  9821. "Connection: close\r\n"
  9822. "\r\n",
  9823. &resp));
  9824. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9825. // PATCH without Content-Length
  9826. resp.clear();
  9827. ASSERT_TRUE(send_request(5,
  9828. "PATCH /patch HTTP/1.1\r\n"
  9829. "Host: localhost\r\n"
  9830. "Connection: close\r\n"
  9831. "\r\n",
  9832. &resp));
  9833. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9834. // DELETE without Content-Length
  9835. resp.clear();
  9836. ASSERT_TRUE(send_request(5,
  9837. "DELETE /delete HTTP/1.1\r\n"
  9838. "Host: localhost\r\n"
  9839. "Connection: close\r\n"
  9840. "\r\n",
  9841. &resp));
  9842. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9843. }
  9844. //==============================================================================
  9845. // open_stream() Tests
  9846. //==============================================================================
  9847. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9848. std::string result;
  9849. char buf[8192];
  9850. ssize_t n;
  9851. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9852. result.append(buf, static_cast<size_t>(n));
  9853. }
  9854. return result;
  9855. }
  9856. // Mock stream for unit tests
  9857. class MockStream : public Stream {
  9858. public:
  9859. std::string data;
  9860. size_t pos = 0;
  9861. ssize_t error_after = -1; // -1 = no error
  9862. explicit MockStream(const std::string &d, ssize_t err = -1)
  9863. : data(d), error_after(err) {}
  9864. bool is_readable() const override { return true; }
  9865. bool wait_readable() const override { return true; }
  9866. bool wait_writable() const override { return true; }
  9867. ssize_t read(char *ptr, size_t size) override {
  9868. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9869. if (pos >= data.size()) return 0;
  9870. size_t limit =
  9871. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9872. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9873. std::memcpy(ptr, data.data() + pos, to_read);
  9874. pos += to_read;
  9875. return static_cast<ssize_t>(to_read);
  9876. }
  9877. ssize_t write(const char *, size_t) override { return -1; }
  9878. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9879. ip = "127.0.0.1";
  9880. port = 0;
  9881. }
  9882. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9883. ip = "127.0.0.1";
  9884. port = 0;
  9885. }
  9886. socket_t socket() const override { return INVALID_SOCKET; }
  9887. time_t duration() const override { return 0; }
  9888. };
  9889. TEST(StreamHandleTest, Basic) {
  9890. ClientImpl::StreamHandle handle;
  9891. EXPECT_FALSE(handle.is_valid());
  9892. handle.response = detail::make_unique<Response>();
  9893. handle.error = Error::Connection;
  9894. EXPECT_FALSE(handle.is_valid());
  9895. handle.error = Error::Success;
  9896. EXPECT_TRUE(handle.is_valid());
  9897. }
  9898. TEST(BodyReaderTest, Basic) {
  9899. MockStream stream("Hello, World!");
  9900. detail::BodyReader reader;
  9901. reader.stream = &stream;
  9902. reader.content_length = 13;
  9903. char buf[32];
  9904. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9905. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9906. EXPECT_TRUE(reader.eof);
  9907. }
  9908. TEST(BodyReaderTest, NoStream) {
  9909. detail::BodyReader reader;
  9910. char buf[32];
  9911. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9912. EXPECT_EQ(Error::Connection, reader.last_error);
  9913. }
  9914. TEST(BodyReaderTest, Error) {
  9915. MockStream stream("Hello, World!", 5);
  9916. detail::BodyReader reader;
  9917. reader.stream = &stream;
  9918. reader.content_length = 13;
  9919. char buf[32];
  9920. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9921. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9922. EXPECT_EQ(Error::Read, reader.last_error);
  9923. }
  9924. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9925. // Mock-based StreamHandle tests relying on private internals are removed.
  9926. class OpenStreamTest : public ::testing::Test {
  9927. protected:
  9928. void SetUp() override {
  9929. svr_.Get("/hello", [](const Request &, Response &res) {
  9930. res.set_content("Hello World!", "text/plain");
  9931. });
  9932. svr_.Get("/large", [](const Request &, Response &res) {
  9933. res.set_content(std::string(10000, 'X'), "text/plain");
  9934. });
  9935. svr_.Get("/chunked", [](const Request &, Response &res) {
  9936. res.set_chunked_content_provider("text/plain",
  9937. [](size_t offset, DataSink &sink) {
  9938. if (offset < 15) {
  9939. sink.write("chunk", 5);
  9940. return true;
  9941. }
  9942. sink.done();
  9943. return true;
  9944. });
  9945. });
  9946. svr_.Get("/compressible", [](const Request &, Response &res) {
  9947. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9948. DataSink &sink) {
  9949. if (offset < 100 * 1024) {
  9950. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9951. sink.write(chunk.data(), chunk.size());
  9952. return true;
  9953. }
  9954. sink.done();
  9955. return true;
  9956. });
  9957. });
  9958. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9959. [](const Request & /*req*/, Response &res) {
  9960. auto i = new int(0);
  9961. res.set_header("Trailer", "Content-Length, X-Allowed");
  9962. res.set_chunked_content_provider(
  9963. "text/plain",
  9964. [i](size_t /*offset*/, DataSink &sink) {
  9965. switch (*i) {
  9966. case 0: sink.os << "123"; break;
  9967. case 1: sink.os << "456"; break;
  9968. case 2: sink.os << "789"; break;
  9969. case 3: {
  9970. sink.done_with_trailer(
  9971. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9972. } break;
  9973. }
  9974. (*i)++;
  9975. return true;
  9976. },
  9977. [i](bool success) {
  9978. EXPECT_TRUE(success);
  9979. delete i;
  9980. });
  9981. });
  9982. // Echo headers endpoint for header-related tests
  9983. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9984. std::string body;
  9985. for (const auto &h : req.headers) {
  9986. body.append(h.first);
  9987. body.push_back(':');
  9988. body.append(h.second);
  9989. body.push_back('\n');
  9990. }
  9991. res.set_content(body, "text/plain");
  9992. });
  9993. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9994. std::string body;
  9995. for (const auto &h : req.headers) {
  9996. body.append(h.first);
  9997. body.push_back(':');
  9998. body.append(h.second);
  9999. body.push_back('\n');
  10000. }
  10001. res.set_content(body, "text/plain");
  10002. });
  10003. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10004. svr_.wait_until_ready();
  10005. }
  10006. void TearDown() override {
  10007. svr_.stop();
  10008. if (thread_.joinable()) thread_.join();
  10009. }
  10010. Server svr_;
  10011. std::thread thread_;
  10012. };
  10013. TEST_F(OpenStreamTest, Basic) {
  10014. Client cli("127.0.0.1", 8787);
  10015. auto handle = cli.open_stream("GET", "/hello");
  10016. EXPECT_TRUE(handle.is_valid());
  10017. EXPECT_EQ("Hello World!", read_all(handle));
  10018. }
  10019. TEST_F(OpenStreamTest, SmallBuffer) {
  10020. Client cli("127.0.0.1", 8787);
  10021. auto handle = cli.open_stream("GET", "/hello");
  10022. std::string result;
  10023. char buf[4];
  10024. ssize_t n;
  10025. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10026. result.append(buf, static_cast<size_t>(n));
  10027. EXPECT_EQ("Hello World!", result);
  10028. }
  10029. TEST_F(OpenStreamTest, DefaultHeaders) {
  10030. Client cli("127.0.0.1", 8787);
  10031. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10032. {
  10033. auto handle = cli.open_stream("GET", "/echo-headers");
  10034. ASSERT_TRUE(handle.is_valid());
  10035. auto body = read_all(handle);
  10036. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10037. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10038. std::string::npos);
  10039. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10040. }
  10041. // open_stream POST with body and no explicit content_type should NOT add
  10042. // text/plain Content-Type (behavior differs from non-streaming path), but
  10043. // should include Content-Length
  10044. {
  10045. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10046. ASSERT_TRUE(handle.is_valid());
  10047. auto body = read_all(handle);
  10048. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10049. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10050. }
  10051. // open_stream POST with explicit Content-Type should preserve it
  10052. {
  10053. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10054. {{"Content-Type", "application/custom"}},
  10055. "{}", "application/custom");
  10056. ASSERT_TRUE(handle.is_valid());
  10057. auto body = read_all(handle);
  10058. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10059. }
  10060. // User-specified User-Agent must not be overwritten for stream API
  10061. {
  10062. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10063. {{"User-Agent", "MyAgent/1.2"}});
  10064. ASSERT_TRUE(handle.is_valid());
  10065. auto body = read_all(handle);
  10066. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10067. }
  10068. }
  10069. TEST_F(OpenStreamTest, Large) {
  10070. Client cli("127.0.0.1", 8787);
  10071. auto handle = cli.open_stream("GET", "/large");
  10072. EXPECT_EQ(10000u, read_all(handle).size());
  10073. }
  10074. TEST_F(OpenStreamTest, ConnectionError) {
  10075. Client cli("127.0.0.1", 9999);
  10076. auto handle = cli.open_stream("GET", "/hello");
  10077. EXPECT_FALSE(handle.is_valid());
  10078. }
  10079. TEST_F(OpenStreamTest, Chunked) {
  10080. Client cli("127.0.0.1", 8787);
  10081. auto handle = cli.open_stream("GET", "/chunked");
  10082. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10083. "Transfer-Encoding") == "chunked");
  10084. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10085. }
  10086. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10087. Client cli("127.0.0.1", 8787);
  10088. auto handle =
  10089. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10090. ASSERT_TRUE(handle.is_valid());
  10091. // Consume body to allow trailers to be received/parsed
  10092. auto body = read_all(handle);
  10093. // Explicitly parse trailers (ensure trailers are available for assertion)
  10094. handle.parse_trailers_if_needed();
  10095. EXPECT_EQ(std::string("123456789"), body);
  10096. // The response should include a Trailer header declaring both names
  10097. ASSERT_TRUE(handle.response);
  10098. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10099. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10100. handle.response->get_header_value("Trailer"));
  10101. // Prohibited trailer must not be present
  10102. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10103. // Allowed trailer should be present
  10104. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10105. EXPECT_EQ(std::string("yes"),
  10106. handle.response->get_trailer_value("X-Allowed"));
  10107. // Verify trailers are NOT present as regular headers
  10108. EXPECT_EQ(std::string(""),
  10109. handle.response->get_header_value("Content-Length"));
  10110. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10111. }
  10112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10113. TEST_F(OpenStreamTest, Gzip) {
  10114. Client cli("127.0.0.1", 8787);
  10115. auto handle = cli.open_stream("GET", "/compressible", {},
  10116. {{"Accept-Encoding", "gzip"}});
  10117. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10118. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10119. }
  10120. #endif
  10121. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10122. TEST_F(OpenStreamTest, Brotli) {
  10123. Client cli("127.0.0.1", 8787);
  10124. auto handle =
  10125. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10126. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10127. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10128. }
  10129. #endif
  10130. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10131. TEST_F(OpenStreamTest, Zstd) {
  10132. Client cli("127.0.0.1", 8787);
  10133. auto handle = cli.open_stream("GET", "/compressible", {},
  10134. {{"Accept-Encoding", "zstd"}});
  10135. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10136. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10137. }
  10138. #endif
  10139. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10140. class SSLOpenStreamTest : public ::testing::Test {
  10141. protected:
  10142. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10143. void SetUp() override {
  10144. svr_.Get("/hello", [](const Request &, Response &res) {
  10145. res.set_content("Hello SSL World!", "text/plain");
  10146. });
  10147. svr_.Get("/chunked", [](const Request &, Response &res) {
  10148. res.set_chunked_content_provider("text/plain",
  10149. [](size_t offset, DataSink &sink) {
  10150. if (offset < 15) {
  10151. sink.write("chunk", 5);
  10152. return true;
  10153. }
  10154. sink.done();
  10155. return true;
  10156. });
  10157. });
  10158. svr_.Post("/echo", [](const Request &req, Response &res) {
  10159. res.set_content(req.body, req.get_header_value("Content-Type"));
  10160. });
  10161. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10162. std::string body = req.body;
  10163. res.set_chunked_content_provider(
  10164. "text/plain", [body](size_t offset, DataSink &sink) {
  10165. if (offset < body.size()) {
  10166. sink.write(body.data() + offset, body.size() - offset);
  10167. }
  10168. sink.done();
  10169. return true;
  10170. });
  10171. });
  10172. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10173. svr_.wait_until_ready();
  10174. }
  10175. void TearDown() override {
  10176. svr_.stop();
  10177. if (thread_.joinable()) thread_.join();
  10178. }
  10179. SSLServer svr_;
  10180. std::thread thread_;
  10181. };
  10182. TEST_F(SSLOpenStreamTest, Basic) {
  10183. SSLClient cli("127.0.0.1", 8788);
  10184. cli.enable_server_certificate_verification(false);
  10185. auto handle = cli.open_stream("GET", "/hello");
  10186. ASSERT_TRUE(handle.is_valid());
  10187. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10188. }
  10189. TEST_F(SSLOpenStreamTest, Chunked) {
  10190. SSLClient cli("127.0.0.1", 8788);
  10191. cli.enable_server_certificate_verification(false);
  10192. auto handle = cli.open_stream("GET", "/chunked");
  10193. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10194. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10195. "Transfer-Encoding") == "chunked");
  10196. auto body = read_all(handle);
  10197. EXPECT_EQ("chunkchunkchunk", body);
  10198. }
  10199. TEST_F(SSLOpenStreamTest, Post) {
  10200. SSLClient cli("127.0.0.1", 8788);
  10201. cli.enable_server_certificate_verification(false);
  10202. auto handle =
  10203. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10204. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10205. EXPECT_EQ(200, handle.response->status);
  10206. auto body = read_all(handle);
  10207. EXPECT_EQ("Hello SSL POST", body);
  10208. }
  10209. TEST_F(SSLOpenStreamTest, PostChunked) {
  10210. SSLClient cli("127.0.0.1", 8788);
  10211. cli.enable_server_certificate_verification(false);
  10212. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10213. "Chunked SSL Data", "text/plain");
  10214. ASSERT_TRUE(handle.is_valid());
  10215. EXPECT_EQ(200, handle.response->status);
  10216. auto body = read_all(handle);
  10217. EXPECT_EQ("Chunked SSL Data", body);
  10218. }
  10219. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10220. //==============================================================================
  10221. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10222. // results for various scenarios.
  10223. //==============================================================================
  10224. TEST(ParityTest, GetVsOpenStream) {
  10225. Server svr;
  10226. const std::string path = "/parity";
  10227. const std::string content = "Parity test content: hello world";
  10228. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10229. res.set_content(content, "text/plain");
  10230. });
  10231. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10232. auto se = detail::scope_exit([&] {
  10233. svr.stop();
  10234. t.join();
  10235. ASSERT_FALSE(svr.is_running());
  10236. });
  10237. svr.wait_until_ready();
  10238. Client cli(HOST, PORT);
  10239. // Non-stream path
  10240. auto r1 = cli.Get(path);
  10241. ASSERT_TRUE(r1);
  10242. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10243. // Stream path
  10244. auto h = cli.open_stream("GET", path);
  10245. ASSERT_TRUE(h.is_valid());
  10246. EXPECT_EQ(r1->body, read_all(h));
  10247. }
  10248. // Helper to compress data with provided compressor type T
  10249. template <typename Compressor>
  10250. static std::string compress_payload_for_parity(const std::string &in) {
  10251. std::string out;
  10252. Compressor compressor;
  10253. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10254. [&](const char *data, size_t n) {
  10255. out.append(data, n);
  10256. return true;
  10257. });
  10258. EXPECT_TRUE(ok);
  10259. return out;
  10260. }
  10261. // Helper function for compression parity tests
  10262. template <typename Compressor>
  10263. static void test_compression_parity(const std::string &original,
  10264. const std::string &path,
  10265. const std::string &encoding) {
  10266. const std::string compressed =
  10267. compress_payload_for_parity<Compressor>(original);
  10268. Server svr;
  10269. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10270. res.set_content(compressed, "application/octet-stream");
  10271. res.set_header("Content-Encoding", encoding);
  10272. });
  10273. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10274. auto se = detail::scope_exit([&] {
  10275. svr.stop();
  10276. t.join();
  10277. ASSERT_FALSE(svr.is_running());
  10278. });
  10279. svr.wait_until_ready();
  10280. Client cli(HOST, PORT);
  10281. // Non-streaming
  10282. {
  10283. auto res = cli.Get(path);
  10284. ASSERT_TRUE(res);
  10285. EXPECT_EQ(StatusCode::OK_200, res->status);
  10286. EXPECT_EQ(original, res->body);
  10287. }
  10288. // Streaming
  10289. {
  10290. auto h = cli.open_stream("GET", path);
  10291. ASSERT_TRUE(h.is_valid());
  10292. EXPECT_EQ(original, read_all(h));
  10293. }
  10294. }
  10295. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10296. TEST(ParityTest, Gzip) {
  10297. test_compression_parity<detail::gzip_compressor>(
  10298. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10299. }
  10300. #endif
  10301. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10302. TEST(ParityTest, Brotli) {
  10303. test_compression_parity<detail::brotli_compressor>(
  10304. "Hello, brotli parity test payload", "/parity-br", "br");
  10305. }
  10306. #endif
  10307. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10308. TEST(ParityTest, Zstd) {
  10309. test_compression_parity<detail::zstd_compressor>(
  10310. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10311. }
  10312. #endif
  10313. //==============================================================================
  10314. // New Stream API Tests
  10315. //==============================================================================
  10316. inline std::string read_body(httplib::stream::Result &result) {
  10317. std::string body;
  10318. while (result.next()) {
  10319. body.append(result.data(), result.size());
  10320. }
  10321. return body;
  10322. }
  10323. TEST(ClientConnectionTest, Basic) {
  10324. httplib::ClientConnection conn;
  10325. EXPECT_FALSE(conn.is_open());
  10326. conn.sock = 1;
  10327. EXPECT_TRUE(conn.is_open());
  10328. httplib::ClientConnection conn2(std::move(conn));
  10329. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10330. conn2.sock = INVALID_SOCKET;
  10331. }
  10332. // Unified test server for all stream::* tests
  10333. class StreamApiTest : public ::testing::Test {
  10334. protected:
  10335. void SetUp() override {
  10336. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10337. res.set_content("Hello World!", "text/plain");
  10338. });
  10339. svr_.Get("/echo-params",
  10340. [](const httplib::Request &req, httplib::Response &res) {
  10341. std::string r;
  10342. for (const auto &p : req.params) {
  10343. if (!r.empty()) r += "&";
  10344. r += p.first + "=" + p.second;
  10345. }
  10346. res.set_content(r, "text/plain");
  10347. });
  10348. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10349. res.set_content(req.body, req.get_header_value("Content-Type"));
  10350. });
  10351. svr_.Post("/echo-headers",
  10352. [](const httplib::Request &req, httplib::Response &res) {
  10353. std::string r;
  10354. for (const auto &h : req.headers)
  10355. r += h.first + ": " + h.second + "\n";
  10356. res.set_content(r, "text/plain");
  10357. });
  10358. svr_.Post("/echo-params",
  10359. [](const httplib::Request &req, httplib::Response &res) {
  10360. std::string r = "params:";
  10361. for (const auto &p : req.params)
  10362. r += p.first + "=" + p.second + ";";
  10363. res.set_content(r + " body:" + req.body, "text/plain");
  10364. });
  10365. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10366. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10367. });
  10368. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10369. res.set_content("PUT:" + req.body, "text/plain");
  10370. });
  10371. svr_.Patch("/echo",
  10372. [](const httplib::Request &req, httplib::Response &res) {
  10373. res.set_content("PATCH:" + req.body, "text/plain");
  10374. });
  10375. svr_.Delete(
  10376. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10377. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10378. "text/plain");
  10379. });
  10380. svr_.Get("/head-test",
  10381. [](const httplib::Request &, httplib::Response &res) {
  10382. res.set_content("body for HEAD", "text/plain");
  10383. });
  10384. svr_.Options("/options",
  10385. [](const httplib::Request &, httplib::Response &res) {
  10386. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10387. });
  10388. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10389. svr_.wait_until_ready();
  10390. }
  10391. void TearDown() override {
  10392. svr_.stop();
  10393. if (thread_.joinable()) thread_.join();
  10394. }
  10395. httplib::Server svr_;
  10396. std::thread thread_;
  10397. };
  10398. // stream::Get tests
  10399. TEST_F(StreamApiTest, GetBasic) {
  10400. httplib::Client cli(HOST, PORT);
  10401. auto result = httplib::stream::Get(cli, "/hello");
  10402. ASSERT_TRUE(result.is_valid());
  10403. EXPECT_EQ(200, result.status());
  10404. EXPECT_EQ("Hello World!", read_body(result));
  10405. }
  10406. TEST_F(StreamApiTest, GetWithParams) {
  10407. httplib::Client cli(HOST, PORT);
  10408. httplib::Params params{{"foo", "bar"}};
  10409. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10410. ASSERT_TRUE(result.is_valid());
  10411. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10412. }
  10413. TEST_F(StreamApiTest, GetConnectionError) {
  10414. httplib::Client cli(HOST, 9999);
  10415. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10416. }
  10417. TEST_F(StreamApiTest, Get404) {
  10418. httplib::Client cli(HOST, PORT);
  10419. auto result = httplib::stream::Get(cli, "/nonexistent");
  10420. EXPECT_TRUE(result.is_valid());
  10421. EXPECT_EQ(404, result.status());
  10422. }
  10423. // stream::Post tests
  10424. TEST_F(StreamApiTest, PostBasic) {
  10425. httplib::Client cli(HOST, PORT);
  10426. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10427. "application/json");
  10428. ASSERT_TRUE(result.is_valid());
  10429. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10430. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10431. }
  10432. TEST_F(StreamApiTest, PostWithHeaders) {
  10433. httplib::Client cli(HOST, PORT);
  10434. httplib::Headers headers{{"X-Custom", "value"}};
  10435. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10436. "text/plain");
  10437. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10438. }
  10439. TEST_F(StreamApiTest, PostWithParams) {
  10440. httplib::Client cli(HOST, PORT);
  10441. httplib::Params params{{"k", "v"}};
  10442. auto result =
  10443. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10444. auto body = read_body(result);
  10445. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10446. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10447. }
  10448. TEST_F(StreamApiTest, PostLarge) {
  10449. httplib::Client cli(HOST, PORT);
  10450. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10451. size_t total = 0;
  10452. while (result.next()) {
  10453. total += result.size();
  10454. }
  10455. EXPECT_EQ(100u * 1024u, total);
  10456. }
  10457. // stream::Put/Patch tests
  10458. TEST_F(StreamApiTest, PutAndPatch) {
  10459. httplib::Client cli(HOST, PORT);
  10460. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10461. EXPECT_EQ("PUT:test", read_body(put));
  10462. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10463. EXPECT_EQ("PATCH:test", read_body(patch));
  10464. }
  10465. // stream::Delete tests
  10466. TEST_F(StreamApiTest, Delete) {
  10467. httplib::Client cli(HOST, PORT);
  10468. auto del1 = httplib::stream::Delete(cli, "/resource");
  10469. EXPECT_EQ("Deleted", read_body(del1));
  10470. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10471. EXPECT_EQ("Deleted:data", read_body(del2));
  10472. }
  10473. // stream::Head/Options tests
  10474. TEST_F(StreamApiTest, HeadAndOptions) {
  10475. httplib::Client cli(HOST, PORT);
  10476. auto head = httplib::stream::Head(cli, "/head-test");
  10477. EXPECT_TRUE(head.is_valid());
  10478. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10479. auto opts = httplib::stream::Options(cli, "/options");
  10480. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10481. }
  10482. // SSL stream::* tests
  10483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10484. class SSLStreamApiTest : public ::testing::Test {
  10485. protected:
  10486. void SetUp() override {
  10487. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10488. res.set_content("Hello SSL!", "text/plain");
  10489. });
  10490. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10491. res.set_content(req.body, "text/plain");
  10492. });
  10493. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10494. svr_.wait_until_ready();
  10495. }
  10496. void TearDown() override {
  10497. svr_.stop();
  10498. if (thread_.joinable()) thread_.join();
  10499. }
  10500. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10501. std::thread thread_;
  10502. };
  10503. TEST_F(SSLStreamApiTest, GetAndPost) {
  10504. httplib::SSLClient cli("127.0.0.1", 8803);
  10505. cli.enable_server_certificate_verification(false);
  10506. auto get = httplib::stream::Get(cli, "/hello");
  10507. EXPECT_EQ("Hello SSL!", read_body(get));
  10508. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10509. EXPECT_EQ("test", read_body(post));
  10510. }
  10511. #endif
  10512. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10513. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10514. // BodyReader
  10515. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10516. // Test that read timeout during streaming is detected
  10517. // Use a large content-length response where server delays mid-stream
  10518. Server svr;
  10519. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10520. // Send a large response with delay in the middle
  10521. res.set_content_provider(
  10522. 1000, // content_length
  10523. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10524. if (offset < 100) {
  10525. // Send first 100 bytes immediately
  10526. std::string data(100, 'A');
  10527. sink.write(data.c_str(), data.size());
  10528. return true;
  10529. }
  10530. // Then delay longer than client timeout
  10531. std::this_thread::sleep_for(std::chrono::seconds(3));
  10532. std::string data(900, 'B');
  10533. sink.write(data.c_str(), data.size());
  10534. return true;
  10535. });
  10536. });
  10537. auto port = 8091;
  10538. std::thread t([&]() { svr.listen("localhost", port); });
  10539. svr.wait_until_ready();
  10540. Client cli("localhost", port);
  10541. cli.set_read_timeout(1, 0); // 1 second timeout
  10542. auto handle = cli.open_stream("GET", "/slow-stream");
  10543. ASSERT_TRUE(handle.is_valid());
  10544. char buf[256];
  10545. ssize_t total = 0;
  10546. ssize_t n;
  10547. bool got_error = false;
  10548. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10549. total += n;
  10550. }
  10551. if (n < 0) {
  10552. got_error = true;
  10553. // Should be timeout or read error
  10554. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10555. handle.get_read_error() == Error::Read)
  10556. << "Actual error: " << to_string(handle.get_read_error());
  10557. }
  10558. // Either we got an error, or we got less data than expected
  10559. EXPECT_TRUE(got_error || total < 1000)
  10560. << "Expected timeout but got all " << total << " bytes";
  10561. svr.stop();
  10562. t.join();
  10563. }
  10564. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10565. // Test connection closed detection via BodyReader
  10566. Server svr;
  10567. std::atomic<bool> close_now{false};
  10568. svr.Get("/will-close", [&](const Request &, Response &res) {
  10569. res.set_content_provider(
  10570. 10000, // Large content_length that we won't fully send
  10571. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10572. if (offset < 100) {
  10573. std::string data(100, 'X');
  10574. sink.write(data.c_str(), data.size());
  10575. return true;
  10576. }
  10577. // Wait for signal then abort
  10578. while (!close_now) {
  10579. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10580. }
  10581. return false; // Abort - server will close connection
  10582. });
  10583. });
  10584. auto port = 8092;
  10585. std::thread t([&]() { svr.listen("localhost", port); });
  10586. svr.wait_until_ready();
  10587. Client cli("localhost", port);
  10588. auto handle = cli.open_stream("GET", "/will-close");
  10589. ASSERT_TRUE(handle.is_valid());
  10590. char buf[256];
  10591. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10592. EXPECT_GT(n, 0) << "First read should succeed";
  10593. // Signal server to close
  10594. close_now = true;
  10595. // Keep reading until error or EOF
  10596. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10597. // Keep reading
  10598. }
  10599. // Should get an error since content_length wasn't satisfied
  10600. if (n < 0) {
  10601. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10602. handle.get_read_error() == Error::Read)
  10603. << "Actual error: " << to_string(handle.get_read_error());
  10604. }
  10605. svr.stop();
  10606. t.join();
  10607. }
  10608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10609. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10610. // Test that read timeout during SSL streaming is detected
  10611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10612. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10613. res.set_content_provider(
  10614. 1000, "text/plain",
  10615. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10616. if (offset < 100) {
  10617. std::string data(100, 'A');
  10618. sink.write(data.c_str(), data.size());
  10619. return true;
  10620. }
  10621. std::this_thread::sleep_for(std::chrono::seconds(3));
  10622. std::string data(900, 'B');
  10623. sink.write(data.c_str(), data.size());
  10624. return true;
  10625. });
  10626. });
  10627. auto port = 8093;
  10628. std::thread t([&]() { svr.listen("localhost", port); });
  10629. svr.wait_until_ready();
  10630. SSLClient cli("localhost", port);
  10631. cli.enable_server_certificate_verification(false);
  10632. cli.set_read_timeout(1, 0); // 1 second timeout
  10633. auto handle = cli.open_stream("GET", "/slow-stream");
  10634. ASSERT_TRUE(handle.is_valid());
  10635. char buf[256];
  10636. ssize_t total = 0;
  10637. ssize_t n;
  10638. bool got_error = false;
  10639. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10640. total += n;
  10641. }
  10642. if (n < 0) {
  10643. got_error = true;
  10644. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10645. handle.get_read_error() == Error::Read)
  10646. << "Actual error: " << to_string(handle.get_read_error());
  10647. }
  10648. EXPECT_TRUE(got_error || total < 1000)
  10649. << "Expected timeout but got all " << total << " bytes";
  10650. svr.stop();
  10651. t.join();
  10652. }
  10653. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10654. // Test SSL connection closed detection
  10655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10656. std::atomic<bool> close_now{false};
  10657. svr.Get("/will-close", [&](const Request &, Response &res) {
  10658. res.set_content_provider(
  10659. 10000, "text/plain",
  10660. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10661. if (offset < 100) {
  10662. std::string data(100, 'X');
  10663. sink.write(data.c_str(), data.size());
  10664. return true;
  10665. }
  10666. while (!close_now) {
  10667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10668. }
  10669. return false;
  10670. });
  10671. });
  10672. auto port = 8094;
  10673. std::thread t([&]() { svr.listen("localhost", port); });
  10674. svr.wait_until_ready();
  10675. SSLClient cli("localhost", port);
  10676. cli.enable_server_certificate_verification(false);
  10677. auto handle = cli.open_stream("GET", "/will-close");
  10678. ASSERT_TRUE(handle.is_valid());
  10679. char buf[256];
  10680. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10681. EXPECT_GT(n, 0);
  10682. // Signal server to close
  10683. close_now = true;
  10684. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10685. // Keep reading
  10686. }
  10687. if (n < 0) {
  10688. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10689. handle.get_read_error() == Error::Read)
  10690. << "Actual error: " << to_string(handle.get_read_error());
  10691. }
  10692. svr.stop();
  10693. t.join();
  10694. }
  10695. #endif
  10696. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10697. using namespace httplib;
  10698. // Create a test file
  10699. const char *fname = "etag_testfile.txt";
  10700. const char *content = "etag-content";
  10701. {
  10702. std::ofstream ofs(fname);
  10703. ofs << content;
  10704. ASSERT_TRUE(ofs.good());
  10705. }
  10706. Server svr;
  10707. svr.set_mount_point("/static", ".");
  10708. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10709. svr.wait_until_ready();
  10710. Client cli(HOST, PORT);
  10711. // First request: should get 200 with ETag header
  10712. auto res1 = cli.Get("/static/etag_testfile.txt");
  10713. ASSERT_TRUE(res1);
  10714. ASSERT_EQ(200, res1->status);
  10715. ASSERT_TRUE(res1->has_header("ETag"));
  10716. std::string etag = res1->get_header_value("ETag");
  10717. EXPECT_FALSE(etag.empty());
  10718. // Verify ETag format: W/"hex-hex"
  10719. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10720. EXPECT_EQ('W', etag[0]);
  10721. EXPECT_EQ('/', etag[1]);
  10722. EXPECT_EQ('"', etag[2]);
  10723. EXPECT_EQ('"', etag.back());
  10724. // Exact match: expect 304 Not Modified
  10725. Headers h2 = {{"If-None-Match", etag}};
  10726. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10727. ASSERT_TRUE(res2);
  10728. EXPECT_EQ(304, res2->status);
  10729. // Wildcard match: expect 304 Not Modified
  10730. Headers h3 = {{"If-None-Match", "*"}};
  10731. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10732. ASSERT_TRUE(res3);
  10733. EXPECT_EQ(304, res3->status);
  10734. // Non-matching ETag: expect 200
  10735. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10736. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10737. ASSERT_TRUE(res4);
  10738. EXPECT_EQ(200, res4->status);
  10739. // Multiple ETags with one matching: expect 304
  10740. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10741. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10742. ASSERT_TRUE(res5);
  10743. EXPECT_EQ(304, res5->status);
  10744. svr.stop();
  10745. t.join();
  10746. std::remove(fname);
  10747. }
  10748. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10749. using namespace httplib;
  10750. Server svr;
  10751. svr.set_mount_point("/static", ".");
  10752. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10753. svr.wait_until_ready();
  10754. Client cli(HOST, PORT);
  10755. // Send If-None-Match: * to a non-existent file
  10756. Headers h = {{"If-None-Match", "*"}};
  10757. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10758. ASSERT_TRUE(res);
  10759. EXPECT_EQ(404, res->status);
  10760. svr.stop();
  10761. t.join();
  10762. }
  10763. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10764. using namespace httplib;
  10765. // Create a test file
  10766. const char *fname = "ims_testfile.txt";
  10767. const char *content = "if-modified-since-test";
  10768. {
  10769. std::ofstream ofs(fname);
  10770. ofs << content;
  10771. ASSERT_TRUE(ofs.good());
  10772. }
  10773. Server svr;
  10774. svr.set_mount_point("/static", ".");
  10775. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10776. svr.wait_until_ready();
  10777. Client cli(HOST, PORT);
  10778. // First request: should get 200 with Last-Modified header
  10779. auto res1 = cli.Get("/static/ims_testfile.txt");
  10780. ASSERT_TRUE(res1);
  10781. ASSERT_EQ(200, res1->status);
  10782. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10783. std::string last_modified = res1->get_header_value("Last-Modified");
  10784. EXPECT_FALSE(last_modified.empty());
  10785. // If-Modified-Since with same time: expect 304
  10786. Headers h2 = {{"If-Modified-Since", last_modified}};
  10787. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10788. ASSERT_TRUE(res2);
  10789. EXPECT_EQ(304, res2->status);
  10790. // If-Modified-Since with future time: expect 304
  10791. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10792. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10793. ASSERT_TRUE(res3);
  10794. EXPECT_EQ(304, res3->status);
  10795. // If-Modified-Since with past time: expect 200
  10796. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10797. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10798. ASSERT_TRUE(res4);
  10799. EXPECT_EQ(200, res4->status);
  10800. // If-None-Match takes precedence over If-Modified-Since
  10801. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10802. ASSERT_TRUE(res1->has_header("ETag"));
  10803. std::string etag = res1->get_header_value("ETag");
  10804. Headers h5 = {{"If-None-Match", etag},
  10805. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10806. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10807. ASSERT_TRUE(res5);
  10808. EXPECT_EQ(304, res5->status);
  10809. svr.stop();
  10810. t.join();
  10811. std::remove(fname);
  10812. }
  10813. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10814. using namespace httplib;
  10815. Server svr;
  10816. // Endpoint that returns compressible content
  10817. svr.Get("/compressible", [](const Request &, Response &res) {
  10818. // Return a large enough body to trigger compression
  10819. std::string body(1000, 'a');
  10820. res.set_content(body, "text/plain");
  10821. });
  10822. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10823. svr.wait_until_ready();
  10824. Client cli(HOST, PORT);
  10825. // Request with gzip support: should get Vary header when compressed
  10826. cli.set_compress(true);
  10827. auto res1 = cli.Get("/compressible");
  10828. ASSERT_TRUE(res1);
  10829. EXPECT_EQ(200, res1->status);
  10830. // If Content-Encoding is set, Vary should also be set
  10831. if (res1->has_header("Content-Encoding")) {
  10832. EXPECT_TRUE(res1->has_header("Vary"));
  10833. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10834. }
  10835. // Request without Accept-Encoding header: should not have compression
  10836. Headers h_no_compress;
  10837. auto res2 = cli.Get("/compressible", h_no_compress);
  10838. ASSERT_TRUE(res2);
  10839. EXPECT_EQ(200, res2->status);
  10840. // Verify Vary header is present when compression is applied
  10841. // (the exact behavior depends on server configuration)
  10842. svr.stop();
  10843. t.join();
  10844. }
  10845. TEST(ETagTest, IfRangeWithETag) {
  10846. using namespace httplib;
  10847. // Create a test file with known content
  10848. const char *fname = "if_range_testfile.txt";
  10849. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10850. {
  10851. std::ofstream ofs(fname);
  10852. ofs << content;
  10853. ASSERT_TRUE(ofs.good());
  10854. }
  10855. Server svr;
  10856. svr.set_mount_point("/static", ".");
  10857. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10858. svr.wait_until_ready();
  10859. Client cli(HOST, PORT);
  10860. // First request: get ETag
  10861. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10862. ASSERT_TRUE(res1);
  10863. ASSERT_EQ(200, res1->status);
  10864. ASSERT_TRUE(res1->has_header("ETag"));
  10865. std::string etag = res1->get_header_value("ETag");
  10866. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10867. // Since our server generates weak ETags (W/"..."), If-Range with our
  10868. // ETag should NOT result in partial content - it should return full content.
  10869. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10870. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10871. ASSERT_TRUE(res2);
  10872. // Weak ETag in If-Range -> full content (200), not partial (206)
  10873. EXPECT_EQ(200, res2->status);
  10874. EXPECT_EQ(content, res2->body);
  10875. EXPECT_FALSE(res2->has_header("Content-Range"));
  10876. // Range request with non-matching If-Range (ETag): should get 200 (full
  10877. // content)
  10878. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10879. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10880. ASSERT_TRUE(res3);
  10881. EXPECT_EQ(200, res3->status);
  10882. EXPECT_EQ(content, res3->body);
  10883. EXPECT_FALSE(res3->has_header("Content-Range"));
  10884. // Range request with strong ETag (hypothetical - our server doesn't generate
  10885. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10886. // should return full content)
  10887. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10888. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10889. ASSERT_TRUE(res4);
  10890. EXPECT_EQ(200, res4->status);
  10891. EXPECT_EQ(content, res4->body);
  10892. EXPECT_FALSE(res4->has_header("Content-Range"));
  10893. svr.stop();
  10894. t.join();
  10895. std::remove(fname);
  10896. }
  10897. TEST(ETagTest, IfRangeWithDate) {
  10898. using namespace httplib;
  10899. // Create a test file
  10900. const char *fname = "if_range_date_testfile.txt";
  10901. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10902. {
  10903. std::ofstream ofs(fname);
  10904. ofs << content;
  10905. ASSERT_TRUE(ofs.good());
  10906. }
  10907. Server svr;
  10908. svr.set_mount_point("/static", ".");
  10909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10910. svr.wait_until_ready();
  10911. Client cli(HOST, PORT);
  10912. // First request: get Last-Modified
  10913. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10914. ASSERT_TRUE(res1);
  10915. ASSERT_EQ(200, res1->status);
  10916. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10917. std::string last_modified = res1->get_header_value("Last-Modified");
  10918. // Range request with matching If-Range (date): should get 206
  10919. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10920. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10921. ASSERT_TRUE(res2);
  10922. EXPECT_EQ(206, res2->status);
  10923. EXPECT_EQ("FGHIJ", res2->body);
  10924. // Range request with old If-Range date: should get 200 (full content)
  10925. Headers h3 = {{"Range", "bytes=5-9"},
  10926. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10927. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10928. ASSERT_TRUE(res3);
  10929. EXPECT_EQ(200, res3->status);
  10930. EXPECT_EQ(content, res3->body);
  10931. // Range request with future If-Range date: should get 206
  10932. Headers h4 = {{"Range", "bytes=0-4"},
  10933. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10934. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10935. ASSERT_TRUE(res4);
  10936. EXPECT_EQ(206, res4->status);
  10937. EXPECT_EQ("ABCDE", res4->body);
  10938. svr.stop();
  10939. t.join();
  10940. std::remove(fname);
  10941. }
  10942. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10943. using namespace httplib;
  10944. const char *fname = "etag_malformed.txt";
  10945. const char *content = "malformed-etag";
  10946. {
  10947. std::ofstream ofs(fname);
  10948. ofs << content;
  10949. ASSERT_TRUE(ofs.good());
  10950. }
  10951. Server svr;
  10952. svr.set_mount_point("/static", ".");
  10953. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10954. svr.wait_until_ready();
  10955. Client cli(HOST, PORT);
  10956. // baseline: should get 200 and an ETag
  10957. auto res1 = cli.Get("/static/etag_malformed.txt");
  10958. ASSERT_TRUE(res1);
  10959. ASSERT_EQ(200, res1->status);
  10960. ASSERT_TRUE(res1->has_header("ETag"));
  10961. // Malformed ETag value (missing quotes) should be treated as non-matching
  10962. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10963. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10964. ASSERT_TRUE(res_bad);
  10965. EXPECT_EQ(200, res_bad->status);
  10966. // Whitespace-only header value should be considered invalid / non-matching
  10967. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  10968. "Host: localhost\r\n"
  10969. "If-None-Match: \r\n"
  10970. "Connection: close\r\n"
  10971. "\r\n";
  10972. std::string out;
  10973. ASSERT_TRUE(send_request(5, raw_req, &out));
  10974. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10975. svr.stop();
  10976. t.join();
  10977. std::remove(fname);
  10978. }
  10979. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10980. using namespace httplib;
  10981. const char *fname = "ims_invalid_format.txt";
  10982. const char *content = "ims-bad-format";
  10983. {
  10984. std::ofstream ofs(fname);
  10985. ofs << content;
  10986. ASSERT_TRUE(ofs.good());
  10987. }
  10988. Server svr;
  10989. svr.set_mount_point("/static", ".");
  10990. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10991. svr.wait_until_ready();
  10992. Client cli(HOST, PORT);
  10993. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10994. ASSERT_TRUE(res1);
  10995. ASSERT_EQ(200, res1->status);
  10996. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10997. // If-Modified-Since with invalid format should not result in 304
  10998. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  10999. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11000. ASSERT_TRUE(res_bad);
  11001. EXPECT_EQ(200, res_bad->status);
  11002. // If-Range with invalid date format should be treated as mismatch -> full
  11003. // content (200)
  11004. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11005. {"If-Range", "invalid-date"}};
  11006. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11007. ASSERT_TRUE(res_ifrange);
  11008. EXPECT_EQ(200, res_ifrange->status);
  11009. svr.stop();
  11010. t.join();
  11011. std::remove(fname);
  11012. }
  11013. TEST(ETagTest, IfRangeWithMalformedETag) {
  11014. using namespace httplib;
  11015. const char *fname = "ifrange_malformed.txt";
  11016. const std::string content = "0123456789";
  11017. {
  11018. std::ofstream ofs(fname);
  11019. ofs << content;
  11020. ASSERT_TRUE(ofs.good());
  11021. }
  11022. Server svr;
  11023. svr.set_mount_point("/static", ".");
  11024. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11025. svr.wait_until_ready();
  11026. Client cli(HOST, PORT);
  11027. // First request: get ETag
  11028. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11029. ASSERT_TRUE(res1);
  11030. ASSERT_EQ(200, res1->status);
  11031. ASSERT_TRUE(res1->has_header("ETag"));
  11032. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11033. // full content (200)
  11034. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11035. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11036. ASSERT_TRUE(res2);
  11037. EXPECT_EQ(200, res2->status);
  11038. EXPECT_EQ(content, res2->body);
  11039. svr.stop();
  11040. t.join();
  11041. std::remove(fname);
  11042. }
  11043. TEST(ETagTest, ExtremeLargeDateValues) {
  11044. using namespace httplib;
  11045. const char *fname = "ims_extreme_date.txt";
  11046. const char *content = "ims-extreme-date";
  11047. {
  11048. std::ofstream ofs(fname);
  11049. ofs << content;
  11050. ASSERT_TRUE(ofs.good());
  11051. }
  11052. Server svr;
  11053. svr.set_mount_point("/static", ".");
  11054. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11055. svr.wait_until_ready();
  11056. Client cli(HOST, PORT);
  11057. auto res1 = cli.Get(std::string("/static/") + fname);
  11058. ASSERT_TRUE(res1);
  11059. ASSERT_EQ(200, res1->status);
  11060. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11061. // Extremely large year that may overflow date parsing routines.
  11062. Headers h_large_date = {
  11063. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11064. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11065. ASSERT_TRUE(res_bad);
  11066. // Expect server to treat this as invalid/mismatch and return full content
  11067. EXPECT_EQ(200, res_bad->status);
  11068. // If-Range with extremely large date should be treated as mismatch -> full
  11069. // content (200)
  11070. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11071. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11072. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11073. ASSERT_TRUE(res_ifrange);
  11074. EXPECT_EQ(200, res_ifrange->status);
  11075. svr.stop();
  11076. t.join();
  11077. std::remove(fname);
  11078. }
  11079. TEST(ETagTest, NegativeFileModificationTime) {
  11080. using namespace httplib;
  11081. const char *fname = "ims_negative_mtime.txt";
  11082. const std::string content = "negative-mtime";
  11083. {
  11084. std::ofstream ofs(fname);
  11085. ofs << content;
  11086. ASSERT_TRUE(ofs.good());
  11087. }
  11088. // Try to set file mtime to a negative value. This may fail on some
  11089. // platforms/filesystems; if it fails, the test will still verify server
  11090. // behaves safely by performing a regular conditional request.
  11091. #if defined(__APPLE__) || defined(__linux__)
  11092. bool set_negative = false;
  11093. do {
  11094. struct timeval times[2];
  11095. // access time: now
  11096. times[0].tv_sec = time(nullptr);
  11097. times[0].tv_usec = 0;
  11098. // modification time: negative (e.g., -1)
  11099. times[1].tv_sec = -1;
  11100. times[1].tv_usec = 0;
  11101. if (utimes(fname, times) == 0) { set_negative = true; }
  11102. } while (0);
  11103. #else
  11104. bool set_negative = false;
  11105. #endif
  11106. Server svr;
  11107. svr.set_mount_point("/static", ".");
  11108. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11109. svr.wait_until_ready();
  11110. Client cli(HOST, PORT);
  11111. auto res1 = cli.Get(std::string("/static/") + fname);
  11112. ASSERT_TRUE(res1);
  11113. ASSERT_EQ(200, res1->status);
  11114. bool has_last_modified = res1->has_header("Last-Modified");
  11115. std::string last_modified;
  11116. if (has_last_modified) {
  11117. last_modified = res1->get_header_value("Last-Modified");
  11118. }
  11119. if (set_negative) {
  11120. // If we successfully set a negative mtime, ensure server returns a
  11121. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11122. // with an old date and ensure server handles it without crash.
  11123. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11124. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11125. ASSERT_TRUE(res2);
  11126. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11127. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11128. } else {
  11129. // Could not set negative mtime on this platform; fall back to verifying
  11130. // that normal invalid/malformed dates are treated safely (non-304).
  11131. Headers h_bad_date = {
  11132. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11133. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11134. ASSERT_TRUE(res_bad);
  11135. EXPECT_EQ(200, res_bad->status);
  11136. }
  11137. svr.stop();
  11138. t.join();
  11139. std::remove(fname);
  11140. }
  11141. //==============================================================================
  11142. // SSE Parsing Tests
  11143. //==============================================================================
  11144. class SSEParsingTest : public ::testing::Test {
  11145. protected:
  11146. // Test helper that mimics SSE parsing behavior
  11147. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11148. int &retry_ms) {
  11149. // Blank line signals end of event
  11150. if (line.empty() || line == "\r") { return true; }
  11151. // Lines starting with ':' are comments (ignored)
  11152. if (!line.empty() && line[0] == ':') { return false; }
  11153. // Find the colon separator
  11154. auto colon_pos = line.find(':');
  11155. if (colon_pos == std::string::npos) {
  11156. // Line with no colon is treated as field name with empty value
  11157. return false;
  11158. }
  11159. std::string field = line.substr(0, colon_pos);
  11160. std::string value;
  11161. // Value starts after colon, skip optional single space
  11162. if (colon_pos + 1 < line.size()) {
  11163. size_t value_start = colon_pos + 1;
  11164. if (line[value_start] == ' ') { value_start++; }
  11165. value = line.substr(value_start);
  11166. // Remove trailing \r if present
  11167. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11168. }
  11169. // Handle known fields
  11170. if (field == "event") {
  11171. msg.event = value;
  11172. } else if (field == "data") {
  11173. // Multiple data lines are concatenated with newlines
  11174. if (!msg.data.empty()) { msg.data += "\n"; }
  11175. msg.data += value;
  11176. } else if (field == "id") {
  11177. // Empty id is valid (clears the last event ID)
  11178. msg.id = value;
  11179. } else if (field == "retry") {
  11180. // Parse retry interval in milliseconds
  11181. try {
  11182. retry_ms = std::stoi(value);
  11183. } catch (...) {
  11184. // Invalid retry value, ignore
  11185. }
  11186. }
  11187. // Unknown fields are ignored per SSE spec
  11188. return false;
  11189. }
  11190. };
  11191. // Test: Single-line data
  11192. TEST_F(SSEParsingTest, SingleLineData) {
  11193. sse::SSEMessage msg;
  11194. int retry_ms = 3000;
  11195. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11196. EXPECT_EQ(msg.data, "hello");
  11197. EXPECT_EQ(msg.event, "message");
  11198. // Blank line ends event
  11199. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11200. }
  11201. // Test: Multi-line data
  11202. TEST_F(SSEParsingTest, MultiLineData) {
  11203. sse::SSEMessage msg;
  11204. int retry_ms = 3000;
  11205. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11206. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11207. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11208. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11209. }
  11210. // Test: Custom event types
  11211. TEST_F(SSEParsingTest, CustomEventType) {
  11212. sse::SSEMessage msg;
  11213. int retry_ms = 3000;
  11214. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11215. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11216. EXPECT_EQ(msg.event, "update");
  11217. EXPECT_EQ(msg.data, "payload");
  11218. }
  11219. // Test: Event ID handling
  11220. TEST_F(SSEParsingTest, EventIdHandling) {
  11221. sse::SSEMessage msg;
  11222. int retry_ms = 3000;
  11223. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11224. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11225. EXPECT_EQ(msg.id, "12345");
  11226. }
  11227. // Test: Empty event ID (clears last event ID)
  11228. TEST_F(SSEParsingTest, EmptyEventId) {
  11229. sse::SSEMessage msg;
  11230. msg.id = "previous";
  11231. int retry_ms = 3000;
  11232. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11233. EXPECT_EQ(msg.id, "");
  11234. }
  11235. // Test: Retry field parsing
  11236. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11237. sse::SSEMessage msg;
  11238. int retry_ms = 3000;
  11239. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11240. EXPECT_EQ(retry_ms, 5000);
  11241. }
  11242. // Test: Invalid retry value
  11243. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11244. sse::SSEMessage msg;
  11245. int retry_ms = 3000;
  11246. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11247. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11248. }
  11249. // Test: Comments (lines starting with :)
  11250. TEST_F(SSEParsingTest, CommentsIgnored) {
  11251. sse::SSEMessage msg;
  11252. int retry_ms = 3000;
  11253. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11254. EXPECT_EQ(msg.data, "");
  11255. EXPECT_EQ(msg.event, "message");
  11256. }
  11257. // Test: Colon in value
  11258. TEST_F(SSEParsingTest, ColonInValue) {
  11259. sse::SSEMessage msg;
  11260. int retry_ms = 3000;
  11261. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11262. EXPECT_EQ(msg.data, "hello:world:test");
  11263. }
  11264. // Test: Line with no colon (field name only)
  11265. TEST_F(SSEParsingTest, FieldNameOnly) {
  11266. sse::SSEMessage msg;
  11267. int retry_ms = 3000;
  11268. // According to SSE spec, this is treated as field name with empty value
  11269. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11270. // Since we don't recognize "data" without colon, data should be empty
  11271. EXPECT_EQ(msg.data, "");
  11272. }
  11273. // Test: Trailing \r handling
  11274. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11275. sse::SSEMessage msg;
  11276. int retry_ms = 3000;
  11277. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11278. EXPECT_EQ(msg.data, "hello");
  11279. }
  11280. // Test: Unknown fields ignored
  11281. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11282. sse::SSEMessage msg;
  11283. int retry_ms = 3000;
  11284. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11285. EXPECT_EQ(msg.data, "");
  11286. EXPECT_EQ(msg.event, "message");
  11287. }
  11288. // Test: Space after colon is optional
  11289. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11290. sse::SSEMessage msg1, msg2;
  11291. int retry_ms = 3000;
  11292. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11293. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11294. EXPECT_EQ(msg1.data, "hello");
  11295. EXPECT_EQ(msg2.data, "hello");
  11296. }
  11297. // Test: SSEMessage clear
  11298. TEST_F(SSEParsingTest, MessageClear) {
  11299. sse::SSEMessage msg;
  11300. msg.event = "custom";
  11301. msg.data = "some data";
  11302. msg.id = "123";
  11303. msg.clear();
  11304. EXPECT_EQ(msg.event, "message");
  11305. EXPECT_EQ(msg.data, "");
  11306. EXPECT_EQ(msg.id, "");
  11307. }
  11308. // Test: Complete event parsing
  11309. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11310. sse::SSEMessage msg;
  11311. int retry_ms = 3000;
  11312. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11313. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11314. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11315. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11316. // Blank line ends event
  11317. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11318. EXPECT_EQ(msg.event, "notification");
  11319. EXPECT_EQ(msg.id, "evt-42");
  11320. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11321. EXPECT_EQ(retry_ms, 1000);
  11322. }
  11323. //==============================================================================
  11324. // Integration Tests with Server
  11325. //==============================================================================
  11326. class SSEIntegrationTest : public ::testing::Test {
  11327. protected:
  11328. void SetUp() override {
  11329. stop_server_.store(false);
  11330. events_.clear();
  11331. server_ = httplib::detail::make_unique<Server>();
  11332. setup_server();
  11333. start_server();
  11334. }
  11335. void TearDown() override {
  11336. stop_server_.store(true);
  11337. event_cv_.notify_all();
  11338. server_->stop();
  11339. if (server_thread_.joinable()) { server_thread_.join(); }
  11340. }
  11341. void setup_server() {
  11342. // Simple SSE endpoint
  11343. server_->Get("/events", [this](const Request &req, Response &res) {
  11344. auto last_id = req.get_header_value("Last-Event-ID");
  11345. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11346. res.set_chunked_content_provider(
  11347. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11348. std::unique_lock<std::mutex> lock(event_mutex_);
  11349. if (event_cv_.wait_for(
  11350. lock, std::chrono::milliseconds(200), [this] {
  11351. return !events_.empty() || stop_server_.load();
  11352. })) {
  11353. if (stop_server_.load()) { return false; }
  11354. if (!events_.empty()) {
  11355. std::string event = events_.front();
  11356. events_.erase(events_.begin());
  11357. sink.write(event.data(), event.size());
  11358. return true;
  11359. }
  11360. }
  11361. return !stop_server_.load();
  11362. });
  11363. });
  11364. // Endpoint that returns error
  11365. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11366. res.status = 500;
  11367. res.set_content("Internal Server Error", "text/plain");
  11368. });
  11369. // Endpoint for custom event types
  11370. server_->Get("/custom-events", [](const Request &, Response &res) {
  11371. res.set_chunked_content_provider(
  11372. "text/event-stream", [](size_t offset, DataSink &sink) {
  11373. if (offset == 0) {
  11374. std::string event = "event: update\ndata: updated\n\n"
  11375. "event: delete\ndata: deleted\n\n";
  11376. sink.write(event.data(), event.size());
  11377. }
  11378. return false; // End stream after sending
  11379. });
  11380. });
  11381. }
  11382. void start_server() {
  11383. port_ = server_->bind_to_any_port(HOST);
  11384. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11385. // Wait for server to start
  11386. while (!server_->is_running()) {
  11387. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11388. }
  11389. }
  11390. int get_port() const { return port_; }
  11391. void send_event(const std::string &event) {
  11392. std::lock_guard<std::mutex> lock(event_mutex_);
  11393. events_.push_back(event);
  11394. event_cv_.notify_all();
  11395. }
  11396. std::unique_ptr<Server> server_;
  11397. std::thread server_thread_;
  11398. std::mutex event_mutex_;
  11399. std::condition_variable event_cv_;
  11400. std::vector<std::string> events_;
  11401. std::atomic<bool> stop_server_{false};
  11402. std::string last_received_event_id_;
  11403. int port_ = 0;
  11404. };
  11405. // Test: Successful connection and on_open callback
  11406. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11407. // Add a simple endpoint that sends one event and closes
  11408. server_->Get("/simple-event", [](const Request &, Response &res) {
  11409. res.set_chunked_content_provider(
  11410. "text/event-stream", [](size_t offset, DataSink &sink) {
  11411. if (offset == 0) {
  11412. std::string event = "data: hello\n\n";
  11413. sink.write(event.data(), event.size());
  11414. }
  11415. return false; // Close stream after sending
  11416. });
  11417. });
  11418. Client client("localhost", get_port());
  11419. sse::SSEClient sse(client, "/simple-event");
  11420. std::atomic<bool> open_called{false};
  11421. std::atomic<bool> message_received{false};
  11422. sse.on_open([&open_called]() { open_called.store(true); });
  11423. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11424. if (msg.data == "hello") { message_received.store(true); }
  11425. });
  11426. sse.set_reconnect_interval(100);
  11427. sse.set_max_reconnect_attempts(1);
  11428. // Start async
  11429. sse.start_async();
  11430. // Wait for message to be processed
  11431. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11432. sse.stop();
  11433. EXPECT_TRUE(open_called.load());
  11434. EXPECT_TRUE(message_received.load());
  11435. }
  11436. // Test: on_message callback
  11437. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11438. // Endpoint that sends multiple events then closes
  11439. server_->Get("/multi-event", [](const Request &, Response &res) {
  11440. res.set_chunked_content_provider(
  11441. "text/event-stream", [](size_t offset, DataSink &sink) {
  11442. if (offset == 0) {
  11443. std::string events = "data: message1\n\ndata: message2\n\n";
  11444. sink.write(events.data(), events.size());
  11445. }
  11446. return false;
  11447. });
  11448. });
  11449. Client client("localhost", get_port());
  11450. sse::SSEClient sse(client, "/multi-event");
  11451. std::vector<std::string> received_messages;
  11452. std::mutex messages_mutex;
  11453. sse.on_message([&](const sse::SSEMessage &msg) {
  11454. std::lock_guard<std::mutex> lock(messages_mutex);
  11455. received_messages.push_back(msg.data);
  11456. });
  11457. sse.set_reconnect_interval(100);
  11458. sse.set_max_reconnect_attempts(1);
  11459. sse.start_async();
  11460. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11461. sse.stop();
  11462. std::lock_guard<std::mutex> lock(messages_mutex);
  11463. EXPECT_GE(received_messages.size(), 2u);
  11464. if (received_messages.size() >= 2) {
  11465. EXPECT_EQ(received_messages[0], "message1");
  11466. EXPECT_EQ(received_messages[1], "message2");
  11467. }
  11468. }
  11469. // Test: on_event for specific types
  11470. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11471. Client client("localhost", get_port());
  11472. sse::SSEClient sse(client, "/custom-events");
  11473. std::atomic<bool> update_received{false};
  11474. std::atomic<bool> delete_received{false};
  11475. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11476. if (msg.data == "updated") { update_received.store(true); }
  11477. });
  11478. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11479. if (msg.data == "deleted") { delete_received.store(true); }
  11480. });
  11481. sse.set_max_reconnect_attempts(1);
  11482. sse.start_async();
  11483. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11484. sse.stop();
  11485. EXPECT_TRUE(update_received.load());
  11486. EXPECT_TRUE(delete_received.load());
  11487. }
  11488. // Test: on_error callback on connection failure
  11489. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11490. // Connect to a non-existent port
  11491. Client client("localhost", 59999);
  11492. sse::SSEClient sse(client, "/events");
  11493. std::atomic<bool> error_called{false};
  11494. Error received_error = Error::Success;
  11495. sse.on_error([&](Error err) {
  11496. error_called.store(true);
  11497. received_error = err;
  11498. });
  11499. sse.set_reconnect_interval(50);
  11500. sse.set_max_reconnect_attempts(1);
  11501. sse.start_async();
  11502. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11503. sse.stop();
  11504. EXPECT_TRUE(error_called.load());
  11505. EXPECT_NE(received_error, Error::Success);
  11506. }
  11507. // Test: Last-Event-ID header sent on reconnect
  11508. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11509. // Endpoint that sends event with ID
  11510. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11511. res.set_chunked_content_provider(
  11512. "text/event-stream", [](size_t offset, DataSink &sink) {
  11513. if (offset == 0) {
  11514. std::string event = "id: evt-123\ndata: test\n\n";
  11515. sink.write(event.data(), event.size());
  11516. }
  11517. return false;
  11518. });
  11519. });
  11520. Client client("localhost", get_port());
  11521. sse::SSEClient sse(client, "/event-with-id");
  11522. std::atomic<bool> id_received{false};
  11523. sse.on_message([&](const sse::SSEMessage &msg) {
  11524. if (!msg.id.empty()) { id_received.store(true); }
  11525. });
  11526. sse.set_reconnect_interval(100);
  11527. sse.set_max_reconnect_attempts(1);
  11528. sse.start_async();
  11529. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11530. sse.stop();
  11531. EXPECT_TRUE(id_received.load());
  11532. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11533. }
  11534. // Test: Manual stop
  11535. TEST_F(SSEIntegrationTest, ManualStop) {
  11536. // Endpoint that sends one event and stays open briefly
  11537. std::atomic<bool> handler_running{true};
  11538. server_->Get("/stay-open", [&handler_running](const Request &,
  11539. Response &res) {
  11540. res.set_chunked_content_provider(
  11541. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11542. if (offset == 0) {
  11543. std::string event = "data: connected\n\n";
  11544. sink.write(event.data(), event.size());
  11545. }
  11546. // Keep connection open while handler_running is true
  11547. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11548. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11549. }
  11550. return false;
  11551. });
  11552. });
  11553. Client client("localhost", get_port());
  11554. sse::SSEClient sse(client, "/stay-open");
  11555. std::atomic<bool> connected{false};
  11556. sse.on_open([&connected]() { connected.store(true); });
  11557. sse.set_reconnect_interval(100);
  11558. sse.set_max_reconnect_attempts(1);
  11559. sse.start_async();
  11560. // Wait for connection to establish
  11561. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11562. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11563. }
  11564. EXPECT_TRUE(connected.load());
  11565. EXPECT_TRUE(sse.is_connected());
  11566. // Signal handler to stop
  11567. handler_running.store(false);
  11568. // Stop SSE client
  11569. sse.stop();
  11570. EXPECT_FALSE(sse.is_connected());
  11571. }
  11572. // Test: SSEClient with custom headers
  11573. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11574. // Setup a server endpoint that checks for custom header
  11575. std::atomic<bool> header_received{false};
  11576. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11577. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11578. header_received.store(true);
  11579. }
  11580. res.set_chunked_content_provider("text/event-stream",
  11581. [](size_t, DataSink &) { return false; });
  11582. });
  11583. Client client("localhost", get_port());
  11584. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11585. sse::SSEClient sse(client, "/header-check", headers);
  11586. sse.set_max_reconnect_attempts(1);
  11587. sse.start_async();
  11588. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11589. sse.stop();
  11590. EXPECT_TRUE(header_received.load());
  11591. }
  11592. // Test: Reconnect interval configuration
  11593. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11594. Client client("localhost", get_port());
  11595. sse::SSEClient sse(client, "/events");
  11596. auto &result = sse.set_reconnect_interval(500);
  11597. // Builder pattern should return reference to self
  11598. EXPECT_EQ(&result, &sse);
  11599. }
  11600. // Test: Max reconnect attempts
  11601. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11602. // Connect to non-existent port to force reconnects
  11603. Client client("localhost", 59998);
  11604. sse::SSEClient sse(client, "/events");
  11605. std::atomic<int> error_count{0};
  11606. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11607. sse.set_reconnect_interval(50);
  11608. sse.set_max_reconnect_attempts(2);
  11609. auto start = std::chrono::steady_clock::now();
  11610. sse.start(); // Blocking call
  11611. auto end = std::chrono::steady_clock::now();
  11612. // Should have stopped after 2 failed attempts
  11613. EXPECT_GE(error_count.load(), 2);
  11614. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11615. auto duration =
  11616. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11617. #ifdef _WIN32
  11618. // Windows is much slower for socket connection failures
  11619. EXPECT_LT(duration.count(), 7000);
  11620. #else
  11621. EXPECT_LT(duration.count(), 1000);
  11622. #endif
  11623. }
  11624. // Test: Multi-line data in integration
  11625. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11626. // Endpoint with multi-line data
  11627. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11628. res.set_chunked_content_provider(
  11629. "text/event-stream", [](size_t offset, DataSink &sink) {
  11630. if (offset == 0) {
  11631. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11632. sink.write(event.data(), event.size());
  11633. }
  11634. return false;
  11635. });
  11636. });
  11637. Client client("localhost", get_port());
  11638. sse::SSEClient sse(client, "/multiline-data");
  11639. std::string received_data;
  11640. std::mutex data_mutex;
  11641. sse.on_message([&](const sse::SSEMessage &msg) {
  11642. std::lock_guard<std::mutex> lock(data_mutex);
  11643. received_data = msg.data;
  11644. });
  11645. sse.set_reconnect_interval(100);
  11646. sse.set_max_reconnect_attempts(1);
  11647. sse.start_async();
  11648. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11649. sse.stop();
  11650. std::lock_guard<std::mutex> lock(data_mutex);
  11651. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11652. }
  11653. // Test: Auto-reconnect after server disconnection
  11654. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11655. std::atomic<int> connection_count{0};
  11656. std::atomic<int> message_count{0};
  11657. // Endpoint that sends one event and closes, forcing reconnect
  11658. server_->Get("/reconnect-test",
  11659. [&connection_count](const Request &, Response &res) {
  11660. connection_count.fetch_add(1);
  11661. res.set_chunked_content_provider(
  11662. "text/event-stream", [](size_t offset, DataSink &sink) {
  11663. if (offset == 0) {
  11664. std::string event = "data: hello\n\n";
  11665. sink.write(event.data(), event.size());
  11666. }
  11667. return false; // Close connection after sending
  11668. });
  11669. });
  11670. Client client("localhost", get_port());
  11671. sse::SSEClient sse(client, "/reconnect-test");
  11672. sse.on_message([&message_count](const sse::SSEMessage &) {
  11673. message_count.fetch_add(1);
  11674. });
  11675. sse.set_reconnect_interval(100);
  11676. sse.set_max_reconnect_attempts(3);
  11677. sse.start_async();
  11678. // Wait long enough for multiple reconnects
  11679. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11680. sse.stop();
  11681. // Should have connected multiple times (initial + reconnects)
  11682. EXPECT_GE(connection_count.load(), 2);
  11683. // Should have received messages from multiple connections
  11684. EXPECT_GE(message_count.load(), 2);
  11685. }
  11686. // Test: Last-Event-ID sent on reconnect
  11687. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11688. std::atomic<int> connection_count{0};
  11689. std::vector<std::string> received_last_event_ids;
  11690. std::mutex id_mutex;
  11691. // Endpoint that checks Last-Event-ID header and sends event with ID
  11692. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11693. int conn = connection_count.fetch_add(1);
  11694. // Capture the Last-Event-ID header from each connection
  11695. {
  11696. std::lock_guard<std::mutex> lock(id_mutex);
  11697. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11698. }
  11699. res.set_chunked_content_provider(
  11700. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11701. if (offset == 0) {
  11702. std::string event =
  11703. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11704. sink.write(event.data(), event.size());
  11705. }
  11706. return false;
  11707. });
  11708. });
  11709. Client client("localhost", get_port());
  11710. sse::SSEClient sse(client, "/reconnect-with-id");
  11711. sse.set_reconnect_interval(100);
  11712. sse.set_max_reconnect_attempts(3);
  11713. sse.start_async();
  11714. // Wait for at least 2 connections
  11715. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11716. sse.stop();
  11717. // Verify behavior
  11718. std::lock_guard<std::mutex> lock(id_mutex);
  11719. EXPECT_GE(received_last_event_ids.size(), 2u);
  11720. // First connection should have no Last-Event-ID
  11721. if (!received_last_event_ids.empty()) {
  11722. EXPECT_EQ(received_last_event_ids[0], "");
  11723. }
  11724. // Second connection should have Last-Event-ID from first connection
  11725. if (received_last_event_ids.size() >= 2) {
  11726. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11727. }
  11728. }
  11729. TEST(Issue2318Test, EmptyHostString) {
  11730. {
  11731. httplib::Client cli_empty("", PORT);
  11732. auto res = cli_empty.Get("/");
  11733. ASSERT_FALSE(res);
  11734. EXPECT_EQ(httplib::Error::Connection, res.error());
  11735. }
  11736. {
  11737. httplib::Client cli(" ", PORT);
  11738. auto res = cli.Get("/");
  11739. ASSERT_FALSE(res);
  11740. EXPECT_EQ(httplib::Error::Connection, res.error());
  11741. }
  11742. }
  11743. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11744. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  11745. Server svr;
  11746. // Set a small payload limit (1KB)
  11747. svr.set_payload_max_length(1024);
  11748. svr.Post("/test", [&](const Request &req, Response &res) {
  11749. res.set_content("Body size: " + std::to_string(req.body.size()),
  11750. "text/plain");
  11751. });
  11752. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11753. auto se = detail::scope_exit([&] {
  11754. svr.stop();
  11755. listen_thread.join();
  11756. });
  11757. svr.wait_until_ready();
  11758. // Create data that compresses well but exceeds limit when decompressed
  11759. // 8KB of repeated null bytes compresses to a very small size
  11760. std::string original_data(8 * 1024, '\0');
  11761. // Compress the data using gzip
  11762. std::string compressed_data;
  11763. detail::gzip_compressor compressor;
  11764. compressor.compress(original_data.data(), original_data.size(), true,
  11765. [&](const char *data, size_t size) {
  11766. compressed_data.append(data, size);
  11767. return true;
  11768. });
  11769. // Verify compression worked (compressed should be much smaller)
  11770. ASSERT_LT(compressed_data.size(), original_data.size());
  11771. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  11772. // Send compressed data with Content-Encoding: gzip
  11773. Client cli(HOST, PORT);
  11774. Headers headers = {{"Content-Encoding", "gzip"}};
  11775. auto res =
  11776. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  11777. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  11778. ASSERT_TRUE(res);
  11779. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11780. }
  11781. #endif