test.cc 384 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <future>
  18. #include <limits>
  19. #include <memory>
  20. #include <sstream>
  21. #include <stdexcept>
  22. #include <thread>
  23. #include <type_traits>
  24. #include <vector>
  25. #define SERVER_CERT_FILE "./cert.pem"
  26. #define SERVER_CERT2_FILE "./cert2.pem"
  27. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  28. #define CA_CERT_FILE "./ca-bundle.crt"
  29. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  30. #define CLIENT_CA_CERT_DIR "."
  31. #define CLIENT_CERT_FILE "./client.cert.pem"
  32. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  33. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  35. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  36. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  38. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  39. using namespace std;
  40. using namespace httplib;
  41. const char *HOST = "localhost";
  42. const int PORT = 1234;
  43. const string LONG_QUERY_VALUE = string(25000, '@');
  44. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  45. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  46. const string TOO_LONG_QUERY_URL =
  47. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  48. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  49. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  50. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  51. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  52. return file.name == key;
  53. });
  54. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  55. return *it;
  56. #else
  57. if (it != items.end()) { return *it; }
  58. throw std::runtime_error("invalid multipart form data name error");
  59. #endif
  60. }
  61. static void read_file(const std::string &path, std::string &out) {
  62. std::ifstream fs(path, std::ios_base::binary);
  63. if (!fs) throw std::runtime_error("File not found: " + path);
  64. fs.seekg(0, std::ios_base::end);
  65. auto size = fs.tellg();
  66. fs.seekg(0);
  67. out.resize(static_cast<size_t>(size));
  68. fs.read(&out[0], static_cast<std::streamsize>(size));
  69. }
  70. void performance_test(const char *host) {
  71. auto port = 1234;
  72. Server svr;
  73. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  74. res.set_content("Benchmark Response", "text/plain");
  75. });
  76. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  77. auto se = detail::scope_exit([&] {
  78. svr.stop();
  79. listen_thread.join();
  80. ASSERT_FALSE(svr.is_running());
  81. });
  82. svr.wait_until_ready();
  83. Client cli(host, port);
  84. // Warm-up request to establish connection and resolve DNS
  85. auto warmup_res = cli.Get("/benchmark");
  86. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  87. // Run multiple trials and collect timings
  88. const int num_trials = 20;
  89. std::vector<int64_t> timings;
  90. timings.reserve(num_trials);
  91. for (int i = 0; i < num_trials; i++) {
  92. auto start = std::chrono::high_resolution_clock::now();
  93. auto res = cli.Get("/benchmark");
  94. auto end = std::chrono::high_resolution_clock::now();
  95. auto elapsed =
  96. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  97. .count();
  98. // Assertions after timing measurement to avoid overhead
  99. ASSERT_TRUE(res);
  100. EXPECT_EQ(StatusCode::OK_200, res->status);
  101. timings.push_back(elapsed);
  102. }
  103. // Calculate 25th percentile (lower quartile)
  104. std::sort(timings.begin(), timings.end());
  105. auto p25 = timings[num_trials / 4];
  106. // Format timings for output
  107. std::ostringstream timings_str;
  108. timings_str << "[";
  109. for (size_t i = 0; i < timings.size(); i++) {
  110. if (i > 0) timings_str << ", ";
  111. timings_str << timings[i];
  112. }
  113. timings_str << "]";
  114. // Localhost HTTP GET should be fast even in CI environments
  115. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  116. << "ms (Issue #1777). Timings: " << timings_str.str();
  117. }
  118. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  119. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  120. class UnixSocketTest : public ::testing::Test {
  121. protected:
  122. void TearDown() override { std::remove(pathname_.c_str()); }
  123. void client_GET(const std::string &addr) {
  124. httplib::Client cli{addr};
  125. cli.set_address_family(AF_UNIX);
  126. ASSERT_TRUE(cli.is_valid());
  127. const auto &result = cli.Get(pattern_);
  128. ASSERT_TRUE(result) << "error: " << result.error();
  129. const auto &resp = result.value();
  130. EXPECT_EQ(resp.status, StatusCode::OK_200);
  131. EXPECT_EQ(resp.body, content_);
  132. }
  133. const std::string pathname_{"./httplib-server.sock"};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. }
  154. #if defined(__linux__) || \
  155. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  156. TEST_F(UnixSocketTest, PeerPid) {
  157. httplib::Server svr;
  158. std::string remote_port_val;
  159. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. remote_port_val = std::to_string(req.remote_port);
  162. });
  163. std::thread t{[&] {
  164. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  165. }};
  166. auto se = detail::scope_exit([&] {
  167. svr.stop();
  168. t.join();
  169. ASSERT_FALSE(svr.is_running());
  170. });
  171. svr.wait_until_ready();
  172. ASSERT_TRUE(svr.is_running());
  173. client_GET(pathname_);
  174. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  175. }
  176. #endif
  177. #ifdef __linux__
  178. TEST_F(UnixSocketTest, abstract) {
  179. constexpr char svr_path[]{"\x00httplib-server.sock"};
  180. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  181. httplib::Server svr;
  182. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  183. res.set_content(content_, "text/plain");
  184. });
  185. std::thread t{[&] {
  186. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  187. }};
  188. auto se = detail::scope_exit([&] {
  189. svr.stop();
  190. t.join();
  191. ASSERT_FALSE(svr.is_running());
  192. });
  193. svr.wait_until_ready();
  194. ASSERT_TRUE(svr.is_running());
  195. client_GET(abstract_addr);
  196. }
  197. #endif
  198. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  199. httplib::Server svr;
  200. std::string received_host_header;
  201. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  202. // Capture the Host header sent by the client
  203. auto host_iter = req.headers.find("Host");
  204. if (host_iter != req.headers.end()) {
  205. received_host_header = host_iter->second;
  206. }
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. // Test that Host header is automatically set to "localhost" for Unix socket
  220. // connections
  221. httplib::Client cli{pathname_};
  222. cli.set_address_family(AF_UNIX);
  223. ASSERT_TRUE(cli.is_valid());
  224. const auto &result = cli.Get(pattern_);
  225. ASSERT_TRUE(result) << "error: " << result.error();
  226. const auto &resp = result.value();
  227. EXPECT_EQ(resp.status, StatusCode::OK_200);
  228. EXPECT_EQ(resp.body, content_);
  229. // Verify that Host header was automatically set to "localhost"
  230. EXPECT_EQ(received_host_header, "localhost");
  231. }
  232. #ifndef _WIN32
  233. TEST(SocketStream, wait_writable_UNIX) {
  234. int fds[2];
  235. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  236. const auto asSocketStream = [&](socket_t fd,
  237. std::function<bool(Stream &)> func) {
  238. return detail::process_client_socket(
  239. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  240. };
  241. asSocketStream(fds[0], [&](Stream &s0) {
  242. EXPECT_EQ(s0.socket(), fds[0]);
  243. EXPECT_TRUE(s0.wait_writable());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.wait_writable());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(PORT + 1);
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  261. ASSERT_EQ(0, listen(s, 1));
  262. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  263. ASSERT_EQ(0, close(s));
  264. }};
  265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  266. std::thread cli{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, close(s));
  271. }};
  272. cli.join();
  273. svr.join();
  274. ASSERT_NE(disconnected_svr_sock, -1);
  275. const auto asSocketStream = [&](socket_t fd,
  276. std::function<bool(Stream &)> func) {
  277. return detail::process_client_socket(
  278. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  279. };
  280. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  281. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  282. EXPECT_FALSE(ss.wait_writable());
  283. return true;
  284. });
  285. ASSERT_EQ(0, close(disconnected_svr_sock));
  286. }
  287. #endif // #ifndef _WIN32
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. u8"descrip=Gastos áéíóúñÑ 6");
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  317. string unescapedCharacters = "-_.!~*'()";
  318. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  319. }
  320. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  321. string reservedCharacters = ";,/?:@&=+$";
  322. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  323. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  324. }
  325. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  326. string chineseCharacters = u8"中国語";
  327. string russianCharacters = u8"дом";
  328. string brazilianCharacters = u8"óculos";
  329. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  330. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  331. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  332. "%D0%B4%D0%BE%D0%BC");
  333. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  334. }
  335. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  336. string unescapedCharacters = "-_.!~*'()";
  337. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  338. }
  339. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  340. string reservedCharacters = ";,/?:@&=+$";
  341. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  342. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  343. }
  344. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  345. string chineseCharacters = u8"中国語";
  346. string russianCharacters = u8"дом";
  347. string brazilianCharacters = u8"óculos";
  348. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  349. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  350. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  351. "%D0%B4%D0%BE%D0%BC");
  352. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  353. }
  354. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  355. // Issue #2082 use case: encoding path component with ampersand
  356. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  357. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  358. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  359. }
  360. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$#";
  366. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  367. }
  368. TEST(EncodeUriTest, TestUTF8Characters) {
  369. string chineseCharacters = u8"中国語";
  370. string russianCharacters = u8"дом";
  371. string brazilianCharacters = u8"óculos";
  372. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  373. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  374. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  375. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  376. }
  377. TEST(EncodeUriTest, TestCompleteUri) {
  378. string uri =
  379. "https://example.com/path/to/resource?query=value&param=test#fragment";
  380. EXPECT_EQ(
  381. httplib::encode_uri(uri),
  382. "https://example.com/path/to/resource?query=value&param=test#fragment");
  383. }
  384. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  385. string uri =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. EXPECT_EQ(httplib::encode_uri(uri),
  388. "https://example.com/path%20with%20spaces/"
  389. "file%20name.html?q=hello%20world");
  390. }
  391. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  392. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  393. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  394. }
  395. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  400. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  401. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  402. string encodedBrazilian = "%C3%B3culos";
  403. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  404. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  405. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  406. }
  407. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  408. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  409. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  410. "Piri Tommy Villiers - on & on");
  411. }
  412. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  413. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  414. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  415. }
  416. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  418. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  419. }
  420. TEST(DecodeUriTest, TestUTF8Characters) {
  421. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  422. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  423. string encodedBrazilian = "%C3%B3culos";
  424. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  425. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  426. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  427. }
  428. TEST(DecodeUriTest, TestCompleteUri) {
  429. string encodedUri = "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world";
  431. EXPECT_EQ(
  432. httplib::decode_uri(encodedUri),
  433. "https://example.com/path with spaces/file name.html?q=hello world");
  434. }
  435. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  436. string original =
  437. "https://example.com/path with spaces/file name.html?q=hello world";
  438. string encoded = httplib::encode_uri(original);
  439. string decoded = httplib::decode_uri(encoded);
  440. EXPECT_EQ(decoded, original);
  441. }
  442. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  443. string original = "Piri Tommy Villiers - on & on";
  444. string encoded = httplib::encode_uri_component(original);
  445. string decoded = httplib::decode_uri_component(encoded);
  446. EXPECT_EQ(decoded, original);
  447. }
  448. TEST(TrimTests, TrimStringTests) {
  449. EXPECT_EQ("abc", detail::trim_copy("abc"));
  450. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  451. EXPECT_TRUE(detail::trim_copy("").empty());
  452. }
  453. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  454. // Simple case without quality values
  455. std::vector<std::string> result1;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html,application/json,text/plain", result1));
  458. EXPECT_EQ(result1.size(), 3U);
  459. EXPECT_EQ(result1[0], "text/html");
  460. EXPECT_EQ(result1[1], "application/json");
  461. EXPECT_EQ(result1[2], "text/plain");
  462. // With quality values
  463. std::vector<std::string> result2;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  466. EXPECT_EQ(result2.size(), 3U);
  467. EXPECT_EQ(result2[0], "application/json"); // highest q value
  468. EXPECT_EQ(result2[1], "text/html");
  469. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  470. }
  471. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  472. // Mixed with and without quality values
  473. std::vector<std::string> result;
  474. EXPECT_TRUE(detail::parse_accept_header(
  475. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  476. EXPECT_EQ(result.size(), 3U);
  477. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  478. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  479. EXPECT_EQ(result[2], "application/json"); // q=0.5
  480. }
  481. TEST(ParseAcceptHeaderTest, EdgeCases) {
  482. // Empty header
  483. std::vector<std::string> empty_result;
  484. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  485. EXPECT_TRUE(empty_result.empty());
  486. // Single type
  487. std::vector<std::string> single_result;
  488. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  489. EXPECT_EQ(single_result.size(), 1U);
  490. EXPECT_EQ(single_result[0], "application/json");
  491. // Wildcard types
  492. std::vector<std::string> wildcard_result;
  493. EXPECT_TRUE(detail::parse_accept_header(
  494. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  495. EXPECT_EQ(wildcard_result.size(), 3U);
  496. EXPECT_EQ(wildcard_result[0], "application/json");
  497. EXPECT_EQ(wildcard_result[1], "text/*");
  498. EXPECT_EQ(wildcard_result[2], "*/*");
  499. }
  500. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  501. // Common browser Accept header
  502. std::vector<std::string> browser_result;
  503. EXPECT_TRUE(
  504. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  505. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  506. browser_result));
  507. EXPECT_EQ(browser_result.size(), 6U);
  508. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  509. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  510. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  513. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  514. // API client header
  515. std::vector<std::string> api_result;
  516. EXPECT_TRUE(detail::parse_accept_header(
  517. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  518. api_result));
  519. EXPECT_EQ(api_result.size(), 3U);
  520. EXPECT_EQ(api_result[0], "application/json");
  521. EXPECT_EQ(api_result[1], "application/xml");
  522. EXPECT_EQ(api_result[2], "text/plain");
  523. }
  524. TEST(ParseAcceptHeaderTest, SpecialCases) {
  525. // Quality value with 3 decimal places
  526. std::vector<std::string> decimal_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  529. EXPECT_EQ(decimal_result.size(), 2U);
  530. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  531. EXPECT_EQ(decimal_result[1], "text/html");
  532. // Zero quality (should still be included but with lowest priority)
  533. std::vector<std::string> zero_q_result;
  534. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  535. zero_q_result));
  536. EXPECT_EQ(zero_q_result.size(), 2U);
  537. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  538. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  539. // No spaces around commas
  540. std::vector<std::string> no_space_result;
  541. EXPECT_TRUE(detail::parse_accept_header(
  542. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  543. no_space_result));
  544. EXPECT_EQ(no_space_result.size(), 3U);
  545. EXPECT_EQ(no_space_result[0], "text/html");
  546. EXPECT_EQ(no_space_result[1], "application/json");
  547. EXPECT_EQ(no_space_result[2], "text/plain");
  548. }
  549. TEST(ParseAcceptHeaderTest, InvalidCases) {
  550. std::vector<std::string> result;
  551. // Invalid quality value (> 1.0)
  552. EXPECT_FALSE(
  553. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  554. // Invalid quality value (< 0.0)
  555. EXPECT_FALSE(
  556. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  557. // Invalid quality value (not a number)
  558. EXPECT_FALSE(detail::parse_accept_header(
  559. "text/html;q=invalid,application/json", result));
  560. // Empty quality value
  561. EXPECT_FALSE(
  562. detail::parse_accept_header("text/html;q=,application/json", result));
  563. // Invalid media type format (no slash and not wildcard)
  564. EXPECT_FALSE(
  565. detail::parse_accept_header("invalidtype,application/json", result));
  566. // Empty media type
  567. result.clear();
  568. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  569. // Only commas
  570. result.clear();
  571. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  572. // Valid cases should still work
  573. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  574. EXPECT_EQ(result.size(), 1U);
  575. EXPECT_EQ(result[0], "*/*");
  576. EXPECT_TRUE(detail::parse_accept_header("*", result));
  577. EXPECT_EQ(result.size(), 1U);
  578. EXPECT_EQ(result[0], "*");
  579. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  580. EXPECT_EQ(result.size(), 1U);
  581. EXPECT_EQ(result[0], "text/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  584. Server svr;
  585. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  586. EXPECT_EQ(req.accept_content_types.size(), 3U);
  587. EXPECT_EQ(req.accept_content_types[0], "application/json");
  588. EXPECT_EQ(req.accept_content_types[1], "text/html");
  589. EXPECT_EQ(req.accept_content_types[2], "*/*");
  590. res.set_content("ok", "text/plain");
  591. });
  592. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  593. EXPECT_TRUE(false);
  594. res.set_content("bad request", "text/plain");
  595. });
  596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  597. auto se = detail::scope_exit([&] {
  598. svr.stop();
  599. listen_thread.join();
  600. ASSERT_FALSE(svr.is_running());
  601. });
  602. svr.wait_until_ready();
  603. Client cli("localhost", PORT);
  604. {
  605. auto res =
  606. cli.Get("/accept_ok",
  607. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  608. ASSERT_TRUE(res);
  609. EXPECT_EQ(StatusCode::OK_200, res->status);
  610. }
  611. {
  612. auto res = cli.Get("/accept_bad_request",
  613. {{"Accept", "text/html;q=abc,application/json"}});
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  616. }
  617. }
  618. TEST(DivideTest, DivideStringTests) {
  619. auto divide = [](const std::string &str, char d) {
  620. std::string lhs;
  621. std::string rhs;
  622. detail::divide(str, d,
  623. [&](const char *lhs_data, std::size_t lhs_size,
  624. const char *rhs_data, std::size_t rhs_size) {
  625. lhs.assign(lhs_data, lhs_size);
  626. rhs.assign(rhs_data, rhs_size);
  627. });
  628. return std::make_pair(std::move(lhs), std::move(rhs));
  629. };
  630. {
  631. const auto res = divide("", '=');
  632. EXPECT_EQ(res.first, "");
  633. EXPECT_EQ(res.second, "");
  634. }
  635. {
  636. const auto res = divide("=", '=');
  637. EXPECT_EQ(res.first, "");
  638. EXPECT_EQ(res.second, "");
  639. }
  640. {
  641. const auto res = divide(" ", '=');
  642. EXPECT_EQ(res.first, " ");
  643. EXPECT_EQ(res.second, "");
  644. }
  645. {
  646. const auto res = divide("a", '=');
  647. EXPECT_EQ(res.first, "a");
  648. EXPECT_EQ(res.second, "");
  649. }
  650. {
  651. const auto res = divide("a=", '=');
  652. EXPECT_EQ(res.first, "a");
  653. EXPECT_EQ(res.second, "");
  654. }
  655. {
  656. const auto res = divide("=b", '=');
  657. EXPECT_EQ(res.first, "");
  658. EXPECT_EQ(res.second, "b");
  659. }
  660. {
  661. const auto res = divide("a=b", '=');
  662. EXPECT_EQ(res.first, "a");
  663. EXPECT_EQ(res.second, "b");
  664. }
  665. {
  666. const auto res = divide("a=b=", '=');
  667. EXPECT_EQ(res.first, "a");
  668. EXPECT_EQ(res.second, "b=");
  669. }
  670. {
  671. const auto res = divide("a=b=c", '=');
  672. EXPECT_EQ(res.first, "a");
  673. EXPECT_EQ(res.second, "b=c");
  674. }
  675. }
  676. TEST(SplitTest, ParseQueryString) {
  677. string s = "key1=val1&key2=val2&key3=val3";
  678. Params dic;
  679. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  680. [&](const char *b, const char *e) {
  681. string key, val;
  682. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  683. if (key.empty()) {
  684. key.assign(b2, e2);
  685. } else {
  686. val.assign(b2, e2);
  687. }
  688. });
  689. dic.emplace(key, val);
  690. });
  691. EXPECT_EQ("val1", dic.find("key1")->second);
  692. EXPECT_EQ("val2", dic.find("key2")->second);
  693. EXPECT_EQ("val3", dic.find("key3")->second);
  694. }
  695. TEST(SplitTest, ParseInvalidQueryTests) {
  696. {
  697. string s = " ";
  698. Params dict;
  699. detail::parse_query_text(s, dict);
  700. EXPECT_TRUE(dict.empty());
  701. }
  702. {
  703. string s = " = =";
  704. Params dict;
  705. detail::parse_query_text(s, dict);
  706. EXPECT_TRUE(dict.empty());
  707. }
  708. }
  709. TEST(ParseQueryTest, ParseQueryString) {
  710. {
  711. std::string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::parse_query_text(s, dic);
  714. EXPECT_EQ("val1", dic.find("key1")->second);
  715. EXPECT_EQ("val2", dic.find("key2")->second);
  716. EXPECT_EQ("val3", dic.find("key3")->second);
  717. }
  718. {
  719. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  720. Params dic;
  721. detail::parse_query_text(s, dic);
  722. EXPECT_EQ("", dic.find("key1")->second);
  723. EXPECT_EQ("val1", dic.find("key2")->second);
  724. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  725. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  726. }
  727. }
  728. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  729. Params dic;
  730. EXPECT_EQ(detail::params_to_query_str(dic), "");
  731. dic.emplace("key1", "val1");
  732. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  733. dic.emplace("key2", "val2");
  734. dic.emplace("key3", "val3");
  735. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  736. }
  737. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  738. string content_type = "multipart/form-data; boundary=something";
  739. string boundary;
  740. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  741. EXPECT_TRUE(ret);
  742. EXPECT_EQ(boundary, "something");
  743. }
  744. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  745. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  746. string boundary;
  747. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  748. EXPECT_TRUE(ret);
  749. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  750. }
  751. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  752. string content_type =
  753. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  754. string boundary;
  755. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  756. EXPECT_TRUE(ret);
  757. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  758. }
  759. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  760. string content_type =
  761. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  762. string boundary;
  763. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  764. EXPECT_TRUE(ret);
  765. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  766. }
  767. TEST(GetHeaderValueTest, DefaultValue) {
  768. Headers headers = {{"Dummy", "Dummy"}};
  769. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  770. EXPECT_STREQ("text/plain", val);
  771. }
  772. TEST(GetHeaderValueTest, DefaultValueInt) {
  773. Headers headers = {{"Dummy", "Dummy"}};
  774. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  775. EXPECT_EQ(100ull, val);
  776. }
  777. TEST(GetHeaderValueTest, RegularValue) {
  778. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  779. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  780. EXPECT_STREQ("text/html", val);
  781. }
  782. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  783. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  784. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  785. EXPECT_STREQ("text/html", val);
  786. }
  787. TEST(GetHeaderValueTest, SetContent) {
  788. Response res;
  789. res.set_content("html", "text/html");
  790. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  791. res.set_content("text", "text/plain");
  792. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  793. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  794. }
  795. TEST(GetHeaderValueTest, RegularValueInt) {
  796. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  798. EXPECT_EQ(100ull, val);
  799. }
  800. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  801. Headers headers = {{"Content-Length", "x"}};
  802. auto is_invalid_value = false;
  803. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  804. is_invalid_value);
  805. EXPECT_EQ(0ull, val);
  806. EXPECT_TRUE(is_invalid_value);
  807. }
  808. TEST(GetHeaderValueTest, Range) {
  809. {
  810. Headers headers = {make_range_header({{1, -1}})};
  811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  812. EXPECT_STREQ("bytes=1-", val);
  813. }
  814. {
  815. Headers headers = {make_range_header({{-1, 1}})};
  816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  817. EXPECT_STREQ("bytes=-1", val);
  818. }
  819. {
  820. Headers headers = {make_range_header({{1, 10}})};
  821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  822. EXPECT_STREQ("bytes=1-10", val);
  823. }
  824. {
  825. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  827. EXPECT_STREQ("bytes=1-10, 100-", val);
  828. }
  829. {
  830. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  832. EXPECT_STREQ("bytes=1-10, 100-200", val);
  833. }
  834. {
  835. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  837. EXPECT_STREQ("bytes=0-0, -1", val);
  838. }
  839. }
  840. TEST(ParseHeaderValueTest, Range) {
  841. {
  842. Ranges ranges;
  843. auto ret = detail::parse_range_header("bytes=1-", ranges);
  844. EXPECT_TRUE(ret);
  845. EXPECT_EQ(1u, ranges.size());
  846. EXPECT_EQ(1u, ranges[0].first);
  847. EXPECT_EQ(-1, ranges[0].second);
  848. }
  849. {
  850. Ranges ranges;
  851. auto ret = detail::parse_range_header("bytes=-1", ranges);
  852. EXPECT_TRUE(ret);
  853. EXPECT_EQ(1u, ranges.size());
  854. EXPECT_EQ(-1, ranges[0].first);
  855. EXPECT_EQ(1u, ranges[0].second);
  856. }
  857. {
  858. Ranges ranges;
  859. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  860. EXPECT_TRUE(ret);
  861. EXPECT_EQ(1u, ranges.size());
  862. EXPECT_EQ(1u, ranges[0].first);
  863. EXPECT_EQ(10u, ranges[0].second);
  864. }
  865. {
  866. Ranges ranges;
  867. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  868. EXPECT_FALSE(ret);
  869. }
  870. {
  871. Ranges ranges;
  872. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  873. EXPECT_TRUE(ret);
  874. EXPECT_EQ(2u, ranges.size());
  875. EXPECT_EQ(1u, ranges[0].first);
  876. EXPECT_EQ(10u, ranges[0].second);
  877. EXPECT_EQ(100u, ranges[1].first);
  878. EXPECT_EQ(-1, ranges[1].second);
  879. }
  880. {
  881. Ranges ranges;
  882. auto ret =
  883. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  884. EXPECT_TRUE(ret);
  885. EXPECT_EQ(3u, ranges.size());
  886. EXPECT_EQ(1u, ranges[0].first);
  887. EXPECT_EQ(10u, ranges[0].second);
  888. EXPECT_EQ(100u, ranges[1].first);
  889. EXPECT_EQ(200u, ranges[1].second);
  890. EXPECT_EQ(300u, ranges[2].first);
  891. EXPECT_EQ(400u, ranges[2].second);
  892. }
  893. {
  894. Ranges ranges;
  895. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  896. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  897. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  908. EXPECT_TRUE(ranges.empty());
  909. }
  910. }
  911. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  912. Request req;
  913. req.set_header("Accept-Encoding", "gzip");
  914. Response res;
  915. res.set_header("Content-Type", "text/plain");
  916. auto ret = detail::encoding_type(req, res);
  917. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  918. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  919. #else
  920. EXPECT_TRUE(ret == detail::EncodingType::None);
  921. #endif
  922. }
  923. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  924. Request req;
  925. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  926. Response res;
  927. res.set_header("Content-Type", "text/plain");
  928. auto ret = detail::encoding_type(req, res);
  929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  930. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  931. #elif CPPHTTPLIB_ZLIB_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  933. #elif CPPHTTPLIB_ZSTD_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  935. #else
  936. EXPECT_TRUE(ret == detail::EncodingType::None);
  937. #endif
  938. }
  939. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding",
  942. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  943. Response res;
  944. res.set_header("Content-Type", "text/plain");
  945. auto ret = detail::encoding_type(req, res);
  946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  947. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  948. #elif CPPHTTPLIB_ZLIB_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  950. #elif CPPHTTPLIB_ZSTD_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  952. #else
  953. EXPECT_TRUE(ret == detail::EncodingType::None);
  954. #endif
  955. }
  956. TEST(BufferStreamTest, read) {
  957. detail::BufferStream strm1;
  958. Stream &strm = strm1;
  959. EXPECT_EQ(5, strm.write("hello"));
  960. char buf[512];
  961. EXPECT_EQ(2, strm.read(buf, 2));
  962. EXPECT_EQ('h', buf[0]);
  963. EXPECT_EQ('e', buf[1]);
  964. EXPECT_EQ(2, strm.read(buf, 2));
  965. EXPECT_EQ('l', buf[0]);
  966. EXPECT_EQ('l', buf[1]);
  967. EXPECT_EQ(1, strm.read(buf, 1));
  968. EXPECT_EQ('o', buf[0]);
  969. EXPECT_EQ(0, strm.read(buf, 1));
  970. }
  971. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  972. auto host = "www.httpwatch.com";
  973. auto ip = hosted_at(host);
  974. EXPECT_EQ("23.96.13.243", ip);
  975. std::vector<std::string> addrs;
  976. hosted_at(host, addrs);
  977. EXPECT_EQ(1u, addrs.size());
  978. }
  979. #if 0 // It depends on each test environment...
  980. TEST(HostnameToIPConversionTest, YouTube_Online) {
  981. auto host = "www.youtube.com";
  982. std::vector<std::string> addrs;
  983. hosted_at(host, addrs);
  984. EXPECT_EQ(20u, addrs.size());
  985. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  986. EXPECT_TRUE(it != addrs.end());
  987. }
  988. #endif
  989. class ChunkedEncodingTest : public ::testing::Test {
  990. protected:
  991. ChunkedEncodingTest()
  992. : cli_(HOST, PORT)
  993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  994. ,
  995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  996. #endif
  997. {
  998. cli_.set_connection_timeout(2);
  999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1000. cli_.enable_server_certificate_verification(false);
  1001. #endif
  1002. }
  1003. virtual void SetUp() {
  1004. read_file("./image.jpg", image_data_);
  1005. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1006. res.set_content("Hello World!", "text/plain");
  1007. });
  1008. svr_.Get(
  1009. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1010. res.set_chunked_content_provider(
  1011. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1012. size_t remaining = image_data_.size() - offset;
  1013. if (remaining == 0) {
  1014. sink.done();
  1015. } else {
  1016. constexpr size_t CHUNK_SIZE = 1024;
  1017. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1018. sink.write(&image_data_[offset], send_size);
  1019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1020. }
  1021. return true;
  1022. });
  1023. });
  1024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1025. svr_.wait_until_ready();
  1026. }
  1027. virtual void TearDown() {
  1028. svr_.stop();
  1029. if (!request_threads_.empty()) {
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. for (auto &t : request_threads_) {
  1032. t.join();
  1033. }
  1034. }
  1035. t_.join();
  1036. }
  1037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1038. SSLClient cli_;
  1039. SSLServer svr_;
  1040. #else
  1041. Client cli_;
  1042. Server svr_;
  1043. #endif
  1044. thread t_;
  1045. std::vector<thread> request_threads_;
  1046. std::string image_data_;
  1047. };
  1048. TEST_F(ChunkedEncodingTest, NormalGet) {
  1049. auto res = cli_.Get("/chunked");
  1050. ASSERT_TRUE(res);
  1051. std::string out;
  1052. read_file("./image.jpg", out);
  1053. EXPECT_EQ(StatusCode::OK_200, res->status);
  1054. EXPECT_EQ(out, res->body);
  1055. }
  1056. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1057. std::string body;
  1058. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1059. body.append(data, data_length);
  1060. return true;
  1061. });
  1062. ASSERT_TRUE(res);
  1063. std::string out;
  1064. read_file("./image.jpg", out);
  1065. EXPECT_EQ(StatusCode::OK_200, res->status);
  1066. EXPECT_EQ(out, body);
  1067. }
  1068. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1069. std::string body;
  1070. auto res = cli_.Get(
  1071. "/chunked",
  1072. [&](const Response &response) {
  1073. EXPECT_EQ(StatusCode::OK_200, response.status);
  1074. return true;
  1075. },
  1076. [&](const char *data, size_t data_length) {
  1077. body.append(data, data_length);
  1078. return true;
  1079. });
  1080. ASSERT_TRUE(res);
  1081. std::string out;
  1082. read_file("./image.jpg", out);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. EXPECT_EQ(out, body);
  1085. }
  1086. TEST(RangeTest, FromHTTPBin_Online) {
  1087. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1088. auto host = "httpbin.org";
  1089. auto path = std::string{"/range/32"};
  1090. #else
  1091. auto host = "nghttp2.org";
  1092. auto path = std::string{"/httpbin/range/32"};
  1093. #endif
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(5);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{1, -1}})};
  1110. auto res = cli.Get(path, headers);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto res = cli.Get(path, headers);
  1118. ASSERT_TRUE(res);
  1119. EXPECT_EQ("bcdefghijk", res->body);
  1120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 31}})};
  1124. auto res = cli.Get(path, headers);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1127. EXPECT_EQ(StatusCode::OK_200, res->status);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{0, -1}})};
  1131. auto res = cli.Get(path, headers);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{0, 32}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1141. }
  1142. }
  1143. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1144. auto host = "unresolvableaddress.local";
  1145. auto path = std::string{"/"};
  1146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1147. auto port = 443;
  1148. SSLClient cli(host, port);
  1149. #else
  1150. auto port = 80;
  1151. Client cli(host, port);
  1152. #endif
  1153. cli.set_connection_timeout(1);
  1154. {
  1155. auto res = cli.Get(path);
  1156. ASSERT_FALSE(res);
  1157. }
  1158. std::this_thread::sleep_for(std::chrono::seconds(8));
  1159. }
  1160. TEST(ConnectionErrorTest, InvalidHost) {
  1161. auto host = "-abcde.com";
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. auto port = 443;
  1164. SSLClient cli(host, port);
  1165. #else
  1166. auto port = 80;
  1167. Client cli(host, port);
  1168. #endif
  1169. cli.set_connection_timeout(std::chrono::seconds(2));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Connection, res.error());
  1173. }
  1174. TEST(ConnectionErrorTest, InvalidHost2) {
  1175. auto host = "httpbin.org/";
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. SSLClient cli(host);
  1178. #else
  1179. Client cli(host);
  1180. #endif
  1181. cli.set_connection_timeout(std::chrono::seconds(2));
  1182. auto res = cli.Get("/");
  1183. ASSERT_TRUE(!res);
  1184. EXPECT_EQ(Error::Connection, res.error());
  1185. }
  1186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1187. auto host = "httpbin.org/";
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. SSLClient cli(host);
  1190. #else
  1191. Client cli(host);
  1192. #endif
  1193. cli.set_connection_timeout(std::chrono::seconds(2));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(!res);
  1196. stringstream s;
  1197. s << "error code: " << res.error();
  1198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1199. }
  1200. TEST(ConnectionErrorTest, InvalidPort) {
  1201. auto host = "localhost";
  1202. auto port = 44380;
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host, port);
  1205. #else
  1206. Client cli(host, port);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_TRUE(Error::Connection == res.error() ||
  1212. Error::ConnectionTimeout == res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, Timeout_Online) {
  1215. auto host = "google.com";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. auto port = 44380;
  1218. SSLClient cli(host, port);
  1219. #else
  1220. auto port = 8080;
  1221. Client cli(host, port);
  1222. #endif
  1223. cli.set_connection_timeout(std::chrono::seconds(2));
  1224. // only probe one address type so that the error reason
  1225. // correlates to the timed-out IPv4, not the unsupported
  1226. // IPv6 connection attempt
  1227. cli.set_address_family(AF_INET);
  1228. auto res = cli.Get("/");
  1229. ASSERT_TRUE(!res);
  1230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1231. }
  1232. TEST(CancelTest, NoCancel_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpbin.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1249. ASSERT_TRUE(res);
  1250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1251. EXPECT_EQ(StatusCode::OK_200, res->status);
  1252. }
  1253. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1254. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1255. auto host = "httpbin.org";
  1256. auto path = std::string{"/range/32"};
  1257. #else
  1258. auto host = "nghttp2.org";
  1259. auto path = std::string{"/httpbin/range/32"};
  1260. #endif
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Canceled, res.error());
  1272. }
  1273. TEST(CancelTest, WithCancelLargePayload_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpbin.org";
  1276. auto path = std::string{"/range/65536"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/65536"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. uint32_t count = 0;
  1290. auto res =
  1291. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, NoCancelPost) {
  1296. Server svr;
  1297. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return true; });
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ("Hello World!", res->body);
  1314. EXPECT_EQ(StatusCode::OK_200, res->status);
  1315. }
  1316. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1317. Server svr;
  1318. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return false; });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, WithCancelLargePayloadPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content(LARGE_DATA, "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, NoCancelPut) {
  1357. Server svr;
  1358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content("Hello World!", "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return true; });
  1373. ASSERT_TRUE(res);
  1374. EXPECT_EQ("Hello World!", res->body);
  1375. EXPECT_EQ(StatusCode::OK_200, res->status);
  1376. }
  1377. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1378. Server svr;
  1379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, WithCancelLargePayloadPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content(LARGE_DATA, "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, NoCancelPatch) {
  1418. Server svr;
  1419. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content("Hello World!", "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return true; });
  1434. ASSERT_TRUE(res);
  1435. EXPECT_EQ("Hello World!", res->body);
  1436. EXPECT_EQ(StatusCode::OK_200, res->status);
  1437. }
  1438. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1439. Server svr;
  1440. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content("Hello World!", "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content(LARGE_DATA, "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return false; });
  1475. ASSERT_TRUE(!res);
  1476. EXPECT_EQ(Error::Canceled, res.error());
  1477. }
  1478. TEST(CancelTest, NoCancelDelete) {
  1479. Server svr;
  1480. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return true; });
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ("Hello World!", res->body);
  1497. EXPECT_EQ(StatusCode::OK_200, res->status);
  1498. }
  1499. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1500. Server svr;
  1501. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content("Hello World!", "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content(LARGE_DATA, "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return false; });
  1536. ASSERT_TRUE(!res);
  1537. EXPECT_EQ(Error::Canceled, res.error());
  1538. }
  1539. static std::string remove_whitespace(const std::string &input) {
  1540. std::string output;
  1541. output.reserve(input.size());
  1542. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1543. [](unsigned char c) { return !std::isspace(c); });
  1544. return output;
  1545. }
  1546. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1547. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1548. auto host = "httpbin.org";
  1549. auto path = std::string{"/basic-auth/hello/world"};
  1550. #else
  1551. auto host = "nghttp2.org";
  1552. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1553. #endif
  1554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1555. auto port = 443;
  1556. SSLClient cli(host, port);
  1557. #else
  1558. auto port = 80;
  1559. Client cli(host, port);
  1560. #endif
  1561. {
  1562. auto res = cli.Get(path);
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1565. }
  1566. {
  1567. auto res =
  1568. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1571. remove_whitespace(res->body));
  1572. EXPECT_EQ(StatusCode::OK_200, res->status);
  1573. }
  1574. {
  1575. cli.set_basic_auth("hello", "world");
  1576. auto res = cli.Get(path);
  1577. ASSERT_TRUE(res);
  1578. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1579. remove_whitespace(res->body));
  1580. EXPECT_EQ(StatusCode::OK_200, res->status);
  1581. }
  1582. {
  1583. cli.set_basic_auth("hello", "bad");
  1584. auto res = cli.Get(path);
  1585. ASSERT_TRUE(res);
  1586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1587. }
  1588. {
  1589. cli.set_basic_auth("bad", "world");
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. }
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1597. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1598. auto host = "httpbin.org";
  1599. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1600. auto paths = std::vector<std::string>{
  1601. "/digest-auth/auth/hello/world/MD5",
  1602. "/digest-auth/auth/hello/world/SHA-256",
  1603. "/digest-auth/auth/hello/world/SHA-512",
  1604. "/digest-auth/auth-int/hello/world/MD5",
  1605. };
  1606. #else
  1607. auto host = "nghttp2.org";
  1608. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1609. auto paths = std::vector<std::string>{
  1610. "/httpbin/digest-auth/auth/hello/world/MD5",
  1611. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1612. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1613. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1614. };
  1615. #endif
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. {
  1619. auto res = cli.Get(unauth_path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_digest_auth("hello", "world");
  1625. for (const auto &path : paths) {
  1626. auto res = cli.Get(path.c_str());
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. cli.set_digest_auth("hello", "bad");
  1633. for (const auto &path : paths) {
  1634. auto res = cli.Get(path.c_str());
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1637. }
  1638. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1639. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1640. // cli.set_digest_auth("bad", "world");
  1641. // for (const auto& path : paths) {
  1642. // auto res = cli.Get(path.c_str());
  1643. // ASSERT_TRUE(res);
  1644. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1645. // }
  1646. }
  1647. }
  1648. #endif
  1649. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1650. auto host = "google.com";
  1651. auto another_host = "example.com";
  1652. auto wrong_ip = "0.0.0.0";
  1653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. }
  1663. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1664. auto host = "google.com";
  1665. auto wrong_ip = "0.0.0.0";
  1666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1667. SSLClient cli(host);
  1668. #else
  1669. Client cli(host);
  1670. #endif
  1671. cli.set_hostname_addr_map({{host, wrong_ip}});
  1672. auto res = cli.Get("/");
  1673. ASSERT_TRUE(!res);
  1674. EXPECT_EQ(Error::Connection, res.error());
  1675. }
  1676. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1677. auto host = "nghttp2.org";
  1678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1679. SSLClient cli(host);
  1680. #else
  1681. Client cli(host);
  1682. #endif
  1683. cli.set_follow_location(true);
  1684. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(RedirectTest, Redirect_Online) {
  1689. auto host = "nghttp2.org";
  1690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1691. SSLClient cli(host);
  1692. #else
  1693. Client cli(host);
  1694. #endif
  1695. cli.set_follow_location(true);
  1696. auto res = cli.Get("/httpbin/redirect/3");
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(RelativeRedirectTest, Redirect_Online) {
  1701. auto host = "nghttp2.org";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_follow_location(true);
  1708. auto res = cli.Get("/httpbin/relative-redirect/3");
  1709. ASSERT_TRUE(res);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. }
  1712. TEST(TooManyRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/redirect/21");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1723. }
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. TEST(YahooRedirectTest, Redirect_Online) {
  1726. Client cli("yahoo.com");
  1727. auto res = cli.Get("/");
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1730. cli.set_follow_location(true);
  1731. res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(StatusCode::OK_200, res->status);
  1734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1735. }
  1736. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1737. #define REDIR_HOST "httpbingo.org"
  1738. #define REDIR_PATH "/redirect-to"
  1739. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1740. SSLClient cli(REDIR_HOST);
  1741. cli.set_follow_location(true);
  1742. auto res =
  1743. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1748. SSLClient cli(REDIR_HOST);
  1749. cli.set_follow_location(true);
  1750. Params params;
  1751. params.emplace("url", "http://example.com");
  1752. params.emplace("status_code", "302");
  1753. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1758. SSLClient cli(REDIR_HOST);
  1759. cli.set_follow_location(true);
  1760. Params params;
  1761. params.emplace("url", "http://example.com");
  1762. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::OK_200, res->status);
  1765. }
  1766. TEST(UrlWithSpace, Redirect_Online) {
  1767. SSLClient cli("edge.forgecdn.net");
  1768. cli.set_follow_location(true);
  1769. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1773. }
  1774. #endif
  1775. #if !defined(_WIN32) && !defined(_WIN64)
  1776. TEST(ReceiveSignals, Signal) {
  1777. auto setupSignalHandlers = []() {
  1778. struct sigaction act;
  1779. sigemptyset(&act.sa_mask);
  1780. act.sa_flags = SA_SIGINFO;
  1781. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1782. switch (sig) {
  1783. case SIGINT:
  1784. default: break;
  1785. }
  1786. };
  1787. ::sigaction(SIGINT, &act, nullptr);
  1788. };
  1789. Server svr;
  1790. int port = 0;
  1791. auto thread = std::thread([&]() {
  1792. setupSignalHandlers();
  1793. port = svr.bind_to_any_port("localhost");
  1794. svr.listen_after_bind();
  1795. });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. thread.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. svr.wait_until_ready();
  1802. ASSERT_TRUE(svr.is_running());
  1803. pthread_kill(thread.native_handle(), SIGINT);
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1805. ASSERT_TRUE(svr.is_running());
  1806. }
  1807. #endif
  1808. TEST(RedirectToDifferentPort, Redirect) {
  1809. Server svr1;
  1810. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1811. res.set_content("Hello World!", "text/plain");
  1812. });
  1813. int svr1_port = 0;
  1814. auto thread1 = std::thread([&]() {
  1815. svr1_port = svr1.bind_to_any_port("localhost");
  1816. svr1.listen_after_bind();
  1817. });
  1818. Server svr2;
  1819. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1820. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1821. });
  1822. int svr2_port = 0;
  1823. auto thread2 = std::thread([&]() {
  1824. svr2_port = svr2.bind_to_any_port("localhost");
  1825. svr2.listen_after_bind();
  1826. });
  1827. auto se = detail::scope_exit([&] {
  1828. svr2.stop();
  1829. thread2.join();
  1830. svr1.stop();
  1831. thread1.join();
  1832. ASSERT_FALSE(svr2.is_running());
  1833. ASSERT_FALSE(svr1.is_running());
  1834. });
  1835. svr1.wait_until_ready();
  1836. svr2.wait_until_ready();
  1837. Client cli("localhost", svr2_port);
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/2");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("Hello World!", res->body);
  1843. }
  1844. TEST(RedirectFromPageWithContent, Redirect) {
  1845. Server svr;
  1846. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("___", "text/plain");
  1848. res.set_redirect("/2");
  1849. });
  1850. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. th.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli("localhost", PORT);
  1862. cli.set_follow_location(true);
  1863. std::string body;
  1864. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1865. body.append(data, data_length);
  1866. return true;
  1867. });
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", body);
  1871. }
  1872. {
  1873. Client cli("localhost", PORT);
  1874. std::string body;
  1875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1876. body.append(data, data_length);
  1877. return true;
  1878. });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(StatusCode::Found_302, res->status);
  1881. EXPECT_EQ("___", body);
  1882. }
  1883. }
  1884. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1885. Server svr;
  1886. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("___", "text/plain");
  1888. // res.set_redirect("/2");
  1889. res.set_redirect("http://[::1]:1234/2");
  1890. });
  1891. svr.Get("/2", [&](const Request &req, Response &res) {
  1892. auto host_header = req.headers.find("Host");
  1893. ASSERT_TRUE(host_header != req.headers.end());
  1894. EXPECT_EQ("[::1]:1234", host_header->second);
  1895. res.set_content("Hello World!", "text/plain");
  1896. });
  1897. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. th.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1904. // actually starts anything, so the condition !svr.is_running() will
  1905. // always remain true, and the loop never stops.
  1906. // This basically counts how many milliseconds have passed since the
  1907. // call to svr.listen(), and if after 5 seconds nothing started yet
  1908. // aborts the test.
  1909. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1911. ASSERT_LT(milliseconds, 5000U);
  1912. }
  1913. {
  1914. Client cli("http://[::1]:1234");
  1915. cli.set_follow_location(true);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ("Hello World!", body);
  1924. }
  1925. {
  1926. Client cli("http://[::1]:1234");
  1927. std::string body;
  1928. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1929. body.append(data, data_length);
  1930. return true;
  1931. });
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::Found_302, res->status);
  1934. EXPECT_EQ("___", body);
  1935. }
  1936. }
  1937. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1938. Server svr;
  1939. svr.Get("/foo", [](const Request &req, Response &res) {
  1940. auto a = req.params.find("a");
  1941. if (a != req.params.end()) {
  1942. res.set_content((*a).second, "text/plain");
  1943. res.status = StatusCode::OK_200;
  1944. } else {
  1945. res.status = StatusCode::BadRequest_400;
  1946. }
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. cli.set_path_encode(false);
  1958. auto res = cli.Get("/foo?a=explicitly+encoded");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // This expects it back with a space, as the `+` won't have been
  1962. // url-encoded, and server-side the params get decoded turning `+`
  1963. // into spaces.
  1964. EXPECT_EQ("explicitly encoded", res->body);
  1965. }
  1966. }
  1967. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1968. Server svr;
  1969. svr.Get("/", [](const Request &req, Response &) {
  1970. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_path_encode(false);
  1982. auto res = cli.Get("/?something=%0A");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. }
  1987. TEST(BindServerTest, DISABLED_BindDualStack) {
  1988. Server svr;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("Hello World!", "text/plain");
  1991. });
  1992. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1993. auto se = detail::scope_exit([&] {
  1994. svr.stop();
  1995. thread.join();
  1996. ASSERT_FALSE(svr.is_running());
  1997. });
  1998. svr.wait_until_ready();
  1999. {
  2000. Client cli("127.0.0.1", PORT);
  2001. auto res = cli.Get("/1");
  2002. ASSERT_TRUE(res);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ("Hello World!", res->body);
  2005. }
  2006. {
  2007. Client cli("::1", PORT);
  2008. auto res = cli.Get("/1");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", res->body);
  2012. }
  2013. }
  2014. TEST(BindServerTest, BindAndListenSeparately) {
  2015. Server svr;
  2016. int port = svr.bind_to_any_port("0.0.0.0");
  2017. ASSERT_TRUE(svr.is_valid());
  2018. ASSERT_TRUE(port > 0);
  2019. svr.stop();
  2020. }
  2021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2022. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2024. CLIENT_CA_CERT_DIR);
  2025. int port = svr.bind_to_any_port("0.0.0.0");
  2026. ASSERT_TRUE(svr.is_valid());
  2027. ASSERT_TRUE(port > 0);
  2028. svr.stop();
  2029. }
  2030. #endif
  2031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2032. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2033. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2034. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2035. int port = svr.bind_to_any_port("0.0.0.0");
  2036. ASSERT_TRUE(svr.is_valid());
  2037. ASSERT_TRUE(port > 0);
  2038. svr.stop();
  2039. }
  2040. #endif
  2041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2042. X509 *readCertificate(const std::string &strFileName) {
  2043. std::ifstream inStream(strFileName);
  2044. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2045. std::istreambuf_iterator<char>());
  2046. if (strCertPEM.empty()) return (nullptr);
  2047. BIO *pbCert = BIO_new(BIO_s_mem());
  2048. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2049. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2050. BIO_free(pbCert);
  2051. return (pCert);
  2052. }
  2053. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2054. std::ifstream inStream(strFileName);
  2055. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2056. std::istreambuf_iterator<char>());
  2057. if (strPrivateKeyPEM.empty()) return (nullptr);
  2058. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2059. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2060. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2061. BIO_free(pbPrivKey);
  2062. return (pPrivateKey);
  2063. }
  2064. TEST(BindServerTest, UpdateCerts) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2070. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2071. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2072. ASSERT_TRUE(cert != nullptr);
  2073. ASSERT_TRUE(ca_cert != nullptr);
  2074. ASSERT_TRUE(key != nullptr);
  2075. X509_STORE *cert_store = X509_STORE_new();
  2076. X509_STORE_add_cert(cert_store, ca_cert);
  2077. svr.update_certs(cert, key, cert_store);
  2078. ASSERT_TRUE(svr.is_valid());
  2079. svr.stop();
  2080. X509_free(cert);
  2081. X509_free(ca_cert);
  2082. EVP_PKEY_free(key);
  2083. }
  2084. #endif
  2085. TEST(ErrorHandlerTest, ContentLength) {
  2086. Server svr;
  2087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2088. res.status = StatusCode::OK_200;
  2089. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2090. "text/html"); // <= Content-Length still 13
  2091. });
  2092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!\n", "text/plain");
  2094. res.status = 524;
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. {
  2104. Client cli(HOST, PORT);
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::OK_200, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. }
  2113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2114. TEST(ExceptionTest, WithoutExceptionHandler) {
  2115. Server svr;
  2116. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2117. throw std::runtime_error("exception...");
  2118. });
  2119. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2120. throw std::runtime_error("exception\r\n...");
  2121. });
  2122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2123. auto se = detail::scope_exit([&] {
  2124. svr.stop();
  2125. listen_thread.join();
  2126. ASSERT_FALSE(svr.is_running());
  2127. });
  2128. svr.wait_until_ready();
  2129. Client cli("localhost", PORT);
  2130. {
  2131. auto res = cli.Get("/exception");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2135. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2136. }
  2137. {
  2138. auto res = cli.Get("/unknown");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2141. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2142. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2143. }
  2144. }
  2145. TEST(ExceptionTest, WithExceptionHandler) {
  2146. Server svr;
  2147. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2148. std::exception_ptr ep) {
  2149. EXPECT_FALSE(ep == nullptr);
  2150. try {
  2151. std::rethrow_exception(ep);
  2152. } catch (std::exception &e) {
  2153. EXPECT_EQ("abc", std::string(e.what()));
  2154. } catch (...) {}
  2155. res.status = StatusCode::InternalServerError_500;
  2156. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2157. "text/html"); // <= Content-Length still 13 at this point
  2158. });
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!\n", "text/plain");
  2161. throw std::runtime_error("abc");
  2162. });
  2163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. for (size_t i = 0; i < 10; i++) {
  2171. Client cli(HOST, PORT);
  2172. for (size_t j = 0; j < 100; j++) {
  2173. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2179. }
  2180. cli.set_keep_alive(true);
  2181. for (size_t j = 0; j < 100; j++) {
  2182. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2186. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2187. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2188. }
  2189. }
  2190. }
  2191. TEST(ExceptionTest, AndErrorHandler) {
  2192. Server svr;
  2193. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2194. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2195. });
  2196. svr.set_exception_handler(
  2197. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. res.set_content(e.what(), "text/html");
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. });
  2206. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2207. throw std::runtime_error("EXCEPTION");
  2208. });
  2209. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2210. res.set_content("ERROR", "text/html");
  2211. res.status = StatusCode::InternalServerError_500;
  2212. });
  2213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2214. auto se = detail::scope_exit([&] {
  2215. svr.stop();
  2216. thread.join();
  2217. ASSERT_FALSE(svr.is_running());
  2218. });
  2219. svr.wait_until_ready();
  2220. Client cli(HOST, PORT);
  2221. {
  2222. auto res = cli.Get("/exception");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2225. EXPECT_EQ("EXCEPTION", res->body);
  2226. }
  2227. {
  2228. auto res = cli.Get("/error");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2231. EXPECT_EQ("ERROR", res->body);
  2232. }
  2233. {
  2234. auto res = cli.Get("/invalid");
  2235. ASSERT_TRUE(res);
  2236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2237. EXPECT_EQ("NOT_FOUND", res->body);
  2238. }
  2239. }
  2240. #endif
  2241. TEST(NoContentTest, ContentLength) {
  2242. Server svr;
  2243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2244. res.status = StatusCode::NoContent_204;
  2245. });
  2246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2247. auto se = detail::scope_exit([&] {
  2248. svr.stop();
  2249. thread.join();
  2250. ASSERT_FALSE(svr.is_running());
  2251. });
  2252. svr.wait_until_ready();
  2253. {
  2254. Client cli(HOST, PORT);
  2255. auto res = cli.Get("/hi");
  2256. ASSERT_TRUE(res);
  2257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2259. }
  2260. }
  2261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2264. ASSERT_TRUE(svr.is_valid());
  2265. #else
  2266. Server svr;
  2267. #endif
  2268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2269. if (req.path == "/routing_handler") {
  2270. res.set_header("PRE_ROUTING", "on");
  2271. res.set_content("Routing Handler", "text/plain");
  2272. return httplib::Server::HandlerResponse::Handled;
  2273. }
  2274. return httplib::Server::HandlerResponse::Unhandled;
  2275. });
  2276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2277. res.set_content("Error", "text/html");
  2278. });
  2279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2280. if (req.path == "/routing_handler") {
  2281. res.set_header("POST_ROUTING", "on");
  2282. }
  2283. });
  2284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!\n", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. {
  2295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2296. SSLClient cli(HOST, PORT);
  2297. cli.enable_server_certificate_verification(false);
  2298. #else
  2299. Client cli(HOST, PORT);
  2300. #endif
  2301. auto res = cli.Get("/routing_handler");
  2302. ASSERT_TRUE(res);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ("Routing Handler", res->body);
  2305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2309. }
  2310. {
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli(HOST, PORT);
  2313. cli.enable_server_certificate_verification(false);
  2314. #else
  2315. Client cli(HOST, PORT);
  2316. #endif
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!\n", res->body);
  2321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2323. }
  2324. {
  2325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2326. SSLClient cli(HOST, PORT);
  2327. cli.enable_server_certificate_verification(false);
  2328. #else
  2329. Client cli(HOST, PORT);
  2330. #endif
  2331. auto res = cli.Get("/aaa");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2334. EXPECT_EQ("Error", res->body);
  2335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2337. }
  2338. }
  2339. TEST(RequestHandlerTest, PreRequestHandler) {
  2340. auto route_path = "/user/:user";
  2341. Server svr;
  2342. svr.Get("/hi", [](const Request &, Response &res) {
  2343. res.set_content("hi", "text/plain");
  2344. });
  2345. svr.Get(route_path, [](const Request &req, Response &res) {
  2346. res.set_content(req.path_params.at("user"), "text/plain");
  2347. });
  2348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2349. if (req.matched_route == route_path) {
  2350. auto user = req.path_params.at("user");
  2351. if (user != "john") {
  2352. res.status = StatusCode::Forbidden_403;
  2353. res.set_content("error", "text/html");
  2354. return Server::HandlerResponse::Handled;
  2355. }
  2356. }
  2357. return Server::HandlerResponse::Unhandled;
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. {
  2368. auto res = cli.Get("/hi");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. EXPECT_EQ("hi", res->body);
  2372. }
  2373. {
  2374. auto res = cli.Get("/user/john");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("john", res->body);
  2378. }
  2379. {
  2380. auto res = cli.Get("/user/invalid-user");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2383. EXPECT_EQ("error", res->body);
  2384. }
  2385. }
  2386. TEST(InvalidFormatTest, StatusCode) {
  2387. Server svr;
  2388. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2389. res.set_content("Hello World!\n", "text/plain");
  2390. res.status = 9999; // Status should be a three-digit code...
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. {
  2400. Client cli(HOST, PORT);
  2401. auto res = cli.Get("/hi");
  2402. ASSERT_FALSE(res);
  2403. }
  2404. }
  2405. TEST(URLFragmentTest, WithFragment) {
  2406. Server svr;
  2407. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2408. EXPECT_TRUE(req.target == "/hi");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. {
  2418. Client cli(HOST, PORT);
  2419. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2420. EXPECT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. res = cli.Get("/hi%23key1=val1=key2=val2");
  2423. EXPECT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2425. }
  2426. }
  2427. TEST(HeaderWriter, SetHeaderWriter) {
  2428. Server svr;
  2429. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2430. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2431. return detail::write_headers(strm, hdrs);
  2432. });
  2433. svr.Get("/hi", [](const Request &req, Response &res) {
  2434. auto it = req.headers.find("CustomClientHeader");
  2435. EXPECT_TRUE(it != req.headers.end());
  2436. EXPECT_EQ(it->second, "CustomClientValue");
  2437. res.set_content("Hello World!\n", "text/plain");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2449. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2450. return detail::write_headers(strm, hdrs);
  2451. });
  2452. auto res = cli.Get("/hi");
  2453. EXPECT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::OK_200, res->status);
  2455. auto it = res->headers.find("CustomServerHeader");
  2456. EXPECT_TRUE(it != res->headers.end());
  2457. EXPECT_EQ(it->second, "CustomServerValue");
  2458. }
  2459. }
  2460. class ServerTest : public ::testing::Test {
  2461. protected:
  2462. ServerTest()
  2463. : cli_(HOST, PORT)
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. ,
  2466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2467. #endif
  2468. {
  2469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2470. cli_.enable_server_certificate_verification(false);
  2471. #endif
  2472. }
  2473. virtual void SetUp() {
  2474. svr_.set_mount_point("/", "./www");
  2475. svr_.set_mount_point("/mount", "./www2");
  2476. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2477. svr_.Get("/hi",
  2478. [&](const Request & /*req*/, Response &res) {
  2479. res.set_content("Hello World!", "text/plain");
  2480. })
  2481. .Get("/file_content",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_file_content("./www/dir/test.html");
  2484. })
  2485. .Get("/file_content_with_content_type",
  2486. [&](const Request & /*req*/, Response &res) {
  2487. res.set_file_content("./www/file", "text/plain");
  2488. })
  2489. .Get("/invalid_file_content",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_file_content("./www/dir/invalid_file_path");
  2492. })
  2493. .Get("/http_response_splitting",
  2494. [&](const Request & /*req*/, Response &res) {
  2495. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2496. EXPECT_EQ(0U, res.headers.size());
  2497. EXPECT_FALSE(res.has_header("a"));
  2498. res.set_header("a", "1\nSet-Cookie: a=1");
  2499. EXPECT_EQ(0U, res.headers.size());
  2500. EXPECT_FALSE(res.has_header("a"));
  2501. res.set_header("a", "1\rSet-Cookie: a=1");
  2502. EXPECT_EQ(0U, res.headers.size());
  2503. EXPECT_FALSE(res.has_header("a"));
  2504. res.set_header("a\r\nb", "0");
  2505. EXPECT_EQ(0U, res.headers.size());
  2506. EXPECT_FALSE(res.has_header("a"));
  2507. res.set_header("a\rb", "0");
  2508. EXPECT_EQ(0U, res.headers.size());
  2509. EXPECT_FALSE(res.has_header("a"));
  2510. res.set_header("a\nb", "0");
  2511. EXPECT_EQ(0U, res.headers.size());
  2512. EXPECT_FALSE(res.has_header("a"));
  2513. res.set_redirect("1\r\nSet-Cookie: a=1");
  2514. EXPECT_EQ(0U, res.headers.size());
  2515. EXPECT_FALSE(res.has_header("Location"));
  2516. })
  2517. .Get("/slow",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. std::this_thread::sleep_for(std::chrono::seconds(2));
  2520. res.set_content("slow", "text/plain");
  2521. })
  2522. #if 0
  2523. .Post("/slowpost",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. std::this_thread::sleep_for(std::chrono::seconds(2));
  2526. res.set_content("slow", "text/plain");
  2527. })
  2528. #endif
  2529. .Get("/remote_addr",
  2530. [&](const Request &req, Response &res) {
  2531. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2532. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2533. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2534. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2535. res.set_content(req.remote_addr, "text/plain");
  2536. })
  2537. .Get("/local_addr",
  2538. [&](const Request &req, Response &res) {
  2539. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2540. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2541. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2542. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2543. auto local_addr = req.local_addr;
  2544. auto local_port = std::to_string(req.local_port);
  2545. res.set_content(local_addr.append(":").append(local_port),
  2546. "text/plain");
  2547. })
  2548. .Get("/endwith%",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. })
  2552. .Get("/a\\+\\+b",
  2553. [&](const Request &req, Response &res) {
  2554. ASSERT_TRUE(req.has_param("a +b"));
  2555. auto val = req.get_param_value("a +b");
  2556. res.set_content(val, "text/plain");
  2557. })
  2558. .Get("/", [&](const Request & /*req*/,
  2559. Response &res) { res.set_redirect("/hi"); })
  2560. .Post("/1",
  2561. [](const Request & /*req*/, Response &res) {
  2562. res.set_redirect("/2", StatusCode::SeeOther_303);
  2563. })
  2564. .Get("/2",
  2565. [](const Request & /*req*/, Response &res) {
  2566. res.set_content("redirected.", "text/plain");
  2567. res.status = StatusCode::OK_200;
  2568. })
  2569. .Post("/person",
  2570. [&](const Request &req, Response &res) {
  2571. if (req.has_param("name") && req.has_param("note")) {
  2572. persons_[req.get_param_value("name")] =
  2573. req.get_param_value("note");
  2574. } else {
  2575. res.status = StatusCode::BadRequest_400;
  2576. }
  2577. })
  2578. .Put("/person",
  2579. [&](const Request &req, Response &res) {
  2580. if (req.has_param("name") && req.has_param("note")) {
  2581. persons_[req.get_param_value("name")] =
  2582. req.get_param_value("note");
  2583. } else {
  2584. res.status = StatusCode::BadRequest_400;
  2585. }
  2586. })
  2587. .Get("/person/(.*)",
  2588. [&](const Request &req, Response &res) {
  2589. string name = req.matches[1];
  2590. if (persons_.find(name) != persons_.end()) {
  2591. auto note = persons_[name];
  2592. res.set_content(note, "text/plain");
  2593. } else {
  2594. res.status = StatusCode::NotFound_404;
  2595. }
  2596. })
  2597. .Delete("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name")) {
  2600. string name = req.get_param_value("name");
  2601. if (persons_.find(name) != persons_.end()) {
  2602. persons_.erase(name);
  2603. res.set_content("DELETED", "text/plain");
  2604. } else {
  2605. res.status = StatusCode::NotFound_404;
  2606. }
  2607. } else {
  2608. res.status = StatusCode::BadRequest_400;
  2609. }
  2610. })
  2611. .Post("/x-www-form-urlencoded-json",
  2612. [&](const Request &req, Response &res) {
  2613. auto json = req.get_param_value("json");
  2614. ASSERT_EQ(JSON_DATA, json);
  2615. res.set_content(json, "appliation/json");
  2616. res.status = StatusCode::OK_200;
  2617. })
  2618. .Get("/streamed-chunked",
  2619. [&](const Request & /*req*/, Response &res) {
  2620. res.set_chunked_content_provider(
  2621. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2622. sink.os << "123";
  2623. sink.os << "456";
  2624. sink.os << "789";
  2625. sink.done();
  2626. return true;
  2627. });
  2628. })
  2629. .Get("/streamed-chunked-with-prohibited-trailer",
  2630. [&](const Request & /*req*/, Response &res) {
  2631. auto i = new int(0);
  2632. // Declare both a prohibited trailer (Content-Length) and an
  2633. // allowed one
  2634. res.set_header("Trailer", "Content-Length, X-Allowed");
  2635. res.set_chunked_content_provider(
  2636. "text/plain",
  2637. [i](size_t /*offset*/, DataSink &sink) {
  2638. switch (*i) {
  2639. case 0: sink.os << "123"; break;
  2640. case 1: sink.os << "456"; break;
  2641. case 2: sink.os << "789"; break;
  2642. case 3: {
  2643. sink.done_with_trailer(
  2644. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2645. } break;
  2646. }
  2647. (*i)++;
  2648. return true;
  2649. },
  2650. [i](bool success) {
  2651. EXPECT_TRUE(success);
  2652. delete i;
  2653. });
  2654. })
  2655. .Get("/streamed-chunked2",
  2656. [&](const Request & /*req*/, Response &res) {
  2657. auto i = new int(0);
  2658. res.set_chunked_content_provider(
  2659. "text/plain",
  2660. [i](size_t /*offset*/, DataSink &sink) {
  2661. switch (*i) {
  2662. case 0: sink.os << "123"; break;
  2663. case 1: sink.os << "456"; break;
  2664. case 2: sink.os << "789"; break;
  2665. case 3: sink.done(); break;
  2666. }
  2667. (*i)++;
  2668. return true;
  2669. },
  2670. [i](bool success) {
  2671. EXPECT_TRUE(success);
  2672. delete i;
  2673. });
  2674. })
  2675. .Get("/streamed-chunked-with-trailer",
  2676. [&](const Request & /*req*/, Response &res) {
  2677. auto i = new int(0);
  2678. res.set_header("Trailer", "Dummy1, Dummy2");
  2679. res.set_chunked_content_provider(
  2680. "text/plain",
  2681. [i](size_t /*offset*/, DataSink &sink) {
  2682. switch (*i) {
  2683. case 0: sink.os << "123"; break;
  2684. case 1: sink.os << "456"; break;
  2685. case 2: sink.os << "789"; break;
  2686. case 3: {
  2687. sink.done_with_trailer(
  2688. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2689. } break;
  2690. }
  2691. (*i)++;
  2692. return true;
  2693. },
  2694. [i](bool success) {
  2695. EXPECT_TRUE(success);
  2696. delete i;
  2697. });
  2698. })
  2699. .Get("/streamed",
  2700. [&](const Request & /*req*/, Response &res) {
  2701. res.set_content_provider(
  2702. 6, "text/plain",
  2703. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2704. sink.os << (offset < 3 ? "a" : "b");
  2705. return true;
  2706. });
  2707. })
  2708. .Get("/streamed-with-range",
  2709. [&](const Request &req, Response &res) {
  2710. auto data = new std::string("abcdefg");
  2711. res.set_content_provider(
  2712. data->size(), "text/plain",
  2713. [data](size_t offset, size_t length, DataSink &sink) {
  2714. size_t DATA_CHUNK_SIZE = 4;
  2715. const auto &d = *data;
  2716. auto out_len =
  2717. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2718. auto ret =
  2719. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2720. EXPECT_TRUE(ret);
  2721. return true;
  2722. },
  2723. [data, &req](bool success) {
  2724. EXPECT_EQ(success, !req.has_param("error"));
  2725. delete data;
  2726. });
  2727. })
  2728. .Get("/streamed-cancel",
  2729. [&](const Request & /*req*/, Response &res) {
  2730. res.set_content_provider(
  2731. size_t(-1), "text/plain",
  2732. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2733. sink.os << "data_chunk";
  2734. return true;
  2735. });
  2736. })
  2737. .Get("/regex-with-delimiter",
  2738. [&](const Request &req, Response & /*res*/) {
  2739. ASSERT_TRUE(req.has_param("key"));
  2740. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2741. })
  2742. .Get("/with-range",
  2743. [&](const Request & /*req*/, Response &res) {
  2744. res.set_content("abcdefg", "text/plain");
  2745. })
  2746. .Get("/test-start-time",
  2747. [&](const Request &req, Response & /*res*/) {
  2748. EXPECT_NE(req.start_time_,
  2749. std::chrono::steady_clock::time_point::min());
  2750. })
  2751. .Get("/with-range-customized-response",
  2752. [&](const Request & /*req*/, Response &res) {
  2753. res.status = StatusCode::BadRequest_400;
  2754. res.set_content(JSON_DATA, "application/json");
  2755. })
  2756. .Post("/chunked",
  2757. [&](const Request &req, Response & /*res*/) {
  2758. EXPECT_EQ(req.body, "dechunked post body");
  2759. })
  2760. .Post("/large-chunked",
  2761. [&](const Request &req, Response & /*res*/) {
  2762. std::string expected(6 * 30 * 1024u, 'a');
  2763. EXPECT_EQ(req.body, expected);
  2764. })
  2765. .Post("/multipart",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2768. req.form.get_field_count("text2") +
  2769. req.form.get_field_count("file3") +
  2770. req.form.get_field_count("file4"));
  2771. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2772. req.form.get_file_count("file2"));
  2773. ASSERT_TRUE(!req.form.has_file("???"));
  2774. ASSERT_TRUE(!req.form.has_field("???"));
  2775. ASSERT_TRUE(req.body.empty());
  2776. {
  2777. const auto &text = req.form.get_field("text1");
  2778. EXPECT_EQ("text default", text);
  2779. }
  2780. {
  2781. const auto &text = req.form.get_field("text2");
  2782. EXPECT_EQ("aωb", text);
  2783. }
  2784. {
  2785. const auto &file = req.form.get_file("file1");
  2786. EXPECT_EQ("hello.txt", file.filename);
  2787. EXPECT_EQ("text/plain", file.content_type);
  2788. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2789. }
  2790. {
  2791. const auto &file = req.form.get_file("file2");
  2792. EXPECT_EQ("world.json", file.filename);
  2793. EXPECT_EQ("application/json", file.content_type);
  2794. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2795. }
  2796. {
  2797. const auto &text = req.form.get_field("file3");
  2798. EXPECT_EQ(0u, text.size());
  2799. }
  2800. {
  2801. const auto &text = req.form.get_field("file4");
  2802. EXPECT_EQ(0u, text.size());
  2803. }
  2804. })
  2805. .Post("/multipart/multi_file_values",
  2806. [&](const Request &req, Response & /*res*/) {
  2807. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2808. req.form.get_field_count("multi_text1"));
  2809. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2810. ASSERT_TRUE(!req.form.has_file("???"));
  2811. ASSERT_TRUE(!req.form.has_field("???"));
  2812. ASSERT_TRUE(req.body.empty());
  2813. {
  2814. const auto &text = req.form.get_field("text");
  2815. EXPECT_EQ("default text", text);
  2816. }
  2817. {
  2818. const auto &text1_values = req.form.get_fields("multi_text1");
  2819. EXPECT_EQ(2u, text1_values.size());
  2820. EXPECT_EQ("aaaaa", text1_values[0]);
  2821. EXPECT_EQ("bbbbb", text1_values[1]);
  2822. }
  2823. {
  2824. const auto &file1_values = req.form.get_files("multi_file1");
  2825. EXPECT_EQ(2u, file1_values.size());
  2826. auto file1 = file1_values[0];
  2827. EXPECT_EQ(file1.filename, "hello.txt");
  2828. EXPECT_EQ(file1.content_type, "text/plain");
  2829. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2830. auto file2 = file1_values[1];
  2831. EXPECT_EQ(file2.filename, "world.json");
  2832. EXPECT_EQ(file2.content_type, "application/json");
  2833. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2834. }
  2835. })
  2836. .Post("/empty",
  2837. [&](const Request &req, Response &res) {
  2838. EXPECT_EQ(req.body, "");
  2839. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2840. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2841. res.set_content("empty", "text/plain");
  2842. })
  2843. .Post("/empty-no-content-type",
  2844. [&](const Request &req, Response &res) {
  2845. EXPECT_EQ(req.body, "");
  2846. EXPECT_FALSE(req.has_header("Content-Type"));
  2847. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2848. res.set_content("empty-no-content-type", "text/plain");
  2849. })
  2850. .Post("/path-only",
  2851. [&](const Request &req, Response &res) {
  2852. EXPECT_EQ(req.body, "");
  2853. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2855. res.set_content("path-only", "text/plain");
  2856. })
  2857. .Post("/path-headers-only",
  2858. [&](const Request &req, Response &res) {
  2859. EXPECT_EQ(req.body, "");
  2860. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2862. EXPECT_EQ("world", req.get_header_value("hello"));
  2863. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2864. res.set_content("path-headers-only", "text/plain");
  2865. })
  2866. .Post("/post-large",
  2867. [&](const Request &req, Response &res) {
  2868. EXPECT_EQ(req.body, LARGE_DATA);
  2869. res.set_content(req.body, "text/plain");
  2870. })
  2871. .Post("/post-loopback",
  2872. [&](const Request &, Response &res,
  2873. ContentReader const &content_reader) {
  2874. std::string body;
  2875. content_reader([&](const char *data, size_t data_length) {
  2876. body.append(data, data_length);
  2877. return true;
  2878. });
  2879. res.set_content(body, "text/plain");
  2880. })
  2881. .Put("/put-loopback",
  2882. [&](const Request &, Response &res,
  2883. ContentReader const &content_reader) {
  2884. std::string body;
  2885. content_reader([&](const char *data, size_t data_length) {
  2886. body.append(data, data_length);
  2887. return true;
  2888. });
  2889. res.set_content(body, "text/plain");
  2890. })
  2891. .Patch("/patch-loopback",
  2892. [&](const Request &, Response &res,
  2893. ContentReader const &content_reader) {
  2894. std::string body;
  2895. content_reader([&](const char *data, size_t data_length) {
  2896. body.append(data, data_length);
  2897. return true;
  2898. });
  2899. res.set_content(body, "text/plain");
  2900. })
  2901. .Put("/empty-no-content-type",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "");
  2904. EXPECT_FALSE(req.has_header("Content-Type"));
  2905. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2906. res.set_content("empty-no-content-type", "text/plain");
  2907. })
  2908. .Put("/put",
  2909. [&](const Request &req, Response &res) {
  2910. EXPECT_EQ(req.body, "PUT");
  2911. res.set_content(req.body, "text/plain");
  2912. })
  2913. .Put("/put-large",
  2914. [&](const Request &req, Response &res) {
  2915. EXPECT_EQ(req.body, LARGE_DATA);
  2916. res.set_content(req.body, "text/plain");
  2917. })
  2918. .Patch("/patch",
  2919. [&](const Request &req, Response &res) {
  2920. EXPECT_EQ(req.body, "PATCH");
  2921. res.set_content(req.body, "text/plain");
  2922. })
  2923. .Delete("/delete",
  2924. [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("DELETE", "text/plain");
  2926. })
  2927. .Delete("/delete-body",
  2928. [&](const Request &req, Response &res) {
  2929. EXPECT_EQ(req.body, "content");
  2930. res.set_content(req.body, "text/plain");
  2931. })
  2932. .Options(R"(\*)",
  2933. [&](const Request & /*req*/, Response &res) {
  2934. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2935. })
  2936. .Get("/request-target",
  2937. [&](const Request &req, Response & /*res*/) {
  2938. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2939. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2940. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2941. })
  2942. .Get("/long-query-value",
  2943. [&](const Request &req, Response & /*res*/) {
  2944. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2945. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2946. })
  2947. .Get("/too-long-query-value",
  2948. [&](const Request &req, Response & /*res*/) {
  2949. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2950. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2951. })
  2952. .Get("/array-param",
  2953. [&](const Request &req, Response & /*res*/) {
  2954. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2955. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2956. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2957. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2958. })
  2959. .Post("/validate-no-multiple-headers",
  2960. [&](const Request &req, Response & /*res*/) {
  2961. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2962. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2963. })
  2964. .Post("/content_receiver",
  2965. [&](const Request &req, Response &res,
  2966. const ContentReader &content_reader) {
  2967. if (req.is_multipart_form_data()) {
  2968. std::vector<FormData> items;
  2969. content_reader(
  2970. [&](const FormData &file) {
  2971. items.push_back(file);
  2972. return true;
  2973. },
  2974. [&](const char *data, size_t data_length) {
  2975. items.back().content.append(data, data_length);
  2976. return true;
  2977. });
  2978. EXPECT_EQ(5u, items.size());
  2979. {
  2980. const auto &file = get_file_value(items, "text1");
  2981. EXPECT_TRUE(file.filename.empty());
  2982. EXPECT_EQ("text default", file.content);
  2983. }
  2984. {
  2985. const auto &file = get_file_value(items, "text2");
  2986. EXPECT_TRUE(file.filename.empty());
  2987. EXPECT_EQ("aωb", file.content);
  2988. }
  2989. {
  2990. const auto &file = get_file_value(items, "file1");
  2991. EXPECT_EQ("hello.txt", file.filename);
  2992. EXPECT_EQ("text/plain", file.content_type);
  2993. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2994. }
  2995. {
  2996. const auto &file = get_file_value(items, "file2");
  2997. EXPECT_EQ("world.json", file.filename);
  2998. EXPECT_EQ("application/json", file.content_type);
  2999. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3000. }
  3001. {
  3002. const auto &file = get_file_value(items, "file3");
  3003. EXPECT_TRUE(file.filename.empty());
  3004. EXPECT_EQ("application/octet-stream", file.content_type);
  3005. EXPECT_EQ(0u, file.content.size());
  3006. }
  3007. } else {
  3008. std::string body;
  3009. content_reader([&](const char *data, size_t data_length) {
  3010. EXPECT_EQ(7U, data_length);
  3011. body.append(data, data_length);
  3012. return true;
  3013. });
  3014. EXPECT_EQ(body, "content");
  3015. res.set_content(body, "text/plain");
  3016. }
  3017. })
  3018. .Put("/content_receiver",
  3019. [&](const Request & /*req*/, Response &res,
  3020. const ContentReader &content_reader) {
  3021. std::string body;
  3022. content_reader([&](const char *data, size_t data_length) {
  3023. body.append(data, data_length);
  3024. return true;
  3025. });
  3026. EXPECT_EQ(body, "content");
  3027. res.set_content(body, "text/plain");
  3028. })
  3029. .Patch("/content_receiver",
  3030. [&](const Request & /*req*/, Response &res,
  3031. const ContentReader &content_reader) {
  3032. std::string body;
  3033. content_reader([&](const char *data, size_t data_length) {
  3034. body.append(data, data_length);
  3035. return true;
  3036. });
  3037. EXPECT_EQ(body, "content");
  3038. res.set_content(body, "text/plain");
  3039. })
  3040. .Post("/query-string-and-body",
  3041. [&](const Request &req, Response & /*res*/) {
  3042. ASSERT_TRUE(req.has_param("key"));
  3043. EXPECT_EQ(req.get_param_value("key"), "value");
  3044. EXPECT_EQ(req.body, "content");
  3045. })
  3046. .Get("/last-request",
  3047. [&](const Request &req, Response & /*res*/) {
  3048. EXPECT_EQ("close", req.get_header_value("Connection"));
  3049. })
  3050. .Get(R"(/redirect/(\d+))",
  3051. [&](const Request &req, Response &res) {
  3052. auto num = std::stoi(req.matches[1]) + 1;
  3053. std::string url = "/redirect/" + std::to_string(num);
  3054. res.set_redirect(url);
  3055. })
  3056. .Post("/binary",
  3057. [&](const Request &req, Response &res) {
  3058. EXPECT_EQ(4U, req.body.size());
  3059. EXPECT_EQ("application/octet-stream",
  3060. req.get_header_value("Content-Type"));
  3061. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3062. res.set_content(req.body, "application/octet-stream");
  3063. })
  3064. .Put("/binary",
  3065. [&](const Request &req, Response &res) {
  3066. EXPECT_EQ(4U, req.body.size());
  3067. EXPECT_EQ("application/octet-stream",
  3068. req.get_header_value("Content-Type"));
  3069. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3070. res.set_content(req.body, "application/octet-stream");
  3071. })
  3072. .Patch("/binary",
  3073. [&](const Request &req, Response &res) {
  3074. EXPECT_EQ(4U, req.body.size());
  3075. EXPECT_EQ("application/octet-stream",
  3076. req.get_header_value("Content-Type"));
  3077. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3078. res.set_content(req.body, "application/octet-stream");
  3079. })
  3080. .Delete("/binary",
  3081. [&](const Request &req, Response &res) {
  3082. EXPECT_EQ(4U, req.body.size());
  3083. EXPECT_EQ("application/octet-stream",
  3084. req.get_header_value("Content-Type"));
  3085. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3086. res.set_content(req.body, "application/octet-stream");
  3087. })
  3088. .Get("/issue1772",
  3089. [&](const Request & /*req*/, Response &res) {
  3090. res.status = 401;
  3091. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3092. })
  3093. .Delete("/issue609",
  3094. [](const httplib::Request &, httplib::Response &res,
  3095. const httplib::ContentReader &) {
  3096. res.set_content("ok", "text/plain");
  3097. })
  3098. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3099. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3100. .Get("/compress",
  3101. [&](const Request & /*req*/, Response &res) {
  3102. res.set_content(
  3103. "12345678901234567890123456789012345678901234567890123456789"
  3104. "01234567890123456789012345678901234567890",
  3105. "text/plain");
  3106. })
  3107. .Get("/nocompress",
  3108. [&](const Request & /*req*/, Response &res) {
  3109. res.set_content(
  3110. "12345678901234567890123456789012345678901234567890123456789"
  3111. "01234567890123456789012345678901234567890",
  3112. "application/octet-stream");
  3113. })
  3114. .Post("/compress-multipart",
  3115. [&](const Request &req, Response & /*res*/) {
  3116. EXPECT_EQ(2u, req.form.fields.size());
  3117. ASSERT_TRUE(!req.form.has_field("???"));
  3118. {
  3119. const auto &text = req.form.get_field("key1");
  3120. EXPECT_EQ("test", text);
  3121. }
  3122. {
  3123. const auto &text = req.form.get_field("key2");
  3124. EXPECT_EQ("--abcdefg123", text);
  3125. }
  3126. })
  3127. #endif
  3128. ;
  3129. persons_["john"] = "programmer";
  3130. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3131. svr_.wait_until_ready();
  3132. }
  3133. virtual void TearDown() {
  3134. svr_.stop();
  3135. if (!request_threads_.empty()) {
  3136. std::this_thread::sleep_for(std::chrono::seconds(1));
  3137. for (auto &t : request_threads_) {
  3138. t.join();
  3139. }
  3140. }
  3141. t_.join();
  3142. }
  3143. map<string, string> persons_;
  3144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3145. SSLClient cli_;
  3146. SSLServer svr_;
  3147. #else
  3148. Client cli_;
  3149. Server svr_;
  3150. #endif
  3151. thread t_;
  3152. std::vector<thread> request_threads_;
  3153. };
  3154. TEST_F(ServerTest, GetMethod200) {
  3155. auto res = cli_.Get("/hi");
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ("HTTP/1.1", res->version);
  3158. EXPECT_EQ(StatusCode::OK_200, res->status);
  3159. EXPECT_EQ("OK", res->reason);
  3160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3161. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3162. EXPECT_EQ("Hello World!", res->body);
  3163. }
  3164. TEST_F(ServerTest, GetEmptyFile) {
  3165. auto res = cli_.Get("/empty_file");
  3166. ASSERT_TRUE(res);
  3167. EXPECT_EQ(StatusCode::OK_200, res->status);
  3168. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3169. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3170. EXPECT_EQ("", res->body);
  3171. }
  3172. TEST_F(ServerTest, GetFileContent) {
  3173. auto res = cli_.Get("/file_content");
  3174. ASSERT_TRUE(res);
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3177. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3178. EXPECT_EQ("test.html", res->body);
  3179. }
  3180. TEST_F(ServerTest, GetFileContentWithRange) {
  3181. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3182. ASSERT_TRUE(res);
  3183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3184. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3185. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3186. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3187. EXPECT_EQ("est", res->body);
  3188. }
  3189. TEST_F(ServerTest, GetFileContentWithContentType) {
  3190. auto res = cli_.Get("/file_content_with_content_type");
  3191. ASSERT_TRUE(res);
  3192. EXPECT_EQ(StatusCode::OK_200, res->status);
  3193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3194. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3195. EXPECT_EQ("file\n", res->body);
  3196. }
  3197. TEST_F(ServerTest, GetInvalidFileContent) {
  3198. auto res = cli_.Get("/invalid_file_content");
  3199. ASSERT_TRUE(res);
  3200. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3201. }
  3202. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3203. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3204. ASSERT_TRUE(res);
  3205. EXPECT_EQ("HTTP/1.1", res->version);
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3208. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3209. EXPECT_EQ("Hello World!", res->body);
  3210. }
  3211. TEST_F(ServerTest, GetMethod302) {
  3212. auto res = cli_.Get("/");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::Found_302, res->status);
  3215. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3216. }
  3217. TEST_F(ServerTest, GetMethod302Redirect) {
  3218. cli_.set_follow_location(true);
  3219. auto res = cli_.Get("/");
  3220. ASSERT_TRUE(res);
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("Hello World!", res->body);
  3223. EXPECT_EQ("/hi", res->location);
  3224. }
  3225. TEST_F(ServerTest, GetMethod404) {
  3226. auto res = cli_.Get("/invalid");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, HeadMethod200) {
  3231. auto res = cli_.Head("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::OK_200, res->status);
  3234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3235. EXPECT_TRUE(res->body.empty());
  3236. }
  3237. TEST_F(ServerTest, HeadMethod200Static) {
  3238. auto res = cli_.Head("/mount/dir/index.html");
  3239. ASSERT_TRUE(res);
  3240. EXPECT_EQ(StatusCode::OK_200, res->status);
  3241. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3242. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3243. EXPECT_TRUE(res->body.empty());
  3244. }
  3245. TEST_F(ServerTest, HeadMethod404) {
  3246. auto res = cli_.Head("/invalid");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3249. EXPECT_TRUE(res->body.empty());
  3250. }
  3251. TEST_F(ServerTest, GetMethodPersonJohn) {
  3252. auto res = cli_.Get("/person/john");
  3253. ASSERT_TRUE(res);
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3256. EXPECT_EQ("programmer", res->body);
  3257. }
  3258. TEST_F(ServerTest, PostMethod1) {
  3259. auto res = cli_.Get("/person/john1");
  3260. ASSERT_TRUE(res);
  3261. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3262. res = cli_.Post("/person", "name=john1&note=coder",
  3263. "application/x-www-form-urlencoded");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::OK_200, res->status);
  3266. res = cli_.Get("/person/john1");
  3267. ASSERT_TRUE(res);
  3268. ASSERT_EQ(StatusCode::OK_200, res->status);
  3269. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3270. ASSERT_EQ("coder", res->body);
  3271. }
  3272. TEST_F(ServerTest, PostMethod2) {
  3273. auto res = cli_.Get("/person/john2");
  3274. ASSERT_TRUE(res);
  3275. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3276. Params params;
  3277. params.emplace("name", "john2");
  3278. params.emplace("note", "coder");
  3279. res = cli_.Post("/person", params);
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::OK_200, res->status);
  3282. res = cli_.Get("/person/john2");
  3283. ASSERT_TRUE(res);
  3284. ASSERT_EQ(StatusCode::OK_200, res->status);
  3285. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3286. ASSERT_EQ("coder", res->body);
  3287. }
  3288. TEST_F(ServerTest, PutMethod3) {
  3289. auto res = cli_.Get("/person/john3");
  3290. ASSERT_TRUE(res);
  3291. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3292. Params params;
  3293. params.emplace("name", "john3");
  3294. params.emplace("note", "coder");
  3295. res = cli_.Put("/person", params);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. res = cli_.Get("/person/john3");
  3299. ASSERT_TRUE(res);
  3300. ASSERT_EQ(StatusCode::OK_200, res->status);
  3301. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3302. ASSERT_EQ("coder", res->body);
  3303. }
  3304. TEST_F(ServerTest, DeleteMethod1) {
  3305. auto res = cli_.Get("/person/john4");
  3306. ASSERT_TRUE(res);
  3307. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3308. Params params;
  3309. params.emplace("name", "john4");
  3310. params.emplace("note", "coder");
  3311. res = cli_.Post("/person", params);
  3312. ASSERT_TRUE(res);
  3313. ASSERT_EQ(StatusCode::OK_200, res->status);
  3314. res = cli_.Get("/person/john4");
  3315. ASSERT_TRUE(res);
  3316. ASSERT_EQ(StatusCode::OK_200, res->status);
  3317. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3318. ASSERT_EQ("coder", res->body);
  3319. Params delete_params;
  3320. delete_params.emplace("name", "john4");
  3321. res = cli_.Delete("/person", delete_params);
  3322. ASSERT_TRUE(res);
  3323. ASSERT_EQ(StatusCode::OK_200, res->status);
  3324. ASSERT_EQ("DELETED", res->body);
  3325. res = cli_.Get("/person/john4");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3328. }
  3329. TEST_F(ServerTest, DeleteMethod2) {
  3330. auto res = cli_.Get("/person/john5");
  3331. ASSERT_TRUE(res);
  3332. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3333. Params params;
  3334. params.emplace("name", "john5");
  3335. params.emplace("note", "developer");
  3336. res = cli_.Post("/person", params);
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::OK_200, res->status);
  3339. res = cli_.Get("/person/john5");
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3343. ASSERT_EQ("developer", res->body);
  3344. Params delete_params;
  3345. delete_params.emplace("name", "john5");
  3346. Headers headers;
  3347. headers.emplace("Custom-Header", "test-value");
  3348. res = cli_.Delete("/person", headers, delete_params);
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. ASSERT_EQ("DELETED", res->body);
  3352. res = cli_.Get("/person/john5");
  3353. ASSERT_TRUE(res);
  3354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3355. }
  3356. TEST_F(ServerTest, DeleteMethod3) {
  3357. auto res = cli_.Get("/person/john6");
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3360. Params params;
  3361. params.emplace("name", "john6");
  3362. params.emplace("note", "tester");
  3363. res = cli_.Post("/person", params);
  3364. ASSERT_TRUE(res);
  3365. ASSERT_EQ(StatusCode::OK_200, res->status);
  3366. res = cli_.Get("/person/john6");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3370. ASSERT_EQ("tester", res->body);
  3371. Params delete_params;
  3372. delete_params.emplace("name", "john6");
  3373. Headers headers;
  3374. headers.emplace("Custom-Header", "test-value");
  3375. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("DELETED", res->body);
  3379. res = cli_.Get("/person/john6");
  3380. ASSERT_TRUE(res);
  3381. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3382. }
  3383. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3384. Params params;
  3385. params.emplace("json", JSON_DATA);
  3386. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::OK_200, res->status);
  3389. ASSERT_EQ(JSON_DATA, res->body);
  3390. }
  3391. TEST_F(ServerTest, PostEmptyContent) {
  3392. auto res = cli_.Post("/empty", "", "text/plain");
  3393. ASSERT_TRUE(res);
  3394. ASSERT_EQ(StatusCode::OK_200, res->status);
  3395. ASSERT_EQ("empty", res->body);
  3396. }
  3397. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3398. auto res = cli_.Post("/empty-no-content-type");
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("empty-no-content-type", res->body);
  3402. }
  3403. TEST_F(ServerTest, PostPathOnly) {
  3404. auto res = cli_.Post("/path-only");
  3405. ASSERT_TRUE(res);
  3406. ASSERT_EQ(StatusCode::OK_200, res->status);
  3407. ASSERT_EQ("path-only", res->body);
  3408. }
  3409. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3410. auto res = cli_.Post("/path-headers-only",
  3411. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("path-headers-only", res->body);
  3415. }
  3416. TEST_F(ServerTest, PostLarge) {
  3417. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3418. ASSERT_TRUE(res);
  3419. ASSERT_EQ(StatusCode::OK_200, res->status);
  3420. EXPECT_EQ(LARGE_DATA, res->body);
  3421. }
  3422. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3423. auto res = cli_.Put("/empty-no-content-type");
  3424. ASSERT_TRUE(res);
  3425. ASSERT_EQ(StatusCode::OK_200, res->status);
  3426. ASSERT_EQ("empty-no-content-type", res->body);
  3427. }
  3428. TEST_F(ServerTest, GetMethodDir) {
  3429. auto res = cli_.Get("/dir/");
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3433. auto body = R"(<html>
  3434. <head>
  3435. </head>
  3436. <body>
  3437. <a href="/dir/test.html">Test</a>
  3438. <a href="/hi">hi</a>
  3439. </body>
  3440. </html>
  3441. )";
  3442. EXPECT_EQ(body, res->body);
  3443. }
  3444. TEST_F(ServerTest, GetMethodDirTest) {
  3445. auto res = cli_.Get("/dir/test.html");
  3446. ASSERT_TRUE(res);
  3447. EXPECT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3449. EXPECT_EQ("test.html", res->body);
  3450. }
  3451. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3452. auto res = cli_.Get("/dir/../dir/test.html");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::OK_200, res->status);
  3455. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3456. EXPECT_EQ("test.html", res->body);
  3457. }
  3458. TEST_F(ServerTest, GetMethodInvalidPath) {
  3459. auto res = cli_.Get("/dir/../test.html");
  3460. ASSERT_TRUE(res);
  3461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3462. }
  3463. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3464. auto res = cli_.Get("/../www/dir/test.html");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3467. }
  3468. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3469. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3470. ASSERT_TRUE(res);
  3471. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3472. }
  3473. TEST_F(ServerTest, GetMethodDirMountTest) {
  3474. auto res = cli_.Get("/mount/dir/test.html");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ("test.html", res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3481. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3488. auto res = cli_.Get("/mount/dir/../test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3491. }
  3492. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3493. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3494. ASSERT_TRUE(res);
  3495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3496. }
  3497. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3498. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3501. }
  3502. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3503. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3506. }
  3507. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3508. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3509. ASSERT_TRUE(res);
  3510. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3511. }
  3512. TEST_F(ServerTest, PostMethod303) {
  3513. auto res = cli_.Post("/1", "body", "text/plain");
  3514. ASSERT_TRUE(res);
  3515. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3516. EXPECT_EQ("/2", res->get_header_value("Location"));
  3517. }
  3518. TEST_F(ServerTest, PostMethod303Redirect) {
  3519. cli_.set_follow_location(true);
  3520. auto res = cli_.Post("/1", "body", "text/plain");
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::OK_200, res->status);
  3523. EXPECT_EQ("redirected.", res->body);
  3524. EXPECT_EQ("/2", res->location);
  3525. }
  3526. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3527. auto res = cli_.Get("/dir/test.abcde");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::OK_200, res->status);
  3530. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3531. EXPECT_EQ("abcde", res->body);
  3532. }
  3533. TEST_F(ServerTest, StaticFileRange) {
  3534. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3537. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3538. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3539. EXPECT_EQ(true, res->has_header("Content-Range"));
  3540. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3541. EXPECT_EQ(std::string("cd"), res->body);
  3542. }
  3543. TEST_F(ServerTest, StaticFileRanges) {
  3544. auto res =
  3545. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3548. EXPECT_TRUE(
  3549. res->get_header_value("Content-Type")
  3550. .find(
  3551. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3552. 0);
  3553. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3554. }
  3555. TEST_F(ServerTest, StaticFileRangeHead) {
  3556. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3559. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3560. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3561. EXPECT_EQ(true, res->has_header("Content-Range"));
  3562. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3563. }
  3564. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3565. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3566. ASSERT_TRUE(res);
  3567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3569. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3570. EXPECT_EQ(true, res->has_header("Content-Range"));
  3571. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3572. res->get_header_value("Content-Range"));
  3573. EXPECT_EQ("LAST\n", res->body);
  3574. }
  3575. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3576. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3577. ASSERT_TRUE(res);
  3578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3579. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3580. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3581. EXPECT_EQ(true, res->has_header("Content-Range"));
  3582. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3583. }
  3584. TEST_F(ServerTest, StaticFileBigFile) {
  3585. auto res = cli_.Get("/dir/1MB.txt");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::OK_200, res->status);
  3588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3589. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3590. }
  3591. TEST_F(ServerTest, InvalidBaseDirMount) {
  3592. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3593. }
  3594. TEST_F(ServerTest, Binary) {
  3595. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3596. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3597. "application/octet-stream");
  3598. ASSERT_TRUE(res);
  3599. ASSERT_EQ(StatusCode::OK_200, res->status);
  3600. ASSERT_EQ(4U, res->body.size());
  3601. res = cli_.Put("/binary", binary.data(), binary.size(),
  3602. "application/octet-stream");
  3603. ASSERT_TRUE(res);
  3604. ASSERT_EQ(StatusCode::OK_200, res->status);
  3605. ASSERT_EQ(4U, res->body.size());
  3606. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3607. "application/octet-stream");
  3608. ASSERT_TRUE(res);
  3609. ASSERT_EQ(StatusCode::OK_200, res->status);
  3610. ASSERT_EQ(4U, res->body.size());
  3611. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3612. "application/octet-stream");
  3613. ASSERT_TRUE(res);
  3614. ASSERT_EQ(StatusCode::OK_200, res->status);
  3615. ASSERT_EQ(4U, res->body.size());
  3616. }
  3617. TEST_F(ServerTest, BinaryString) {
  3618. auto binary = std::string("\x00\x01\x02\x03", 4);
  3619. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3620. ASSERT_TRUE(res);
  3621. ASSERT_EQ(StatusCode::OK_200, res->status);
  3622. ASSERT_EQ(4U, res->body.size());
  3623. res = cli_.Put("/binary", binary, "application/octet-stream");
  3624. ASSERT_TRUE(res);
  3625. ASSERT_EQ(StatusCode::OK_200, res->status);
  3626. ASSERT_EQ(4U, res->body.size());
  3627. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3628. ASSERT_TRUE(res);
  3629. ASSERT_EQ(StatusCode::OK_200, res->status);
  3630. ASSERT_EQ(4U, res->body.size());
  3631. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. ASSERT_EQ(4U, res->body.size());
  3635. }
  3636. TEST_F(ServerTest, EmptyRequest) {
  3637. auto res = cli_.Get("");
  3638. ASSERT_TRUE(!res);
  3639. EXPECT_EQ(Error::Connection, res.error());
  3640. }
  3641. TEST_F(ServerTest, LongRequest) {
  3642. std::string request;
  3643. for (size_t i = 0; i < 545; i++) {
  3644. request += "/TooLongRequest";
  3645. }
  3646. request += "OK";
  3647. auto res = cli_.Get(request.c_str());
  3648. ASSERT_TRUE(res);
  3649. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3650. }
  3651. TEST_F(ServerTest, TooLongRequest) {
  3652. std::string request;
  3653. for (size_t i = 0; i < 546; i++) {
  3654. request += "/TooLongRequest";
  3655. }
  3656. request += "_NG";
  3657. auto start = std::chrono::high_resolution_clock::now();
  3658. cli_.set_keep_alive(true);
  3659. auto res = cli_.Get(request.c_str());
  3660. auto end = std::chrono::high_resolution_clock::now();
  3661. auto elapsed =
  3662. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3663. .count();
  3664. ASSERT_TRUE(res);
  3665. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3666. EXPECT_LE(elapsed, 100);
  3667. EXPECT_EQ("close", res->get_header_value("Connection"));
  3668. EXPECT_FALSE(cli_.is_socket_open());
  3669. }
  3670. TEST_F(ServerTest, AlmostTooLongRequest) {
  3671. // test for #2046 - URI length check shouldn't include other content on req
  3672. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3673. // leading /, space, HTTP/1.1)
  3674. std::string request =
  3675. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3676. auto res = cli_.Get(request.c_str());
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3679. }
  3680. TEST_F(ServerTest, LongHeader) {
  3681. Request req;
  3682. req.method = "GET";
  3683. req.path = "/hi";
  3684. std::string host_and_port;
  3685. host_and_port += HOST;
  3686. host_and_port += ":";
  3687. host_and_port += std::to_string(PORT);
  3688. req.headers.emplace("Host", host_and_port.c_str());
  3689. req.headers.emplace("Accept", "*/*");
  3690. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3691. req.headers.emplace(
  3692. "Header-Name",
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3698. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3699. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3700. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3701. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3721. "@@@@@@@@@@@@@@@@");
  3722. auto res = std::make_shared<Response>();
  3723. auto error = Error::Success;
  3724. auto ret = cli_.send(req, *res, error);
  3725. ASSERT_TRUE(ret);
  3726. EXPECT_EQ(StatusCode::OK_200, res->status);
  3727. }
  3728. TEST_F(ServerTest, LongQueryValue) {
  3729. auto start = std::chrono::high_resolution_clock::now();
  3730. cli_.set_keep_alive(true);
  3731. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3732. auto end = std::chrono::high_resolution_clock::now();
  3733. auto elapsed =
  3734. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3735. .count();
  3736. ASSERT_TRUE(res);
  3737. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3738. EXPECT_LE(elapsed, 100);
  3739. EXPECT_EQ("close", res->get_header_value("Connection"));
  3740. EXPECT_FALSE(cli_.is_socket_open());
  3741. }
  3742. TEST_F(ServerTest, TooLongQueryValue) {
  3743. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3744. ASSERT_FALSE(res);
  3745. EXPECT_EQ(Error::Read, res.error());
  3746. }
  3747. TEST_F(ServerTest, TooLongHeader) {
  3748. Request req;
  3749. req.method = "GET";
  3750. req.path = "/hi";
  3751. std::string host_and_port;
  3752. host_and_port += HOST;
  3753. host_and_port += ":";
  3754. host_and_port += std::to_string(PORT);
  3755. req.headers.emplace("Host", host_and_port.c_str());
  3756. req.headers.emplace("Accept", "*/*");
  3757. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3758. req.headers.emplace(
  3759. "Header-Name",
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3788. "@@@@@@@@@@@@@@@@@");
  3789. auto res = std::make_shared<Response>();
  3790. auto error = Error::Success;
  3791. auto ret = cli_.send(req, *res, error);
  3792. ASSERT_TRUE(ret);
  3793. EXPECT_EQ(StatusCode::OK_200, res->status);
  3794. }
  3795. TEST_F(ServerTest, HeaderCountAtLimit) {
  3796. // Test with headers just under the 100 limit
  3797. httplib::Headers headers;
  3798. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3799. // This should keep us just under the 100 header limit
  3800. for (int i = 0; i < 95; i++) {
  3801. std::string name = "X-Test-Header-" + std::to_string(i);
  3802. std::string value = "value" + std::to_string(i);
  3803. headers.emplace(name, value);
  3804. }
  3805. // This should work fine as we're under the limit
  3806. auto res = cli_.Get("/hi", headers);
  3807. EXPECT_TRUE(res);
  3808. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3809. }
  3810. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3811. // Test with many headers to exceed the 100 limit
  3812. httplib::Headers headers;
  3813. // Add 150 headers to definitely exceed the 100 limit
  3814. for (int i = 0; i < 150; i++) {
  3815. std::string name = "X-Test-Header-" + std::to_string(i);
  3816. std::string value = "value" + std::to_string(i);
  3817. headers.emplace(name, value);
  3818. }
  3819. // This should fail due to exceeding header count limit
  3820. cli_.set_keep_alive(true);
  3821. auto res = cli_.Get("/hi", headers);
  3822. // The request should either fail or return 400 Bad Request
  3823. if (res) {
  3824. // If we get a response, it should be 400 Bad Request
  3825. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3826. } else {
  3827. // Or the request should fail entirely
  3828. EXPECT_FALSE(res);
  3829. }
  3830. EXPECT_EQ("close", res->get_header_value("Connection"));
  3831. EXPECT_FALSE(cli_.is_socket_open());
  3832. }
  3833. TEST_F(ServerTest, PercentEncoding) {
  3834. auto res = cli_.Get("/e%6edwith%");
  3835. ASSERT_TRUE(res);
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. }
  3838. TEST_F(ServerTest, PercentEncodingUnicode) {
  3839. auto res = cli_.Get("/e%u006edwith%");
  3840. ASSERT_TRUE(res);
  3841. EXPECT_EQ(StatusCode::OK_200, res->status);
  3842. }
  3843. TEST_F(ServerTest, InvalidPercentEncoding) {
  3844. auto res = cli_.Get("/%endwith%");
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3847. }
  3848. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3849. auto res = cli_.Get("/%uendwith%");
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3852. }
  3853. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3854. auto res = cli_.Get("/hello?aaa=bbb%");
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3857. }
  3858. TEST_F(ServerTest, PlusSignEncoding) {
  3859. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::OK_200, res->status);
  3862. EXPECT_EQ("a +b", res->body);
  3863. }
  3864. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3865. // This test simulates a potential DoS attack using many headers
  3866. // to verify our security fix prevents memory exhaustion
  3867. httplib::Headers attack_headers;
  3868. // Attempt to add many headers like an attacker would (200 headers to far
  3869. // exceed limit)
  3870. for (int i = 0; i < 200; i++) {
  3871. std::string name = "X-Attack-Header-" + std::to_string(i);
  3872. std::string value = "attack_payload_" + std::to_string(i);
  3873. attack_headers.emplace(name, value);
  3874. }
  3875. // Try to POST with excessive headers
  3876. cli_.set_keep_alive(true);
  3877. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3878. // Should either fail or return 400 Bad Request due to security limit
  3879. if (res) {
  3880. // If we get a response, it should be 400 Bad Request
  3881. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3882. } else {
  3883. // Request failed, which is the expected behavior for DoS protection
  3884. EXPECT_FALSE(res);
  3885. }
  3886. EXPECT_EQ("close", res->get_header_value("Connection"));
  3887. EXPECT_FALSE(cli_.is_socket_open());
  3888. }
  3889. TEST_F(ServerTest, MultipartFormData) {
  3890. UploadFormDataItems items = {
  3891. {"text1", "text default", "", ""},
  3892. {"text2", "aωb", "", ""},
  3893. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3894. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3895. {"file3", "", "", "application/octet-stream"},
  3896. {"file4", "", "", " application/json tmp-string "}};
  3897. auto res = cli_.Post("/multipart", items);
  3898. ASSERT_TRUE(res);
  3899. EXPECT_EQ(StatusCode::OK_200, res->status);
  3900. }
  3901. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3902. UploadFormDataItems items = {
  3903. {"text", "default text", "", ""},
  3904. {"multi_text1", "aaaaa", "", ""},
  3905. {"multi_text1", "bbbbb", "", ""},
  3906. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3907. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3908. "application/json"},
  3909. };
  3910. auto res = cli_.Post("/multipart/multi_file_values", items);
  3911. ASSERT_TRUE(res);
  3912. EXPECT_EQ(StatusCode::OK_200, res->status);
  3913. }
  3914. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3915. auto res = cli_.Get("/hi");
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3919. EXPECT_EQ("Hello World!", res->body);
  3920. }
  3921. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3922. Request req;
  3923. req.method = "POST";
  3924. req.path = "/chunked";
  3925. std::string host_and_port;
  3926. host_and_port += HOST;
  3927. host_and_port += ":";
  3928. host_and_port += std::to_string(PORT);
  3929. req.headers.emplace("Host", host_and_port.c_str());
  3930. req.headers.emplace("Accept", "*/*");
  3931. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3932. req.headers.emplace("Content-Type", "text/plain");
  3933. req.headers.emplace("Content-Length", "0");
  3934. req.headers.emplace(
  3935. "Transfer-Encoding",
  3936. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3937. // Client does not chunk, so make a chunked body manually.
  3938. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3939. auto res = std::make_shared<Response>();
  3940. auto error = Error::Success;
  3941. auto ret = cli_.send(req, *res, error);
  3942. ASSERT_TRUE(ret);
  3943. EXPECT_EQ(StatusCode::OK_200, res->status);
  3944. }
  3945. TEST_F(ServerTest, GetStreamed2) {
  3946. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3949. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3950. EXPECT_EQ(true, res->has_header("Content-Range"));
  3951. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3952. EXPECT_EQ(std::string("ab"), res->body);
  3953. }
  3954. TEST_F(ServerTest, GetStreamed) {
  3955. auto res = cli_.Get("/streamed");
  3956. ASSERT_TRUE(res);
  3957. EXPECT_EQ(StatusCode::OK_200, res->status);
  3958. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3959. EXPECT_EQ(std::string("aaabbb"), res->body);
  3960. }
  3961. TEST_F(ServerTest, GetStreamedWithRange1) {
  3962. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3963. ASSERT_TRUE(res);
  3964. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3965. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3966. EXPECT_EQ(true, res->has_header("Content-Range"));
  3967. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3968. EXPECT_EQ(std::string("def"), res->body);
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithRange2) {
  3971. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3974. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3975. EXPECT_EQ(true, res->has_header("Content-Range"));
  3976. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3977. EXPECT_EQ(std::string("bcdefg"), res->body);
  3978. }
  3979. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3980. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3981. ASSERT_TRUE(res);
  3982. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3983. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3984. EXPECT_EQ(true, res->has_header("Content-Range"));
  3985. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3986. EXPECT_EQ(std::string("efg"), res->body);
  3987. }
  3988. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3989. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3990. ASSERT_TRUE(res);
  3991. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3992. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ(false, res->has_header("Content-Range"));
  3994. EXPECT_EQ(0U, res->body.size());
  3995. }
  3996. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3997. auto res = cli_.Get("/streamed-with-range",
  3998. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3999. "92233720368547758079223372036854775807"}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4002. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(false, res->has_header("Content-Range"));
  4004. EXPECT_EQ(0U, res->body.size());
  4005. }
  4006. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4007. auto res = cli_.Get(
  4008. "/with-range",
  4009. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4010. {"Accept-Encoding", ""}});
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4013. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4014. EXPECT_EQ(true, res->has_header("Content-Range"));
  4015. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4016. EXPECT_EQ(std::string("abcdefg"), res->body);
  4017. }
  4018. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4019. auto res = cli_.Get("/with-range", {
  4020. {"Range", "bytes=0-"},
  4021. {"Accept-Encoding", ""},
  4022. });
  4023. ASSERT_TRUE(res);
  4024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4025. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4026. EXPECT_EQ(true, res->has_header("Content-Range"));
  4027. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4028. EXPECT_EQ(std::string("abcdefg"), res->body);
  4029. }
  4030. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4031. auto res =
  4032. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4033. ASSERT_TRUE(res);
  4034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4035. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4036. EXPECT_EQ(false, res->has_header("Content-Range"));
  4037. EXPECT_EQ(267U, res->body.size());
  4038. // Check that both range contents are present
  4039. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4040. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4041. // Check that Content-Range headers are present for both ranges
  4042. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4043. std::string::npos);
  4044. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4045. std::string::npos);
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4048. Ranges ranges;
  4049. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4050. ranges.emplace_back(0, -1);
  4051. }
  4052. auto res =
  4053. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4054. ASSERT_TRUE(res);
  4055. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4056. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4057. EXPECT_EQ(false, res->has_header("Content-Range"));
  4058. EXPECT_EQ(0U, res->body.size());
  4059. }
  4060. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4061. auto res =
  4062. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ(5U, res->body.size());
  4066. // Check that overlapping ranges are coalesced into a single range
  4067. EXPECT_EQ("bcdef", res->body);
  4068. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4069. // Should be single range, not multipart
  4070. EXPECT_TRUE(res->has_header("Content-Range"));
  4071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4072. }
  4073. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4074. auto res =
  4075. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ(268U, res->body.size());
  4079. // Check that both range contents are present
  4080. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4081. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4082. // Check that Content-Range headers are present for both ranges
  4083. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4084. std::string::npos);
  4085. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4086. std::string::npos);
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(269U, res->body.size());
  4094. // Check that both duplicate range contents are present
  4095. size_t first_abc = res->body.find("abc\r\n");
  4096. EXPECT_TRUE(first_abc != std::string::npos);
  4097. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4098. EXPECT_TRUE(second_abc != std::string::npos);
  4099. // Check that Content-Range headers are present for both ranges
  4100. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4101. EXPECT_TRUE(first_range != std::string::npos);
  4102. size_t second_range =
  4103. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4104. EXPECT_TRUE(second_range != std::string::npos);
  4105. }
  4106. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4107. auto res = cli_.Get("/streamed-with-range?error",
  4108. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4109. ASSERT_TRUE(res);
  4110. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4111. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4112. EXPECT_EQ(false, res->has_header("Content-Range"));
  4113. EXPECT_EQ(0U, res->body.size());
  4114. }
  4115. TEST_F(ServerTest, GetStreamedEndless) {
  4116. uint64_t offset = 0;
  4117. auto res = cli_.Get("/streamed-cancel",
  4118. [&](const char * /*data*/, uint64_t data_length) {
  4119. if (offset < 100) {
  4120. offset += data_length;
  4121. return true;
  4122. }
  4123. return false;
  4124. });
  4125. ASSERT_TRUE(!res);
  4126. EXPECT_EQ(Error::Canceled, res.error());
  4127. }
  4128. TEST_F(ServerTest, ClientStop) {
  4129. std::atomic_size_t count{4};
  4130. std::vector<std::thread> threads;
  4131. for (auto i = count.load(); i != 0; --i) {
  4132. threads.emplace_back([&]() {
  4133. auto res = cli_.Get("/streamed-cancel",
  4134. [&](const char *, uint64_t) { return true; });
  4135. --count;
  4136. ASSERT_TRUE(!res);
  4137. EXPECT_TRUE(res.error() == Error::Canceled ||
  4138. res.error() == Error::Read || res.error() == Error::Write);
  4139. });
  4140. }
  4141. std::this_thread::sleep_for(std::chrono::seconds(2));
  4142. while (count != 0) {
  4143. cli_.stop();
  4144. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4145. }
  4146. for (auto &t : threads) {
  4147. t.join();
  4148. }
  4149. }
  4150. TEST_F(ServerTest, GetWithRange1) {
  4151. auto res = cli_.Get("/with-range", {
  4152. make_range_header({{3, 5}}),
  4153. {"Accept-Encoding", ""},
  4154. });
  4155. ASSERT_TRUE(res);
  4156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4157. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4158. EXPECT_EQ(true, res->has_header("Content-Range"));
  4159. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4160. EXPECT_EQ(std::string("def"), res->body);
  4161. }
  4162. TEST_F(ServerTest, GetWithRange2) {
  4163. auto res = cli_.Get("/with-range", {
  4164. make_range_header({{1, -1}}),
  4165. {"Accept-Encoding", ""},
  4166. });
  4167. ASSERT_TRUE(res);
  4168. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4169. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4170. EXPECT_EQ(true, res->has_header("Content-Range"));
  4171. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4172. EXPECT_EQ(std::string("bcdefg"), res->body);
  4173. }
  4174. TEST_F(ServerTest, GetWithRange3) {
  4175. auto res = cli_.Get("/with-range", {
  4176. make_range_header({{0, 0}}),
  4177. {"Accept-Encoding", ""},
  4178. });
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4181. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4182. EXPECT_EQ(true, res->has_header("Content-Range"));
  4183. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4184. EXPECT_EQ(std::string("a"), res->body);
  4185. }
  4186. TEST_F(ServerTest, GetWithRange4) {
  4187. auto res = cli_.Get("/with-range", {
  4188. make_range_header({{-1, 2}}),
  4189. {"Accept-Encoding", ""},
  4190. });
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4196. EXPECT_EQ(std::string("fg"), res->body);
  4197. }
  4198. TEST_F(ServerTest, GetWithRange5) {
  4199. auto res = cli_.Get("/with-range", {
  4200. make_range_header({{0, 5}}),
  4201. {"Accept-Encoding", ""},
  4202. });
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4205. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(true, res->has_header("Content-Range"));
  4207. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4208. EXPECT_EQ(std::string("abcdef"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4211. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4214. }
  4215. TEST_F(ServerTest, GetWithRangeMultipart) {
  4216. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4217. ASSERT_TRUE(res);
  4218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4219. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4220. EXPECT_EQ(false, res->has_header("Content-Range"));
  4221. EXPECT_EQ(267U, res->body.size());
  4222. }
  4223. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4224. auto res =
  4225. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4226. ASSERT_TRUE(res);
  4227. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4228. }
  4229. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4230. auto res = cli_.Get("/with-range-customized-response",
  4231. {{make_range_header({{1, 2}})}});
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4234. EXPECT_EQ(true, res->has_header("Content-Length"));
  4235. EXPECT_EQ(false, res->has_header("Content-Range"));
  4236. EXPECT_EQ(JSON_DATA, res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4239. auto res = cli_.Get("/with-range-customized-response",
  4240. {{make_range_header({{1, 2}, {4, 5}})}});
  4241. ASSERT_TRUE(res);
  4242. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4243. EXPECT_EQ(true, res->has_header("Content-Length"));
  4244. EXPECT_EQ(false, res->has_header("Content-Range"));
  4245. EXPECT_EQ(JSON_DATA, res->body);
  4246. }
  4247. TEST_F(ServerTest, Issue1772) {
  4248. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4249. ASSERT_TRUE(res);
  4250. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4251. }
  4252. TEST_F(ServerTest, Issue609) {
  4253. auto res = cli_.Delete("/issue609");
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::OK_200, res->status);
  4256. EXPECT_EQ(std::string("ok"), res->body);
  4257. }
  4258. TEST_F(ServerTest, GetStreamedChunked) {
  4259. auto res = cli_.Get("/streamed-chunked");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ(std::string("123456789"), res->body);
  4263. }
  4264. TEST_F(ServerTest, GetStreamedChunked2) {
  4265. auto res = cli_.Get("/streamed-chunked2");
  4266. ASSERT_TRUE(res);
  4267. EXPECT_EQ(StatusCode::OK_200, res->status);
  4268. EXPECT_EQ(std::string("123456789"), res->body);
  4269. }
  4270. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4271. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4272. ASSERT_TRUE(res);
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ(std::string("123456789"), res->body);
  4275. EXPECT_TRUE(res->has_header("Trailer"));
  4276. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4277. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4278. // Trailers are now stored separately from headers (security fix)
  4279. EXPECT_EQ(2U, res->trailers.size());
  4280. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4281. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4282. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4283. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4284. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4285. // Verify trailers are NOT in headers (security verification)
  4286. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4287. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4288. }
  4289. TEST_F(ServerTest, LargeChunkedPost) {
  4290. Request req;
  4291. req.method = "POST";
  4292. req.path = "/large-chunked";
  4293. std::string host_and_port;
  4294. host_and_port += HOST;
  4295. host_and_port += ":";
  4296. host_and_port += std::to_string(PORT);
  4297. req.headers.emplace("Host", host_and_port.c_str());
  4298. req.headers.emplace("Accept", "*/*");
  4299. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4300. req.headers.emplace("Content-Type", "text/plain");
  4301. req.headers.emplace("Content-Length", "0");
  4302. req.headers.emplace("Transfer-Encoding", "chunked");
  4303. std::string long_string(30 * 1024u, 'a');
  4304. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4305. // Attempt to make a large enough post to exceed OS buffers, to test that
  4306. // the server handles short reads if the full chunk data isn't available.
  4307. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4308. auto res = std::make_shared<Response>();
  4309. auto error = Error::Success;
  4310. auto ret = cli_.send(req, *res, error);
  4311. ASSERT_TRUE(ret);
  4312. EXPECT_EQ(StatusCode::OK_200, res->status);
  4313. }
  4314. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4315. auto res = cli_.Get("/remote_addr");
  4316. ASSERT_TRUE(res);
  4317. EXPECT_EQ(StatusCode::OK_200, res->status);
  4318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4319. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4320. }
  4321. TEST_F(ServerTest, GetMethodLocalAddr) {
  4322. auto res = cli_.Get("/local_addr");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::OK_200, res->status);
  4325. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4326. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4327. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4328. }
  4329. TEST_F(ServerTest, HTTPResponseSplitting) {
  4330. auto res = cli_.Get("/http_response_splitting");
  4331. ASSERT_TRUE(res);
  4332. EXPECT_EQ(StatusCode::OK_200, res->status);
  4333. }
  4334. TEST_F(ServerTest, SlowRequest) {
  4335. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4336. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4337. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4338. }
  4339. #if 0
  4340. TEST_F(ServerTest, SlowPost) {
  4341. char buffer[64 * 1024];
  4342. memset(buffer, 0x42, sizeof(buffer));
  4343. auto res = cli_.Post(
  4344. "/slowpost", 64 * 1024 * 1024,
  4345. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4346. auto ret = sink.write(buffer, sizeof(buffer));
  4347. EXPECT_TRUE(ret);
  4348. return true;
  4349. },
  4350. "text/plain");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. }
  4354. TEST_F(ServerTest, SlowPostFail) {
  4355. char buffer[64 * 1024];
  4356. memset(buffer, 0x42, sizeof(buffer));
  4357. cli_.set_write_timeout(std::chrono::seconds(0));
  4358. auto res = cli_.Post(
  4359. "/slowpost", 64 * 1024 * 1024,
  4360. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4361. sink.write(buffer, sizeof(buffer));
  4362. return true;
  4363. },
  4364. "text/plain");
  4365. ASSERT_TRUE(!res);
  4366. EXPECT_EQ(Error::Write, res.error());
  4367. }
  4368. #endif
  4369. TEST_F(ServerTest, Put) {
  4370. auto res = cli_.Put("/put", "PUT", "text/plain");
  4371. ASSERT_TRUE(res);
  4372. EXPECT_EQ(StatusCode::OK_200, res->status);
  4373. EXPECT_EQ("PUT", res->body);
  4374. }
  4375. TEST_F(ServerTest, PutWithContentProvider) {
  4376. auto res = cli_.Put(
  4377. "/put", 3,
  4378. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4379. sink.os << "PUT";
  4380. return true;
  4381. },
  4382. "text/plain");
  4383. ASSERT_TRUE(res);
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. EXPECT_EQ("PUT", res->body);
  4386. }
  4387. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4388. auto res = cli_.Post(
  4389. "/post", 42,
  4390. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4391. return false;
  4392. },
  4393. "text/plain");
  4394. ASSERT_TRUE(!res);
  4395. EXPECT_EQ(Error::Canceled, res.error());
  4396. }
  4397. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4398. auto res = cli_.Put(
  4399. "/put",
  4400. [](size_t /*offset*/, DataSink &sink) {
  4401. sink.os << "PUT";
  4402. sink.done();
  4403. return true;
  4404. },
  4405. "text/plain");
  4406. ASSERT_TRUE(res);
  4407. EXPECT_EQ(StatusCode::OK_200, res->status);
  4408. EXPECT_EQ("PUT", res->body);
  4409. }
  4410. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4411. auto res = cli_.Post(
  4412. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4413. "text/plain");
  4414. ASSERT_TRUE(!res);
  4415. EXPECT_EQ(Error::Canceled, res.error());
  4416. }
  4417. TEST_F(ServerTest, PostLoopBack) {
  4418. std::string body;
  4419. auto res = cli_.Post(
  4420. "/post-loopback", 9,
  4421. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4422. EXPECT_EQ(9u, length);
  4423. sink.write("123", 3);
  4424. sink.write("456", 3);
  4425. sink.write("789", 3);
  4426. return true;
  4427. },
  4428. "text/plain",
  4429. [&body](const char *data, size_t data_length) {
  4430. body.append(data, data_length);
  4431. return true;
  4432. });
  4433. ASSERT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. EXPECT_EQ("123456789", body);
  4436. }
  4437. TEST_F(ServerTest, PutLoopBack) {
  4438. std::string body;
  4439. auto res = cli_.Put(
  4440. "/put-loopback", 9,
  4441. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4442. EXPECT_EQ(9u, length);
  4443. sink.write("123", 3);
  4444. sink.write("456", 3);
  4445. sink.write("789", 3);
  4446. return true;
  4447. },
  4448. "text/plain",
  4449. [&body](const char *data, size_t data_length) {
  4450. body.append(data, data_length);
  4451. return true;
  4452. });
  4453. ASSERT_TRUE(res);
  4454. EXPECT_EQ(StatusCode::OK_200, res->status);
  4455. EXPECT_EQ("123456789", body);
  4456. }
  4457. TEST_F(ServerTest, PatchLoopBack) {
  4458. std::string body;
  4459. auto res = cli_.Patch(
  4460. "/patch-loopback", 9,
  4461. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4462. EXPECT_EQ(9u, length);
  4463. sink.write("123", 3);
  4464. sink.write("456", 3);
  4465. sink.write("789", 3);
  4466. return true;
  4467. },
  4468. "text/plain",
  4469. [&body](const char *data, size_t data_length) {
  4470. body.append(data, data_length);
  4471. return true;
  4472. });
  4473. ASSERT_TRUE(res);
  4474. EXPECT_EQ(StatusCode::OK_200, res->status);
  4475. EXPECT_EQ("123456789", body);
  4476. }
  4477. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4478. std::string body;
  4479. auto res = cli_.Post(
  4480. "/post-loopback",
  4481. [](size_t /*offset*/, DataSink &sink) {
  4482. sink.write("123", 3);
  4483. sink.write("456", 3);
  4484. sink.write("789", 3);
  4485. sink.done();
  4486. return true;
  4487. },
  4488. "text/plain",
  4489. [&body](const char *data, size_t data_length) {
  4490. body.append(data, data_length);
  4491. return true;
  4492. });
  4493. ASSERT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. EXPECT_EQ("123456789", body);
  4496. }
  4497. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4498. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4499. cli_.set_compress(true);
  4500. auto res = cli_.Put(
  4501. "/put", 3,
  4502. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4503. sink.os << "PUT";
  4504. return true;
  4505. },
  4506. "text/plain");
  4507. ASSERT_TRUE(res);
  4508. EXPECT_EQ(StatusCode::OK_200, res->status);
  4509. EXPECT_EQ("PUT", res->body);
  4510. }
  4511. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4512. cli_.set_compress(true);
  4513. auto res = cli_.Post(
  4514. "/post", 42,
  4515. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4516. return false;
  4517. },
  4518. "text/plain");
  4519. ASSERT_TRUE(!res);
  4520. EXPECT_EQ(Error::Canceled, res.error());
  4521. }
  4522. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4523. cli_.set_compress(true);
  4524. auto res = cli_.Put(
  4525. "/put",
  4526. [](size_t /*offset*/, DataSink &sink) {
  4527. sink.os << "PUT";
  4528. sink.done();
  4529. return true;
  4530. },
  4531. "text/plain");
  4532. ASSERT_TRUE(res);
  4533. EXPECT_EQ(StatusCode::OK_200, res->status);
  4534. EXPECT_EQ("PUT", res->body);
  4535. }
  4536. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4537. cli_.set_compress(true);
  4538. auto res = cli_.Post(
  4539. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4540. "text/plain");
  4541. ASSERT_TRUE(!res);
  4542. EXPECT_EQ(Error::Canceled, res.error());
  4543. }
  4544. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4545. cli_.set_compress(true);
  4546. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4547. ASSERT_TRUE(res);
  4548. EXPECT_EQ(StatusCode::OK_200, res->status);
  4549. EXPECT_EQ(LARGE_DATA, res->body);
  4550. }
  4551. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4552. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4553. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4554. Client cli(s.c_str());
  4555. cli.enable_server_certificate_verification(false);
  4556. #else
  4557. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4558. Client cli(s.c_str());
  4559. #endif
  4560. cli.set_compress(true);
  4561. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4562. ASSERT_TRUE(res);
  4563. EXPECT_EQ(StatusCode::OK_200, res->status);
  4564. EXPECT_EQ(LARGE_DATA, res->body);
  4565. // The compressed size should be less than a 10th of the original. May vary
  4566. // depending on the zlib library.
  4567. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4568. static_cast<uint64_t>(10 * 1024 * 1024));
  4569. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4570. }
  4571. TEST_F(ServerTest, PutContentWithDeflate) {
  4572. cli_.set_compress(false);
  4573. Headers headers;
  4574. headers.emplace("Content-Encoding", "deflate");
  4575. // PUT in deflate format:
  4576. auto res = cli_.Put("/put", headers,
  4577. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. EXPECT_EQ("PUT", res->body);
  4581. }
  4582. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4583. Headers headers;
  4584. headers.emplace("Accept-Encoding", "gzip, deflate");
  4585. auto res = cli_.Get("/streamed-chunked", headers);
  4586. ASSERT_TRUE(res);
  4587. EXPECT_EQ(StatusCode::OK_200, res->status);
  4588. EXPECT_EQ(std::string("123456789"), res->body);
  4589. }
  4590. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4591. Headers headers;
  4592. headers.emplace("Accept-Encoding", "gzip, deflate");
  4593. auto res = cli_.Get("/streamed-chunked2", headers);
  4594. ASSERT_TRUE(res);
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. EXPECT_EQ(std::string("123456789"), res->body);
  4597. }
  4598. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4599. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. TEST(GzipDecompressor, ChunkedDecompression) {
  4604. std::string data;
  4605. for (size_t i = 0; i < 32 * 1024; ++i) {
  4606. data.push_back(static_cast<char>('a' + i % 26));
  4607. }
  4608. std::string compressed_data;
  4609. {
  4610. httplib::detail::gzip_compressor compressor;
  4611. bool result = compressor.compress(
  4612. data.data(), data.size(),
  4613. /*last=*/true,
  4614. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4615. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4616. compressed_data_size);
  4617. return true;
  4618. });
  4619. ASSERT_TRUE(result);
  4620. }
  4621. std::string decompressed_data;
  4622. {
  4623. httplib::detail::gzip_decompressor decompressor;
  4624. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4625. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4626. size_t chunk_size = 130;
  4627. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4628. chunk_begin += chunk_size) {
  4629. size_t current_chunk_size =
  4630. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4631. bool result = decompressor.decompress(
  4632. compressed_data.data() + chunk_begin, current_chunk_size,
  4633. [&](const char *decompressed_data_chunk,
  4634. size_t decompressed_data_chunk_size) {
  4635. decompressed_data.insert(decompressed_data.size(),
  4636. decompressed_data_chunk,
  4637. decompressed_data_chunk_size);
  4638. return true;
  4639. });
  4640. ASSERT_TRUE(result);
  4641. }
  4642. }
  4643. ASSERT_EQ(data, decompressed_data);
  4644. }
  4645. TEST(GzipDecompressor, DeflateDecompression) {
  4646. std::string original_text = "Raw deflate without gzip";
  4647. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4648. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4649. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4650. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4651. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4652. std::string decompressed_data;
  4653. {
  4654. httplib::detail::gzip_decompressor decompressor;
  4655. bool result = decompressor.decompress(
  4656. compressed_data.data(), compressed_data.size(),
  4657. [&](const char *decompressed_data_chunk,
  4658. size_t decompressed_data_chunk_size) {
  4659. decompressed_data.insert(decompressed_data.size(),
  4660. decompressed_data_chunk,
  4661. decompressed_data_chunk_size);
  4662. return true;
  4663. });
  4664. ASSERT_TRUE(result);
  4665. }
  4666. ASSERT_EQ(original_text, decompressed_data);
  4667. }
  4668. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4669. std::string original_text = "Raw deflate without gzip";
  4670. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4671. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4672. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4673. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4674. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4675. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4676. std::string decompressed_data;
  4677. {
  4678. httplib::detail::gzip_decompressor decompressor;
  4679. bool result = decompressor.decompress(
  4680. compressed_data.data(), compressed_data.size(),
  4681. [&](const char *decompressed_data_chunk,
  4682. size_t decompressed_data_chunk_size) {
  4683. decompressed_data.insert(decompressed_data.size(),
  4684. decompressed_data_chunk,
  4685. decompressed_data_chunk_size);
  4686. return true;
  4687. });
  4688. ASSERT_TRUE(result);
  4689. }
  4690. ASSERT_EQ(original_text, decompressed_data);
  4691. }
  4692. #ifdef _WIN32
  4693. TEST(GzipDecompressor, LargeRandomData) {
  4694. // prepare large random data that is difficult to be compressed and is
  4695. // expected to have large size even when compressed
  4696. std::random_device seed_gen;
  4697. std::mt19937 random(seed_gen());
  4698. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4699. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4700. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4701. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4702. // compress data over 4GiB
  4703. std::string compressed_data;
  4704. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4705. httplib::detail::gzip_compressor compressor;
  4706. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4707. data.size() * sizeof(std::uint32_t), true,
  4708. [&](const char *data, size_t size) {
  4709. compressed_data.insert(
  4710. compressed_data.size(), data, size);
  4711. return true;
  4712. });
  4713. ASSERT_TRUE(result);
  4714. // FIXME: compressed data size is expected to be greater than 4GiB,
  4715. // but there is no guarantee
  4716. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4717. // decompress data over 4GiB
  4718. std::string decompressed_data;
  4719. decompressed_data.reserve(data_size);
  4720. httplib::detail::gzip_decompressor decompressor;
  4721. result = decompressor.decompress(
  4722. compressed_data.data(), compressed_data.size(),
  4723. [&](const char *data, size_t size) {
  4724. decompressed_data.insert(decompressed_data.size(), data, size);
  4725. return true;
  4726. });
  4727. ASSERT_TRUE(result);
  4728. // compare
  4729. ASSERT_EQ(data_size, decompressed_data.size());
  4730. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4731. 0);
  4732. }
  4733. #endif
  4734. #endif
  4735. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4736. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4737. Headers headers;
  4738. headers.emplace("Accept-Encoding", "br");
  4739. auto res = cli_.Get("/streamed-chunked", headers);
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. EXPECT_EQ(std::string("123456789"), res->body);
  4743. }
  4744. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4745. Headers headers;
  4746. headers.emplace("Accept-Encoding", "br");
  4747. auto res = cli_.Get("/streamed-chunked2", headers);
  4748. ASSERT_TRUE(res);
  4749. EXPECT_EQ(StatusCode::OK_200, res->status);
  4750. EXPECT_EQ(std::string("123456789"), res->body);
  4751. }
  4752. #endif
  4753. TEST_F(ServerTest, Patch) {
  4754. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4755. ASSERT_TRUE(res);
  4756. EXPECT_EQ(StatusCode::OK_200, res->status);
  4757. EXPECT_EQ("PATCH", res->body);
  4758. }
  4759. TEST_F(ServerTest, Delete) {
  4760. auto res = cli_.Delete("/delete");
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ(StatusCode::OK_200, res->status);
  4763. EXPECT_EQ("DELETE", res->body);
  4764. }
  4765. TEST_F(ServerTest, DeleteContentReceiver) {
  4766. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. EXPECT_EQ("content", res->body);
  4770. }
  4771. TEST_F(ServerTest, Options) {
  4772. auto res = cli_.Options("*");
  4773. ASSERT_TRUE(res);
  4774. EXPECT_EQ(StatusCode::OK_200, res->status);
  4775. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4776. EXPECT_TRUE(res->body.empty());
  4777. }
  4778. TEST_F(ServerTest, URL) {
  4779. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4780. ASSERT_TRUE(res);
  4781. EXPECT_EQ(StatusCode::OK_200, res->status);
  4782. }
  4783. TEST_F(ServerTest, ArrayParam) {
  4784. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4785. ASSERT_TRUE(res);
  4786. EXPECT_EQ(StatusCode::OK_200, res->status);
  4787. }
  4788. TEST_F(ServerTest, NoMultipleHeaders) {
  4789. Headers headers = {{"Content-Length", "5"}};
  4790. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4791. "text/plain");
  4792. ASSERT_TRUE(res);
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. }
  4795. TEST_F(ServerTest, PostContentReceiver) {
  4796. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4797. ASSERT_TRUE(res);
  4798. ASSERT_EQ(StatusCode::OK_200, res->status);
  4799. ASSERT_EQ("content", res->body);
  4800. }
  4801. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4802. UploadFormDataItems items = {
  4803. {"text1", "text default", "", ""},
  4804. {"text2", "aωb", "", ""},
  4805. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4806. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4807. {"file3", "", "", "application/octet-stream"},
  4808. };
  4809. auto res = cli_.Post("/content_receiver", items);
  4810. ASSERT_TRUE(res);
  4811. EXPECT_EQ(StatusCode::OK_200, res->status);
  4812. }
  4813. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4814. UploadFormDataItems items = {
  4815. {"text1", "text default", "", ""},
  4816. {"text2", "aωb", "", ""},
  4817. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4818. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4819. {"file3", "", "", "application/octet-stream"},
  4820. };
  4821. auto boundary = std::string("+++++");
  4822. std::string body;
  4823. for (const auto &item : items) {
  4824. body += "--" + boundary + "\r\n";
  4825. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4826. if (!item.filename.empty()) {
  4827. body += "; filename=\"" + item.filename + "\"";
  4828. }
  4829. body += "\r\n";
  4830. if (!item.content_type.empty()) {
  4831. body += "Content-Type: " + item.content_type + "\r\n";
  4832. }
  4833. body += "\r\n";
  4834. body += item.content + "\r\n";
  4835. }
  4836. body += "--" + boundary + "--\r\n";
  4837. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4838. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::OK_200, res->status);
  4841. }
  4842. TEST_F(ServerTest, PostContentReceiverGzip) {
  4843. cli_.set_compress(true);
  4844. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4845. ASSERT_TRUE(res);
  4846. ASSERT_EQ(StatusCode::OK_200, res->status);
  4847. ASSERT_EQ("content", res->body);
  4848. }
  4849. TEST_F(ServerTest, PutContentReceiver) {
  4850. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4851. ASSERT_TRUE(res);
  4852. ASSERT_EQ(StatusCode::OK_200, res->status);
  4853. ASSERT_EQ("content", res->body);
  4854. }
  4855. TEST_F(ServerTest, PatchContentReceiver) {
  4856. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4857. ASSERT_TRUE(res);
  4858. ASSERT_EQ(StatusCode::OK_200, res->status);
  4859. ASSERT_EQ("content", res->body);
  4860. }
  4861. template <typename ClientType>
  4862. void TestWithHeadersAndContentReceiver(
  4863. ClientType &cli,
  4864. std::function<Result(ClientType &, const std::string &, const Headers &,
  4865. const std::string &, const std::string &,
  4866. ContentReceiver, DownloadProgress)>
  4867. request_func) {
  4868. Headers headers;
  4869. headers.emplace("X-Custom-Header", "test-value");
  4870. std::string received_body;
  4871. auto res = request_func(
  4872. cli, "/content_receiver", headers, "content", "application/json",
  4873. [&](const char *data, size_t data_length) {
  4874. received_body.append(data, data_length);
  4875. return true;
  4876. },
  4877. nullptr);
  4878. ASSERT_TRUE(res);
  4879. EXPECT_EQ(StatusCode::OK_200, res->status);
  4880. EXPECT_EQ("content", received_body);
  4881. }
  4882. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4884. using ClientT = SSLClient;
  4885. #else
  4886. using ClientT = Client;
  4887. #endif
  4888. TestWithHeadersAndContentReceiver<ClientT>(
  4889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4890. const std::string &body, const std::string &content_type,
  4891. ContentReceiver receiver, DownloadProgress progress) {
  4892. return cli.Post(path, headers, body, content_type, receiver, progress);
  4893. });
  4894. }
  4895. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4896. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4897. using ClientT = SSLClient;
  4898. #else
  4899. using ClientT = Client;
  4900. #endif
  4901. TestWithHeadersAndContentReceiver<ClientT>(
  4902. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4903. const std::string &body, const std::string &content_type,
  4904. ContentReceiver receiver, DownloadProgress progress) {
  4905. return cli.Put(path, headers, body, content_type, receiver, progress);
  4906. });
  4907. }
  4908. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4909. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4910. using ClientT = SSLClient;
  4911. #else
  4912. using ClientT = Client;
  4913. #endif
  4914. TestWithHeadersAndContentReceiver<ClientT>(
  4915. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4916. const std::string &body, const std::string &content_type,
  4917. ContentReceiver receiver, DownloadProgress progress) {
  4918. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4919. });
  4920. }
  4921. template <typename ClientType>
  4922. void TestWithHeadersAndContentReceiverWithProgress(
  4923. ClientType &cli,
  4924. std::function<Result(ClientType &, const std::string &, const Headers &,
  4925. const std::string &, const std::string &,
  4926. ContentReceiver, DownloadProgress)>
  4927. request_func) {
  4928. Headers headers;
  4929. headers.emplace("X-Test-Header", "progress-test");
  4930. std::string received_body;
  4931. auto progress_called = false;
  4932. auto res = request_func(
  4933. cli, "/content_receiver", headers, "content", "text/plain",
  4934. [&](const char *data, size_t data_length) {
  4935. received_body.append(data, data_length);
  4936. return true;
  4937. },
  4938. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4939. progress_called = true;
  4940. return true;
  4941. });
  4942. ASSERT_TRUE(res);
  4943. EXPECT_EQ(StatusCode::OK_200, res->status);
  4944. EXPECT_EQ("content", received_body);
  4945. EXPECT_TRUE(progress_called);
  4946. }
  4947. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4949. using ClientT = SSLClient;
  4950. #else
  4951. using ClientT = Client;
  4952. #endif
  4953. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4954. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4955. const std::string &body, const std::string &content_type,
  4956. ContentReceiver receiver, DownloadProgress progress) {
  4957. return cli.Post(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4961. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4962. using ClientT = SSLClient;
  4963. #else
  4964. using ClientT = Client;
  4965. #endif
  4966. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4967. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4968. const std::string &body, const std::string &content_type,
  4969. ContentReceiver receiver, DownloadProgress progress) {
  4970. return cli.Put(path, headers, body, content_type, receiver, progress);
  4971. });
  4972. }
  4973. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4974. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4975. using ClientT = SSLClient;
  4976. #else
  4977. using ClientT = Client;
  4978. #endif
  4979. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4980. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4981. const std::string &body, const std::string &content_type,
  4982. ContentReceiver receiver, DownloadProgress progress) {
  4983. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4984. });
  4985. }
  4986. template <typename ClientType>
  4987. void TestWithHeadersAndContentReceiverError(
  4988. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4989. const Headers &, const std::string &,
  4990. const std::string &, ContentReceiver)>
  4991. request_func) {
  4992. Headers headers;
  4993. headers.emplace("X-Error-Test", "true");
  4994. std::string received_body;
  4995. auto receiver_failed = false;
  4996. auto res =
  4997. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4998. [&](const char *data, size_t data_length) {
  4999. received_body.append(data, data_length);
  5000. receiver_failed = true;
  5001. return false;
  5002. });
  5003. ASSERT_FALSE(res);
  5004. EXPECT_TRUE(receiver_failed);
  5005. }
  5006. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5008. using ClientT = SSLClient;
  5009. #else
  5010. using ClientT = Client;
  5011. #endif
  5012. TestWithHeadersAndContentReceiverError<ClientT>(
  5013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5014. const std::string &body, const std::string &content_type,
  5015. ContentReceiver receiver) {
  5016. return cli.Post(path, headers, body, content_type, receiver);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5021. using ClientT = SSLClient;
  5022. #else
  5023. using ClientT = Client;
  5024. #endif
  5025. TestWithHeadersAndContentReceiverError<ClientT>(
  5026. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5027. const std::string &body, const std::string &content_type,
  5028. ContentReceiver receiver) {
  5029. return cli.Put(path, headers, body, content_type, receiver);
  5030. });
  5031. }
  5032. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5034. using ClientT = SSLClient;
  5035. #else
  5036. using ClientT = Client;
  5037. #endif
  5038. TestWithHeadersAndContentReceiverError<ClientT>(
  5039. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5040. const std::string &body, const std::string &content_type,
  5041. ContentReceiver receiver) {
  5042. return cli.Patch(path, headers, body, content_type, receiver);
  5043. });
  5044. }
  5045. TEST_F(ServerTest, PostQueryStringAndBody) {
  5046. auto res =
  5047. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5048. ASSERT_TRUE(res);
  5049. ASSERT_EQ(StatusCode::OK_200, res->status);
  5050. }
  5051. TEST_F(ServerTest, HTTP2Magic) {
  5052. Request req;
  5053. req.method = "PRI";
  5054. req.path = "*";
  5055. req.body = "SM";
  5056. auto res = std::make_shared<Response>();
  5057. auto error = Error::Success;
  5058. auto ret = cli_.send(req, *res, error);
  5059. ASSERT_TRUE(ret);
  5060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5061. }
  5062. TEST_F(ServerTest, KeepAlive) {
  5063. auto res = cli_.Get("/hi");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5067. EXPECT_EQ("Hello World!", res->body);
  5068. res = cli_.Get("/hi");
  5069. ASSERT_TRUE(res);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5072. EXPECT_EQ("Hello World!", res->body);
  5073. res = cli_.Get("/hi");
  5074. ASSERT_TRUE(res);
  5075. EXPECT_EQ(StatusCode::OK_200, res->status);
  5076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5077. EXPECT_EQ("Hello World!", res->body);
  5078. res = cli_.Get("/not-exist");
  5079. ASSERT_TRUE(res);
  5080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5081. res = cli_.Post("/empty", "", "text/plain");
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(StatusCode::OK_200, res->status);
  5084. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5085. EXPECT_EQ("empty", res->body);
  5086. EXPECT_EQ("close", res->get_header_value("Connection"));
  5087. res = cli_.Post(
  5088. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5089. "text/plain");
  5090. ASSERT_TRUE(res);
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5093. EXPECT_EQ("empty", res->body);
  5094. cli_.set_keep_alive(false);
  5095. res = cli_.Get("/last-request");
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ(StatusCode::OK_200, res->status);
  5098. EXPECT_EQ("close", res->get_header_value("Connection"));
  5099. }
  5100. TEST_F(ServerTest, TooManyRedirect) {
  5101. cli_.set_follow_location(true);
  5102. auto res = cli_.Get("/redirect/0");
  5103. ASSERT_TRUE(!res);
  5104. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5105. }
  5106. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5107. Request req;
  5108. req.method = "FOOBAR";
  5109. req.path = "/hi";
  5110. cli_.set_keep_alive(true);
  5111. auto res = cli_.send(req);
  5112. ASSERT_TRUE(res);
  5113. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. EXPECT_FALSE(cli_.is_socket_open());
  5116. }
  5117. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5119. TEST_F(ServerTest, Gzip) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "gzip, deflate");
  5122. auto res = cli_.Get("/compress", headers);
  5123. ASSERT_TRUE(res);
  5124. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5125. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5127. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5128. "7890123456789012345678901234567890",
  5129. res->body);
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. }
  5132. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5133. Headers headers;
  5134. headers.emplace("Accept-Encoding", "");
  5135. auto res = cli_.Get("/compress", headers);
  5136. ASSERT_TRUE(res);
  5137. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5138. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5139. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5140. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5141. "7890123456789012345678901234567890",
  5142. res->body);
  5143. EXPECT_EQ(StatusCode::OK_200, res->status);
  5144. }
  5145. TEST_F(ServerTest, GzipWithContentReceiver) {
  5146. Headers headers;
  5147. headers.emplace("Accept-Encoding", "gzip, deflate");
  5148. std::string body;
  5149. auto res = cli_.Get("/compress", headers,
  5150. [&](const char *data, uint64_t data_length) {
  5151. EXPECT_EQ(100U, data_length);
  5152. body.append(data, data_length);
  5153. return true;
  5154. });
  5155. ASSERT_TRUE(res);
  5156. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5158. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5159. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5160. "7890123456789012345678901234567890",
  5161. body);
  5162. EXPECT_EQ(StatusCode::OK_200, res->status);
  5163. }
  5164. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5165. Headers headers;
  5166. headers.emplace("Accept-Encoding", "gzip, deflate");
  5167. cli_.set_decompress(false);
  5168. auto res = cli_.Get("/compress", headers);
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5173. EXPECT_EQ(33U, res->body.size());
  5174. EXPECT_EQ(StatusCode::OK_200, res->status);
  5175. }
  5176. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5177. Headers headers;
  5178. headers.emplace("Accept-Encoding", "");
  5179. std::string body;
  5180. auto res = cli_.Get("/compress", headers,
  5181. [&](const char *data, uint64_t data_length) {
  5182. EXPECT_EQ(100U, data_length);
  5183. body.append(data, data_length);
  5184. return true;
  5185. });
  5186. ASSERT_TRUE(res);
  5187. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5189. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5190. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5191. "7890123456789012345678901234567890",
  5192. body);
  5193. EXPECT_EQ(StatusCode::OK_200, res->status);
  5194. }
  5195. TEST_F(ServerTest, NoGzip) {
  5196. Headers headers;
  5197. headers.emplace("Accept-Encoding", "gzip, deflate");
  5198. auto res = cli_.Get("/nocompress", headers);
  5199. ASSERT_TRUE(res);
  5200. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5201. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5202. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5203. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5204. "7890123456789012345678901234567890",
  5205. res->body);
  5206. EXPECT_EQ(StatusCode::OK_200, res->status);
  5207. }
  5208. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5209. Headers headers;
  5210. headers.emplace("Accept-Encoding", "gzip, deflate");
  5211. std::string body;
  5212. auto res = cli_.Get("/nocompress", headers,
  5213. [&](const char *data, uint64_t data_length) {
  5214. EXPECT_EQ(100U, data_length);
  5215. body.append(data, data_length);
  5216. return true;
  5217. });
  5218. ASSERT_TRUE(res);
  5219. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5220. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5221. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5222. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5223. "7890123456789012345678901234567890",
  5224. body);
  5225. EXPECT_EQ(StatusCode::OK_200, res->status);
  5226. }
  5227. TEST_F(ServerTest, MultipartFormDataGzip) {
  5228. UploadFormDataItems items = {
  5229. {"key1", "test", "", ""},
  5230. {"key2", "--abcdefg123", "", ""},
  5231. };
  5232. cli_.set_compress(true);
  5233. auto res = cli_.Post("/compress-multipart", items);
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. }
  5237. #endif
  5238. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5239. TEST_F(ServerTest, Brotli) {
  5240. Headers headers;
  5241. headers.emplace("Accept-Encoding", "br");
  5242. auto res = cli_.Get("/compress", headers);
  5243. ASSERT_TRUE(res);
  5244. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5246. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5247. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5248. "7890123456789012345678901234567890",
  5249. res->body);
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. }
  5252. #endif
  5253. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5254. TEST_F(ServerTest, Zstd) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "zstd");
  5257. auto res = cli_.Get("/compress", headers);
  5258. ASSERT_TRUE(res);
  5259. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5261. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5262. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5263. "7890123456789012345678901234567890",
  5264. res->body);
  5265. EXPECT_EQ(StatusCode::OK_200, res->status);
  5266. }
  5267. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("100", 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. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5281. Headers headers;
  5282. headers.emplace("Accept-Encoding", "zstd");
  5283. std::string body;
  5284. auto res = cli_.Get("/compress", headers,
  5285. [&](const char *data, uint64_t data_length) {
  5286. EXPECT_EQ(100U, data_length);
  5287. body.append(data, data_length);
  5288. return true;
  5289. });
  5290. ASSERT_TRUE(res);
  5291. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5293. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5294. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5295. "7890123456789012345678901234567890",
  5296. body);
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. }
  5299. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5300. Headers headers;
  5301. headers.emplace("Accept-Encoding", "zstd");
  5302. cli_.set_decompress(false);
  5303. auto res = cli_.Get("/compress", headers);
  5304. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5305. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5306. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5307. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5308. ASSERT_TRUE(res);
  5309. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5311. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5312. EXPECT_EQ(StatusCode::OK_200, res->status);
  5313. ASSERT_EQ(26U, res->body.size());
  5314. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5315. 0);
  5316. }
  5317. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5318. Headers headers;
  5319. headers.emplace("Accept-Encoding", "");
  5320. std::string body;
  5321. auto res = cli_.Get("/compress", headers,
  5322. [&](const char *data, uint64_t data_length) {
  5323. EXPECT_EQ(100U, data_length);
  5324. body.append(data, data_length);
  5325. return true;
  5326. });
  5327. ASSERT_TRUE(res);
  5328. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5330. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5331. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5332. "7890123456789012345678901234567890",
  5333. body);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. }
  5336. TEST_F(ServerTest, NoZstd) {
  5337. Headers headers;
  5338. headers.emplace("Accept-Encoding", "zstd");
  5339. auto res = cli_.Get("/nocompress", headers);
  5340. ASSERT_TRUE(res);
  5341. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5342. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5343. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5344. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5345. "7890123456789012345678901234567890",
  5346. res->body);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. }
  5349. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5350. Headers headers;
  5351. headers.emplace("Accept-Encoding", "zstd");
  5352. std::string body;
  5353. auto res = cli_.Get("/nocompress", headers,
  5354. [&](const char *data, uint64_t data_length) {
  5355. EXPECT_EQ(100U, data_length);
  5356. body.append(data, data_length);
  5357. return true;
  5358. });
  5359. ASSERT_TRUE(res);
  5360. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5361. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5362. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5363. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5364. "7890123456789012345678901234567890",
  5365. body);
  5366. EXPECT_EQ(StatusCode::OK_200, res->status);
  5367. }
  5368. // TODO: How to enable zstd ??
  5369. TEST_F(ServerTest, MultipartFormDataZstd) {
  5370. UploadFormDataItems items = {
  5371. {"key1", "test", "", ""},
  5372. {"key2", "--abcdefg123", "", ""},
  5373. };
  5374. Headers headers;
  5375. headers.emplace("Accept-Encoding", "zstd");
  5376. cli_.set_compress(true);
  5377. auto res = cli_.Post("/compress-multipart", headers, items);
  5378. ASSERT_TRUE(res);
  5379. EXPECT_EQ(StatusCode::OK_200, res->status);
  5380. }
  5381. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5382. Headers headers;
  5383. headers.emplace("Accept-Encoding", "zstd");
  5384. cli_.set_compress(true);
  5385. auto res = cli_.Put(
  5386. "/put", headers, 3,
  5387. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5388. sink.os << "PUT";
  5389. return true;
  5390. },
  5391. "text/plain");
  5392. ASSERT_TRUE(res);
  5393. EXPECT_EQ(StatusCode::OK_200, res->status);
  5394. EXPECT_EQ("PUT", res->body);
  5395. }
  5396. // Pre-compression logging tests
  5397. TEST_F(ServerTest, PreCompressionLogging) {
  5398. // Test data for compression (matches the actual /compress endpoint content)
  5399. const std::string test_content =
  5400. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5401. "3456789012345678901234567890";
  5402. // Variables to capture logging data
  5403. std::string pre_compression_body;
  5404. std::string pre_compression_content_type;
  5405. std::string pre_compression_content_encoding;
  5406. std::string post_compression_body;
  5407. std::string post_compression_content_type;
  5408. std::string post_compression_content_encoding;
  5409. // Set up pre-compression logger
  5410. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5411. const Response &res) {
  5412. pre_compression_body = res.body;
  5413. pre_compression_content_type = res.get_header_value("Content-Type");
  5414. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5415. });
  5416. // Set up post-compression logger
  5417. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5418. post_compression_body = res.body;
  5419. post_compression_content_type = res.get_header_value("Content-Type");
  5420. post_compression_content_encoding =
  5421. res.get_header_value("Content-Encoding");
  5422. });
  5423. // Test with gzip compression
  5424. Headers headers;
  5425. headers.emplace("Accept-Encoding", "gzip");
  5426. auto res = cli_.Get("/compress", headers);
  5427. // Verify response was compressed
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5431. // Verify pre-compression logger captured uncompressed content
  5432. EXPECT_EQ(test_content, pre_compression_body);
  5433. EXPECT_EQ("text/plain", pre_compression_content_type);
  5434. EXPECT_TRUE(pre_compression_content_encoding
  5435. .empty()); // No encoding header before compression
  5436. // Verify post-compression logger captured compressed content
  5437. EXPECT_NE(test_content,
  5438. post_compression_body); // Should be different after compression
  5439. EXPECT_EQ("text/plain", post_compression_content_type);
  5440. EXPECT_EQ("gzip", post_compression_content_encoding);
  5441. // Verify compressed content is smaller
  5442. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5443. }
  5444. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5445. const std::string test_content =
  5446. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5447. "3456789012345678901234567890";
  5448. std::string pre_compression_body;
  5449. std::string post_compression_body;
  5450. svr_.set_pre_compression_logger(
  5451. [&](const Request & /*req*/, const Response &res) {
  5452. pre_compression_body = res.body;
  5453. });
  5454. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5455. post_compression_body = res.body;
  5456. });
  5457. Headers headers;
  5458. headers.emplace("Accept-Encoding", "br");
  5459. auto res = cli_.Get("/compress", headers);
  5460. ASSERT_TRUE(res);
  5461. EXPECT_EQ(StatusCode::OK_200, res->status);
  5462. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5463. // Verify pre-compression content is uncompressed
  5464. EXPECT_EQ(test_content, pre_compression_body);
  5465. // Verify post-compression content is compressed
  5466. EXPECT_NE(test_content, post_compression_body);
  5467. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5468. }
  5469. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5470. const std::string test_content =
  5471. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5472. "3456789012345678901234567890";
  5473. std::string pre_compression_body;
  5474. std::string post_compression_body;
  5475. svr_.set_pre_compression_logger(
  5476. [&](const Request & /*req*/, const Response &res) {
  5477. pre_compression_body = res.body;
  5478. });
  5479. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5480. post_compression_body = res.body;
  5481. });
  5482. // Request without compression (use /nocompress endpoint)
  5483. Headers headers;
  5484. auto res = cli_.Get("/nocompress", headers);
  5485. ASSERT_TRUE(res);
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5488. // Pre-compression logger should not be called when no compression is applied
  5489. EXPECT_TRUE(
  5490. pre_compression_body.empty()); // Pre-compression logger not called
  5491. EXPECT_EQ(
  5492. test_content,
  5493. post_compression_body); // Post-compression logger captures final content
  5494. }
  5495. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5496. const std::string test_content =
  5497. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5498. "3456789012345678901234567890";
  5499. std::string pre_compression_body;
  5500. bool pre_logger_called = false;
  5501. // Set only pre-compression logger
  5502. svr_.set_pre_compression_logger(
  5503. [&](const Request & /*req*/, const Response &res) {
  5504. pre_compression_body = res.body;
  5505. pre_logger_called = true;
  5506. });
  5507. Headers headers;
  5508. headers.emplace("Accept-Encoding", "gzip");
  5509. auto res = cli_.Get("/compress", headers);
  5510. ASSERT_TRUE(res);
  5511. EXPECT_EQ(StatusCode::OK_200, res->status);
  5512. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5513. // Verify pre-compression logger was called
  5514. EXPECT_TRUE(pre_logger_called);
  5515. EXPECT_EQ(test_content, pre_compression_body);
  5516. }
  5517. TEST(ZstdDecompressor, ChunkedDecompression) {
  5518. std::string data;
  5519. for (size_t i = 0; i < 32 * 1024; ++i) {
  5520. data.push_back(static_cast<char>('a' + i % 26));
  5521. }
  5522. std::string compressed_data;
  5523. {
  5524. httplib::detail::zstd_compressor compressor;
  5525. bool result = compressor.compress(
  5526. data.data(), data.size(),
  5527. /*last=*/true,
  5528. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5529. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5530. compressed_data_size);
  5531. return true;
  5532. });
  5533. ASSERT_TRUE(result);
  5534. }
  5535. std::string decompressed_data;
  5536. {
  5537. httplib::detail::zstd_decompressor decompressor;
  5538. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5539. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5540. size_t chunk_size = 130;
  5541. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5542. chunk_begin += chunk_size) {
  5543. size_t current_chunk_size =
  5544. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5545. bool result = decompressor.decompress(
  5546. compressed_data.data() + chunk_begin, current_chunk_size,
  5547. [&](const char *decompressed_data_chunk,
  5548. size_t decompressed_data_chunk_size) {
  5549. decompressed_data.insert(decompressed_data.size(),
  5550. decompressed_data_chunk,
  5551. decompressed_data_chunk_size);
  5552. return true;
  5553. });
  5554. ASSERT_TRUE(result);
  5555. }
  5556. }
  5557. ASSERT_EQ(data, decompressed_data);
  5558. }
  5559. TEST(ZstdDecompressor, Decompress) {
  5560. std::string original_text = "Compressed with ZSTD";
  5561. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5562. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5563. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5564. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5565. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5566. std::string decompressed_data;
  5567. {
  5568. httplib::detail::zstd_decompressor decompressor;
  5569. bool result = decompressor.decompress(
  5570. compressed_data.data(), compressed_data.size(),
  5571. [&](const char *decompressed_data_chunk,
  5572. size_t decompressed_data_chunk_size) {
  5573. decompressed_data.insert(decompressed_data.size(),
  5574. decompressed_data_chunk,
  5575. decompressed_data_chunk_size);
  5576. return true;
  5577. });
  5578. ASSERT_TRUE(result);
  5579. }
  5580. ASSERT_EQ(original_text, decompressed_data);
  5581. }
  5582. #endif
  5583. // Sends a raw request to a server listening at HOST:PORT.
  5584. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5585. std::string *resp = nullptr) {
  5586. auto error = Error::Success;
  5587. auto client_sock = detail::create_client_socket(
  5588. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5589. /*connection_timeout_sec=*/5, 0,
  5590. /*read_timeout_sec=*/5, 0,
  5591. /*write_timeout_sec=*/5, 0, std::string(), error);
  5592. if (client_sock == INVALID_SOCKET) { return false; }
  5593. auto ret = detail::process_client_socket(
  5594. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5595. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5596. if (req.size() !=
  5597. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5598. return false;
  5599. }
  5600. char buf[512];
  5601. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5602. while (line_reader.getline()) {
  5603. if (resp) { *resp += line_reader.ptr(); }
  5604. }
  5605. return true;
  5606. });
  5607. detail::close_socket(client_sock);
  5608. return ret;
  5609. }
  5610. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5611. Server svr;
  5612. std::string header_value;
  5613. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5614. header_value = req.get_header_value("foo");
  5615. res.set_content("ok", "text/plain");
  5616. });
  5617. thread t = thread([&] { svr.listen(HOST, PORT); });
  5618. auto se = detail::scope_exit([&] {
  5619. svr.stop();
  5620. t.join();
  5621. ASSERT_FALSE(svr.is_running());
  5622. });
  5623. svr.wait_until_ready();
  5624. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5625. // like characters are not treated the same - use vertical tab and escape.
  5626. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5627. "foo: \t \v bar \x1B\t \r\n"
  5628. "Connection: close\r\n"
  5629. "\r\n";
  5630. std::string res;
  5631. ASSERT_TRUE(send_request(5, req, &res));
  5632. EXPECT_EQ(header_value, "");
  5633. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5634. }
  5635. // Sends a raw request and verifies that there isn't a crash or exception.
  5636. static void test_raw_request(const std::string &req,
  5637. std::string *out = nullptr) {
  5638. Server svr;
  5639. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5640. res.set_content("ok", "text/plain");
  5641. });
  5642. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. svr.Get("/header_field_value_check",
  5646. [&](const Request & /*req*/, Response &res) {
  5647. res.set_content("ok", "text/plain");
  5648. });
  5649. // Server read timeout must be longer than the client read timeout for the
  5650. // bug to reproduce, probably to force the server to process a request
  5651. // without a trailing blank line.
  5652. const time_t client_read_timeout_sec = 1;
  5653. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5654. bool listen_thread_ok = false;
  5655. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5656. auto se = detail::scope_exit([&] {
  5657. svr.stop();
  5658. t.join();
  5659. ASSERT_FALSE(svr.is_running());
  5660. EXPECT_TRUE(listen_thread_ok);
  5661. });
  5662. svr.wait_until_ready();
  5663. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5664. }
  5665. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5666. // A certain header line causes an exception if the header property is parsed
  5667. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5668. test_raw_request(
  5669. "GET /hi HTTP/1.1\r\n"
  5670. " : "
  5671. " "
  5672. " ");
  5673. }
  5674. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5675. // A certain header line causes an exception if the header property *name* is
  5676. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5677. // greedy matcher and requires backtracking when there are a lot of ":"
  5678. // characters.
  5679. // This occurs with libc++ but not libstdc++.
  5680. test_raw_request(
  5681. "GET /hi HTTP/1.1\r\n"
  5682. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5683. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5684. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5685. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5686. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5687. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5688. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5689. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5690. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5691. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5692. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5693. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5694. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5695. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5696. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5697. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5698. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5699. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5700. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5701. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5702. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5703. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5704. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5705. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5706. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5707. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5708. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5709. "&&&%%%");
  5710. }
  5711. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5712. // Make sure this doesn't crash the server.
  5713. // In a previous version of the header line regex, the "\r" rendered the line
  5714. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5715. // a new position where the leading white space ended and the field value
  5716. // began.
  5717. // The crash occurs with libc++ but not libstdc++.
  5718. test_raw_request("GET /hi HTTP/1.1\r\n"
  5719. "a:" +
  5720. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5721. "\r\n"
  5722. "\r\n");
  5723. }
  5724. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5725. std::string out;
  5726. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5727. "Content-Type: text/plain\r\n"
  5728. "Transfer-Encoding: chunked\r\n"
  5729. "\r\n"
  5730. "nothex\r\n",
  5731. &out);
  5732. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5733. }
  5734. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5735. std::string out;
  5736. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5737. "Content-Type: text/plain\r\n"
  5738. "Transfer-Encoding: chunked\r\n"
  5739. "\r\n"
  5740. "3\r\n"
  5741. "xyz\r\n"
  5742. "NaN\r\n",
  5743. &out);
  5744. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5745. }
  5746. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5747. std::string out;
  5748. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5749. "Content-Type: text/plain\r\n"
  5750. "Transfer-Encoding: chunked\r\n"
  5751. "\r\n"
  5752. // Length is too large for 64 bits.
  5753. "1ffffffffffffffff\r\n"
  5754. "xyz\r\n",
  5755. &out);
  5756. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5757. }
  5758. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5759. test_raw_request("GET /hi HTTP/1.1\r\n"
  5760. "Content-Type: text/plain\r\n\r");
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5763. std::string out;
  5764. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5765. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5766. }
  5767. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5768. std::string out;
  5769. std::string request(
  5770. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5771. test_raw_request(request, &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5775. std::string out;
  5776. std::string request(
  5777. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5778. test_raw_request(request, &out);
  5779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5780. }
  5781. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5782. std::string out;
  5783. std::string request(
  5784. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5785. test_raw_request(request, &out);
  5786. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5787. }
  5788. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5789. std::string out;
  5790. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5791. "Test: \r\n\r\n",
  5792. &out);
  5793. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5794. }
  5795. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5796. Server svr;
  5797. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5798. res.set_header("Cache-Control", "no-cache");
  5799. res.set_chunked_content_provider(
  5800. "text/event-stream", [](size_t offset, DataSink &sink) {
  5801. std::string s = "data:";
  5802. s += std::to_string(offset);
  5803. s += "\n\n";
  5804. auto ret = sink.write(s.data(), s.size());
  5805. EXPECT_TRUE(ret);
  5806. std::this_thread::sleep_for(std::chrono::seconds(1));
  5807. return true;
  5808. });
  5809. });
  5810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5811. svr.wait_until_ready();
  5812. Client client(HOST, PORT);
  5813. const Headers headers = {{"Accept", "text/event-stream"}};
  5814. auto get_thread = std::thread([&client, &headers]() {
  5815. auto res = client.Get(
  5816. "/events", headers,
  5817. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5818. });
  5819. auto se = detail::scope_exit([&] {
  5820. svr.stop();
  5821. get_thread.join();
  5822. listen_thread.join();
  5823. ASSERT_FALSE(svr.is_running());
  5824. });
  5825. // Give GET time to get a few messages.
  5826. std::this_thread::sleep_for(std::chrono::seconds(2));
  5827. }
  5828. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5829. httplib::Server svr;
  5830. svr.Post("/hi",
  5831. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5832. res.status = StatusCode::OK_200;
  5833. });
  5834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5835. svr.wait_until_ready();
  5836. Client cli(HOST, PORT);
  5837. auto res = cli.Post("/hi", "data", "text/plain");
  5838. ASSERT_TRUE(res);
  5839. EXPECT_EQ(StatusCode::OK_200, res->status);
  5840. svr.stop();
  5841. thread.join();
  5842. ASSERT_FALSE(svr.is_running());
  5843. res = cli.Post("/hi", "data", "text/plain");
  5844. ASSERT_FALSE(res);
  5845. }
  5846. TEST(ServerStopTest, ListenFailure) {
  5847. Server svr;
  5848. auto t = thread([&]() {
  5849. auto ret = svr.listen("????", PORT);
  5850. EXPECT_FALSE(ret);
  5851. });
  5852. svr.wait_until_ready();
  5853. svr.stop();
  5854. t.join();
  5855. }
  5856. TEST(ServerStopTest, Decommision) {
  5857. Server svr;
  5858. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5859. for (int i = 0; i < 4; i++) {
  5860. auto is_even = !(i % 2);
  5861. std::thread t{[&] {
  5862. try {
  5863. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5864. if (is_even) {
  5865. throw std::runtime_error("Some thing that happens to go wrong.");
  5866. }
  5867. svr.listen(HOST, PORT);
  5868. } catch (...) { svr.decommission(); }
  5869. }};
  5870. svr.wait_until_ready();
  5871. // Server is up
  5872. {
  5873. Client cli(HOST, PORT);
  5874. auto res = cli.Get("/hi");
  5875. if (is_even) {
  5876. EXPECT_FALSE(res);
  5877. } else {
  5878. EXPECT_TRUE(res);
  5879. EXPECT_EQ("hi...", res->body);
  5880. }
  5881. }
  5882. svr.stop();
  5883. t.join();
  5884. // Server is down...
  5885. {
  5886. Client cli(HOST, PORT);
  5887. auto res = cli.Get("/hi");
  5888. EXPECT_FALSE(res);
  5889. }
  5890. }
  5891. }
  5892. // Helper function for string body upload progress tests
  5893. template <typename SetupHandler, typename ClientCall>
  5894. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5895. ClientCall &&client_call,
  5896. const string &body) {
  5897. Server svr;
  5898. setup_handler(svr);
  5899. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5900. auto se = detail::scope_exit([&] {
  5901. svr.stop();
  5902. t.join();
  5903. });
  5904. svr.wait_until_ready();
  5905. Client cli(HOST, PORT);
  5906. vector<uint64_t> progress_values;
  5907. bool progress_called = false;
  5908. auto res =
  5909. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5910. progress_values.push_back(current);
  5911. progress_called = true;
  5912. return true;
  5913. });
  5914. ASSERT_TRUE(res);
  5915. EXPECT_EQ(200, res->status);
  5916. EXPECT_TRUE(progress_called);
  5917. }
  5918. TEST(UploadProgressTest, PostStringBodyBasic) {
  5919. TestStringBodyUploadProgress(
  5920. [](Server &svr) {
  5921. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5922. res.set_content("received", "text/plain");
  5923. });
  5924. },
  5925. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5926. return cli.Post("/test", body, "text/plain", progress_callback);
  5927. },
  5928. "test data for upload progress");
  5929. }
  5930. TEST(UploadProgressTest, PutStringBodyBasic) {
  5931. TestStringBodyUploadProgress(
  5932. [](Server &svr) {
  5933. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5934. res.set_content("put received", "text/plain");
  5935. });
  5936. },
  5937. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5938. return cli.Put("/test", body, "text/plain", progress_callback);
  5939. },
  5940. "put test data for upload progress");
  5941. }
  5942. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5943. TestStringBodyUploadProgress(
  5944. [](Server &svr) {
  5945. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5946. res.set_content("patch received", "text/plain");
  5947. });
  5948. },
  5949. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5950. return cli.Patch("/test", body, "text/plain", progress_callback);
  5951. },
  5952. "patch test data for upload progress");
  5953. }
  5954. // Helper function for content provider upload progress tests
  5955. template <typename SetupHandler, typename ClientCall>
  5956. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5957. ClientCall &&client_call) {
  5958. Server svr;
  5959. setup_handler(svr);
  5960. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. });
  5965. svr.wait_until_ready();
  5966. Client cli(HOST, PORT);
  5967. vector<uint64_t> progress_values;
  5968. auto res =
  5969. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5970. progress_values.push_back(current);
  5971. return true;
  5972. });
  5973. ASSERT_TRUE(res);
  5974. EXPECT_EQ(200, res->status);
  5975. EXPECT_FALSE(progress_values.empty());
  5976. }
  5977. TEST(UploadProgressTest, PostContentProviderProgress) {
  5978. TestContentProviderUploadProgress(
  5979. [](Server &svr) {
  5980. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5981. res.set_content("provider received", "text/plain");
  5982. });
  5983. },
  5984. [](Client &cli, UploadProgress progress_callback) {
  5985. return cli.Post(
  5986. "/test", 10,
  5987. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5988. sink.os << "test data";
  5989. return true;
  5990. },
  5991. "text/plain", progress_callback);
  5992. });
  5993. }
  5994. // Helper function for multipart upload progress tests
  5995. template <typename SetupHandler, typename ClientCall>
  5996. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5997. ClientCall &&client_call,
  5998. const string &endpoint) {
  5999. Server svr;
  6000. setup_handler(svr);
  6001. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6002. auto se = detail::scope_exit([&] {
  6003. svr.stop();
  6004. t.join();
  6005. });
  6006. svr.wait_until_ready();
  6007. Client cli(HOST, PORT);
  6008. vector<uint64_t> progress_values;
  6009. UploadFormDataItems items = {
  6010. {"field1", "value1", "", ""},
  6011. {"field2", "longer value for progress tracking test", "", ""},
  6012. {"file1", "file content data for upload progress", "test.txt",
  6013. "text/plain"}};
  6014. auto res = client_call(cli, endpoint, items,
  6015. [&](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, PostMultipartProgress) {
  6024. TestMultipartUploadProgress(
  6025. [](Server &svr) {
  6026. svr.Post("/multipart", [](const Request &req, Response &res) {
  6027. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6028. res.set_content("multipart received", "text/plain");
  6029. });
  6030. },
  6031. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6032. UploadProgress progress_callback) {
  6033. return cli.Post(endpoint, items, progress_callback);
  6034. },
  6035. "/multipart");
  6036. }
  6037. // Helper function for basic download progress tests
  6038. template <typename SetupHandler, typename ClientCall>
  6039. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6040. ClientCall &&client_call, const string &endpoint,
  6041. size_t expected_content_size) {
  6042. Server svr;
  6043. setup_handler(svr);
  6044. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6045. auto se = detail::scope_exit([&] {
  6046. svr.stop();
  6047. t.join();
  6048. });
  6049. svr.wait_until_ready();
  6050. Client cli(HOST, PORT);
  6051. vector<uint64_t> progress_values;
  6052. auto res = client_call(cli, endpoint,
  6053. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6054. progress_values.push_back(current);
  6055. return true;
  6056. });
  6057. ASSERT_TRUE(res);
  6058. EXPECT_EQ(200, res->status);
  6059. EXPECT_FALSE(progress_values.empty());
  6060. EXPECT_EQ(expected_content_size, res->body.size());
  6061. }
  6062. TEST(DownloadProgressTest, GetBasic) {
  6063. TestBasicDownloadProgress(
  6064. [](Server &svr) {
  6065. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6066. string content(1000, 'D');
  6067. res.set_content(content, "text/plain");
  6068. });
  6069. },
  6070. [](Client &cli, const string &endpoint,
  6071. DownloadProgress progress_callback) {
  6072. return cli.Get(endpoint, progress_callback);
  6073. },
  6074. "/download", 1000u);
  6075. }
  6076. // Helper function for content receiver download progress tests
  6077. template <typename SetupHandler, typename ClientCall>
  6078. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6079. ClientCall &&client_call,
  6080. const string &endpoint,
  6081. size_t expected_content_size) {
  6082. Server svr;
  6083. setup_handler(svr);
  6084. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6085. auto se = detail::scope_exit([&] {
  6086. svr.stop();
  6087. t.join();
  6088. });
  6089. svr.wait_until_ready();
  6090. Client cli(HOST, PORT);
  6091. vector<uint64_t> progress_values;
  6092. string received_body;
  6093. auto res = client_call(
  6094. cli, endpoint,
  6095. [&](const char *data, size_t data_length) -> bool {
  6096. received_body.append(data, data_length);
  6097. return true;
  6098. },
  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, received_body.size());
  6107. EXPECT_TRUE(res->body.empty());
  6108. }
  6109. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6110. TestContentReceiverDownloadProgress(
  6111. [](Server &svr) {
  6112. svr.Get("/download-receiver",
  6113. [](const Request & /*req*/, Response &res) {
  6114. string content(2000, 'R');
  6115. res.set_content(content, "text/plain");
  6116. });
  6117. },
  6118. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6119. DownloadProgress progress_callback) {
  6120. return cli.Get(endpoint, content_receiver, progress_callback);
  6121. },
  6122. "/download-receiver", 2000u);
  6123. }
  6124. TEST(StreamingTest, NoContentLengthStreaming) {
  6125. Server svr;
  6126. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6127. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6128. if (offset < 6) {
  6129. sink.os << (offset < 3 ? "a" : "b");
  6130. } else {
  6131. sink.done();
  6132. }
  6133. return true;
  6134. });
  6135. });
  6136. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6137. auto listen_se = detail::scope_exit([&] {
  6138. svr.stop();
  6139. listen_thread.join();
  6140. ASSERT_FALSE(svr.is_running());
  6141. });
  6142. svr.wait_until_ready();
  6143. Client client(HOST, PORT);
  6144. auto get_thread = std::thread([&client]() {
  6145. std::string s;
  6146. auto res =
  6147. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6148. s += std::string(data, len);
  6149. return true;
  6150. });
  6151. ASSERT_TRUE(res);
  6152. EXPECT_EQ(StatusCode::OK_200, res->status);
  6153. EXPECT_EQ("aaabbb", s);
  6154. });
  6155. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6156. // Give GET time to get a few messages.
  6157. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6158. }
  6159. TEST(MountTest, Unmount) {
  6160. Server svr;
  6161. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6162. auto se = detail::scope_exit([&] {
  6163. svr.stop();
  6164. listen_thread.join();
  6165. ASSERT_FALSE(svr.is_running());
  6166. });
  6167. svr.wait_until_ready();
  6168. Client cli("localhost", PORT);
  6169. svr.set_mount_point("/mount2", "./www2");
  6170. auto res = cli.Get("/");
  6171. ASSERT_TRUE(res);
  6172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6173. res = cli.Get("/mount2/dir/test.html");
  6174. ASSERT_TRUE(res);
  6175. EXPECT_EQ(StatusCode::OK_200, res->status);
  6176. svr.set_mount_point("/", "./www");
  6177. res = cli.Get("/dir/");
  6178. ASSERT_TRUE(res);
  6179. EXPECT_EQ(StatusCode::OK_200, res->status);
  6180. svr.remove_mount_point("/");
  6181. res = cli.Get("/dir/");
  6182. ASSERT_TRUE(res);
  6183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6184. svr.remove_mount_point("/mount2");
  6185. res = cli.Get("/mount2/dir/test.html");
  6186. ASSERT_TRUE(res);
  6187. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6188. }
  6189. TEST(MountTest, Redicect) {
  6190. Server svr;
  6191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6192. auto se = detail::scope_exit([&] {
  6193. svr.stop();
  6194. listen_thread.join();
  6195. ASSERT_FALSE(svr.is_running());
  6196. });
  6197. svr.set_mount_point("/", "./www");
  6198. svr.wait_until_ready();
  6199. Client cli("localhost", PORT);
  6200. auto res = cli.Get("/dir/");
  6201. ASSERT_TRUE(res);
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. res = cli.Get("/dir");
  6204. ASSERT_TRUE(res);
  6205. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6206. res = cli.Get("/file");
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. res = cli.Get("/file/");
  6210. ASSERT_TRUE(res);
  6211. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6212. cli.set_follow_location(true);
  6213. res = cli.Get("/dir");
  6214. ASSERT_TRUE(res);
  6215. EXPECT_EQ(StatusCode::OK_200, res->status);
  6216. }
  6217. TEST(MountTest, MultibytesPathName) {
  6218. Server svr;
  6219. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6220. auto se = detail::scope_exit([&] {
  6221. svr.stop();
  6222. listen_thread.join();
  6223. ASSERT_FALSE(svr.is_running());
  6224. });
  6225. svr.set_mount_point("/", "./www");
  6226. svr.wait_until_ready();
  6227. Client cli("localhost", PORT);
  6228. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6229. ASSERT_TRUE(res);
  6230. EXPECT_EQ(StatusCode::OK_200, res->status);
  6231. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6232. }
  6233. TEST(KeepAliveTest, ReadTimeout) {
  6234. Server svr;
  6235. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6236. std::this_thread::sleep_for(std::chrono::seconds(2));
  6237. res.set_content("a", "text/plain");
  6238. });
  6239. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6240. res.set_content("b", "text/plain");
  6241. });
  6242. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6243. auto se = detail::scope_exit([&] {
  6244. svr.stop();
  6245. listen_thread.join();
  6246. ASSERT_FALSE(svr.is_running());
  6247. });
  6248. svr.wait_until_ready();
  6249. Client cli("localhost", PORT);
  6250. cli.set_keep_alive(true);
  6251. cli.set_read_timeout(std::chrono::seconds(1));
  6252. auto resa = cli.Get("/a");
  6253. ASSERT_FALSE(resa);
  6254. EXPECT_EQ(Error::Read, resa.error());
  6255. auto resb = cli.Get("/b");
  6256. ASSERT_TRUE(resb);
  6257. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6258. EXPECT_EQ("b", resb->body);
  6259. }
  6260. TEST(KeepAliveTest, MaxCount) {
  6261. size_t keep_alive_max_count = 3;
  6262. Server svr;
  6263. svr.set_keep_alive_max_count(keep_alive_max_count);
  6264. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6265. res.set_content("Hello World!", "text/plain");
  6266. });
  6267. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6268. auto se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. listen_thread.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. });
  6273. svr.wait_until_ready();
  6274. Client cli(HOST, PORT);
  6275. cli.set_keep_alive(true);
  6276. for (size_t i = 0; i < 5; i++) {
  6277. auto result = cli.Get("/hi");
  6278. ASSERT_TRUE(result);
  6279. EXPECT_EQ(StatusCode::OK_200, result->status);
  6280. if (i == keep_alive_max_count - 1) {
  6281. EXPECT_EQ("close", result->get_header_value("Connection"));
  6282. } else {
  6283. EXPECT_FALSE(result->has_header("Connection"));
  6284. }
  6285. }
  6286. }
  6287. TEST(KeepAliveTest, Issue1041) {
  6288. Server svr;
  6289. svr.set_keep_alive_timeout(3);
  6290. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6291. res.set_content("Hello World!", "text/plain");
  6292. });
  6293. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6294. auto se = detail::scope_exit([&] {
  6295. svr.stop();
  6296. listen_thread.join();
  6297. ASSERT_FALSE(svr.is_running());
  6298. });
  6299. svr.wait_until_ready();
  6300. Client cli(HOST, PORT);
  6301. cli.set_keep_alive(true);
  6302. auto result = cli.Get("/hi");
  6303. ASSERT_TRUE(result);
  6304. EXPECT_EQ(StatusCode::OK_200, result->status);
  6305. std::this_thread::sleep_for(std::chrono::seconds(5));
  6306. result = cli.Get("/hi");
  6307. ASSERT_TRUE(result);
  6308. EXPECT_EQ(StatusCode::OK_200, result->status);
  6309. }
  6310. TEST(KeepAliveTest, Issue1959) {
  6311. Server svr;
  6312. svr.set_keep_alive_timeout(5);
  6313. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6314. res.set_content("a", "text/plain");
  6315. });
  6316. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6317. auto se = detail::scope_exit([&] {
  6318. if (!svr.is_running()) return;
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. Client cli("localhost", PORT);
  6325. cli.set_keep_alive(true);
  6326. using namespace std::chrono;
  6327. auto start = steady_clock::now();
  6328. cli.Get("/a");
  6329. svr.stop();
  6330. listen_thread.join();
  6331. auto end = steady_clock::now();
  6332. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6333. EXPECT_LT(elapsed, 5000);
  6334. }
  6335. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6336. TEST(KeepAliveTest, SSLClientReconnection) {
  6337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6338. ASSERT_TRUE(svr.is_valid());
  6339. svr.set_keep_alive_timeout(1);
  6340. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6341. res.set_content("Hello World!", "text/plain");
  6342. });
  6343. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6344. auto se = detail::scope_exit([&] {
  6345. svr.stop();
  6346. listen_thread.join();
  6347. ASSERT_FALSE(svr.is_running());
  6348. });
  6349. svr.wait_until_ready();
  6350. SSLClient cli(HOST, PORT);
  6351. cli.enable_server_certificate_verification(false);
  6352. cli.set_keep_alive(true);
  6353. auto result = cli.Get("/hi");
  6354. ASSERT_TRUE(result);
  6355. EXPECT_EQ(StatusCode::OK_200, result->status);
  6356. result = cli.Get("/hi");
  6357. ASSERT_TRUE(result);
  6358. EXPECT_EQ(StatusCode::OK_200, result->status);
  6359. std::this_thread::sleep_for(std::chrono::seconds(2));
  6360. // Recoonect
  6361. result = cli.Get("/hi");
  6362. ASSERT_TRUE(result);
  6363. EXPECT_EQ(StatusCode::OK_200, result->status);
  6364. result = cli.Get("/hi");
  6365. ASSERT_TRUE(result);
  6366. EXPECT_EQ(StatusCode::OK_200, result->status);
  6367. }
  6368. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6370. ASSERT_TRUE(svr.is_valid());
  6371. svr.set_keep_alive_timeout(1);
  6372. std::string content = "reconnect";
  6373. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6374. res.set_content("Hello World!", "text/plain");
  6375. });
  6376. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6377. auto se = detail::scope_exit([&] {
  6378. svr.stop();
  6379. listen_thread.join();
  6380. ASSERT_FALSE(svr.is_running());
  6381. });
  6382. svr.wait_until_ready();
  6383. SSLClient cli(HOST, PORT);
  6384. cli.enable_server_certificate_verification(false);
  6385. cli.set_keep_alive(true);
  6386. auto result = cli.Post(
  6387. "/hi", content.size(),
  6388. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6389. sink.write(content.c_str(), content.size());
  6390. return true;
  6391. },
  6392. "text/plain");
  6393. ASSERT_TRUE(result);
  6394. EXPECT_EQ(200, result->status);
  6395. std::this_thread::sleep_for(std::chrono::seconds(2));
  6396. // Recoonect
  6397. result = cli.Post(
  6398. "/hi", content.size(),
  6399. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6400. sink.write(content.c_str(), content.size());
  6401. return true;
  6402. },
  6403. "text/plain");
  6404. ASSERT_TRUE(result);
  6405. EXPECT_EQ(200, result->status);
  6406. result = cli.Post(
  6407. "/hi", content.size(),
  6408. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6409. sink.write(content.c_str(), content.size());
  6410. return true;
  6411. },
  6412. "text/plain");
  6413. ASSERT_TRUE(result);
  6414. EXPECT_EQ(200, result->status);
  6415. }
  6416. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6417. {
  6418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6419. ASSERT_TRUE(svr.is_valid());
  6420. svr.Get("/sni", [&](const Request &req, Response &res) {
  6421. std::string expected;
  6422. if (req.ssl) {
  6423. if (const char *sni =
  6424. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6425. expected = sni;
  6426. }
  6427. }
  6428. EXPECT_EQ(expected, req.get_param_value("expected"));
  6429. res.set_content("ok", "text/plain");
  6430. });
  6431. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6432. auto se = detail::scope_exit([&] {
  6433. svr.stop();
  6434. listen_thread.join();
  6435. ASSERT_FALSE(svr.is_running());
  6436. });
  6437. svr.wait_until_ready();
  6438. {
  6439. SSLClient cli("localhost", PORT);
  6440. cli.enable_server_certificate_verification(false);
  6441. auto res = cli.Get("/sni?expected=localhost");
  6442. ASSERT_TRUE(res);
  6443. }
  6444. {
  6445. SSLClient cli("::1", PORT);
  6446. cli.enable_server_certificate_verification(false);
  6447. auto res = cli.Get("/sni?expected=");
  6448. // NOTE: This may fail if the server is listening on IPv4 only
  6449. // (e.g., when localhost resolves to 127.0.0.1 only)
  6450. if (res) {
  6451. EXPECT_EQ(StatusCode::OK_200, res->status);
  6452. } else {
  6453. EXPECT_EQ(Error::Connection, res.error());
  6454. }
  6455. }
  6456. }
  6457. }
  6458. #endif
  6459. TEST(ClientProblemDetectionTest, ContentProvider) {
  6460. Server svr;
  6461. size_t content_length = 1024 * 1024;
  6462. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6463. res.set_content_provider(
  6464. content_length, "text/plain",
  6465. [&](size_t offset, size_t length, DataSink &sink) {
  6466. auto out_len = std::min(length, static_cast<size_t>(1024));
  6467. std::string out(out_len, '@');
  6468. sink.write(out.data(), out_len);
  6469. return offset < 4096;
  6470. },
  6471. [](bool success) { ASSERT_FALSE(success); });
  6472. });
  6473. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6474. res.set_content_provider(
  6475. 0, "text/plain",
  6476. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6477. EXPECT_TRUE(false);
  6478. return true;
  6479. },
  6480. [](bool success) { ASSERT_FALSE(success); });
  6481. });
  6482. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6483. auto se = detail::scope_exit([&] {
  6484. svr.stop();
  6485. listen_thread.join();
  6486. ASSERT_FALSE(svr.is_running());
  6487. });
  6488. svr.wait_until_ready();
  6489. Client cli("localhost", PORT);
  6490. {
  6491. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6492. size_t /*data_length*/) { return false; });
  6493. ASSERT_FALSE(res);
  6494. }
  6495. {
  6496. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6497. size_t /*data_length*/) { return false; });
  6498. ASSERT_TRUE(res);
  6499. }
  6500. }
  6501. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6502. Server svr;
  6503. svr.set_error_handler([](Request const &, Response &res) -> void {
  6504. res.set_chunked_content_provider(
  6505. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6506. sink.os << "hello";
  6507. sink.os << "world";
  6508. sink.done();
  6509. return true;
  6510. });
  6511. });
  6512. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6513. auto se = detail::scope_exit([&] {
  6514. svr.stop();
  6515. listen_thread.join();
  6516. ASSERT_FALSE(svr.is_running());
  6517. });
  6518. svr.wait_until_ready();
  6519. Client cli("localhost", PORT);
  6520. auto res = cli.Get("/");
  6521. ASSERT_TRUE(res);
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. EXPECT_EQ("helloworld", res->body);
  6524. }
  6525. TEST(LongPollingTest, ClientCloseDetection) {
  6526. Server svr;
  6527. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6528. res.set_chunked_content_provider(
  6529. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6530. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6531. sink.os << "hello";
  6532. auto count = 10;
  6533. while (count > 0 && sink.is_writable()) {
  6534. this_thread::sleep_for(chrono::milliseconds(10));
  6535. count--;
  6536. }
  6537. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6538. return true;
  6539. });
  6540. });
  6541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.wait_until_ready();
  6548. Client cli("localhost", PORT);
  6549. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6550. EXPECT_EQ("hello", string(data, data_length));
  6551. return false; // close the socket immediately.
  6552. });
  6553. ASSERT_FALSE(res);
  6554. }
  6555. TEST(GetWithParametersTest, GetWithParameters) {
  6556. Server svr;
  6557. svr.Get("/", [&](const Request &req, Response &) {
  6558. EXPECT_EQ("world", req.get_param_value("hello"));
  6559. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6560. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6561. });
  6562. svr.Get("/params", [&](const Request &req, Response &) {
  6563. EXPECT_EQ("world", req.get_param_value("hello"));
  6564. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6565. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6566. });
  6567. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6568. EXPECT_EQ("resource-id", req.matches[1]);
  6569. EXPECT_EQ("foo", req.get_param_value("param1"));
  6570. EXPECT_EQ("bar", req.get_param_value("param2"));
  6571. });
  6572. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6573. EXPECT_EQ("user-id", req.path_params.at("id"));
  6574. EXPECT_EQ("foo", req.get_param_value("param1"));
  6575. EXPECT_EQ("bar", req.get_param_value("param2"));
  6576. });
  6577. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6578. auto se = detail::scope_exit([&] {
  6579. svr.stop();
  6580. listen_thread.join();
  6581. ASSERT_FALSE(svr.is_running());
  6582. });
  6583. svr.wait_until_ready();
  6584. {
  6585. Client cli(HOST, PORT);
  6586. Params params;
  6587. params.emplace("hello", "world");
  6588. params.emplace("hello2", "world2");
  6589. params.emplace("hello3", "world3");
  6590. auto res = cli.Get("/", params, Headers{});
  6591. ASSERT_TRUE(res);
  6592. EXPECT_EQ(StatusCode::OK_200, res->status);
  6593. }
  6594. {
  6595. Client cli(HOST, PORT);
  6596. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6597. ASSERT_TRUE(res);
  6598. EXPECT_EQ(StatusCode::OK_200, res->status);
  6599. }
  6600. {
  6601. Client cli(HOST, PORT);
  6602. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6603. ASSERT_TRUE(res);
  6604. EXPECT_EQ(StatusCode::OK_200, res->status);
  6605. }
  6606. {
  6607. Client cli(HOST, PORT);
  6608. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6609. ASSERT_TRUE(res);
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. }
  6612. }
  6613. TEST(GetWithParametersTest, GetWithParameters2) {
  6614. Server svr;
  6615. svr.Get("/", [&](const Request &req, Response &res) {
  6616. auto text = req.get_param_value("hello");
  6617. res.set_content(text, "text/plain");
  6618. });
  6619. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6620. auto se = detail::scope_exit([&] {
  6621. svr.stop();
  6622. listen_thread.join();
  6623. ASSERT_FALSE(svr.is_running());
  6624. });
  6625. svr.wait_until_ready();
  6626. Client cli("localhost", PORT);
  6627. Params params;
  6628. params.emplace("hello", "world");
  6629. std::string body;
  6630. auto res = cli.Get("/", params, Headers{},
  6631. [&](const char *data, size_t data_length) {
  6632. body.append(data, data_length);
  6633. return true;
  6634. });
  6635. ASSERT_TRUE(res);
  6636. EXPECT_EQ(StatusCode::OK_200, res->status);
  6637. EXPECT_EQ("world", body);
  6638. }
  6639. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6640. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6641. auto host = "httpbin.org";
  6642. auto path = std::string{"/range/32"};
  6643. #else
  6644. auto host = "nghttp2.org";
  6645. auto path = std::string{"/httpbin/range/32"};
  6646. #endif
  6647. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6648. SSLClient cli(host);
  6649. #else
  6650. Client cli(host);
  6651. #endif
  6652. cli.set_default_headers({make_range_header({{1, 10}})});
  6653. cli.set_connection_timeout(5);
  6654. {
  6655. auto res = cli.Get(path);
  6656. ASSERT_TRUE(res);
  6657. EXPECT_EQ("bcdefghijk", res->body);
  6658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6659. }
  6660. {
  6661. auto res = cli.Get(path);
  6662. ASSERT_TRUE(res);
  6663. EXPECT_EQ("bcdefghijk", res->body);
  6664. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6665. }
  6666. }
  6667. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6668. Server svr;
  6669. svr.set_default_headers({{"Hello", "World"}});
  6670. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6671. res.set_content("ok", "text/plain");
  6672. });
  6673. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6674. auto se = detail::scope_exit([&] {
  6675. svr.stop();
  6676. listen_thread.join();
  6677. ASSERT_FALSE(svr.is_running());
  6678. });
  6679. svr.wait_until_ready();
  6680. Client cli("localhost", PORT);
  6681. auto res = cli.Get("/");
  6682. ASSERT_TRUE(res);
  6683. EXPECT_EQ(StatusCode::OK_200, res->status);
  6684. EXPECT_EQ("ok", res->body);
  6685. EXPECT_EQ("World", res->get_header_value("Hello"));
  6686. }
  6687. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6688. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6689. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6690. ASSERT_TRUE(svr.is_valid());
  6691. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6692. std::this_thread::sleep_for(std::chrono::seconds(2));
  6693. res.set_content("a", "text/plain");
  6694. });
  6695. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6696. res.set_content("b", "text/plain");
  6697. });
  6698. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6699. auto se = detail::scope_exit([&] {
  6700. svr.stop();
  6701. listen_thread.join();
  6702. ASSERT_FALSE(svr.is_running());
  6703. });
  6704. svr.wait_until_ready();
  6705. SSLClient cli("localhost", PORT);
  6706. cli.enable_server_certificate_verification(false);
  6707. cli.set_keep_alive(true);
  6708. cli.set_read_timeout(std::chrono::seconds(1));
  6709. auto resa = cli.Get("/a");
  6710. ASSERT_TRUE(!resa);
  6711. EXPECT_EQ(Error::Read, resa.error());
  6712. auto resb = cli.Get("/b");
  6713. ASSERT_TRUE(resb);
  6714. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6715. EXPECT_EQ("b", resb->body);
  6716. }
  6717. #endif
  6718. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6719. protected:
  6720. ServerTestWithAI_PASSIVE()
  6721. : cli_(HOST, PORT)
  6722. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6723. ,
  6724. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6725. #endif
  6726. {
  6727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6728. cli_.enable_server_certificate_verification(false);
  6729. #endif
  6730. }
  6731. virtual void SetUp() {
  6732. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6733. res.set_content("Hello World!", "text/plain");
  6734. });
  6735. t_ = thread(
  6736. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6737. svr_.wait_until_ready();
  6738. }
  6739. virtual void TearDown() {
  6740. svr_.stop();
  6741. t_.join();
  6742. }
  6743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6744. SSLClient cli_;
  6745. SSLServer svr_;
  6746. #else
  6747. Client cli_;
  6748. Server svr_;
  6749. #endif
  6750. thread t_;
  6751. };
  6752. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6753. auto res = cli_.Get("/hi");
  6754. ASSERT_TRUE(res);
  6755. EXPECT_EQ(StatusCode::OK_200, res->status);
  6756. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6757. EXPECT_EQ("Hello World!", res->body);
  6758. }
  6759. class ServerUpDownTest : public ::testing::Test {
  6760. protected:
  6761. ServerUpDownTest() : cli_(HOST, PORT) {}
  6762. virtual void SetUp() {
  6763. t_ = thread([&]() {
  6764. svr_.bind_to_any_port(HOST);
  6765. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6766. ASSERT_TRUE(svr_.listen_after_bind());
  6767. });
  6768. svr_.wait_until_ready();
  6769. }
  6770. virtual void TearDown() {
  6771. svr_.stop();
  6772. t_.join();
  6773. }
  6774. Client cli_;
  6775. Server svr_;
  6776. thread t_;
  6777. };
  6778. TEST_F(ServerUpDownTest, QuickStartStop) {
  6779. // Should not crash, especially when run with
  6780. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6781. }
  6782. class PayloadMaxLengthTest : public ::testing::Test {
  6783. protected:
  6784. PayloadMaxLengthTest()
  6785. : cli_(HOST, PORT)
  6786. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6787. ,
  6788. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6789. #endif
  6790. {
  6791. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6792. cli_.enable_server_certificate_verification(false);
  6793. #endif
  6794. }
  6795. virtual void SetUp() {
  6796. svr_.set_payload_max_length(8);
  6797. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6798. res.set_content("test", "text/plain");
  6799. });
  6800. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6801. svr_.wait_until_ready();
  6802. }
  6803. virtual void TearDown() {
  6804. svr_.stop();
  6805. t_.join();
  6806. }
  6807. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6808. SSLClient cli_;
  6809. SSLServer svr_;
  6810. #else
  6811. Client cli_;
  6812. Server svr_;
  6813. #endif
  6814. thread t_;
  6815. };
  6816. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6817. auto res = cli_.Post("/test", "123456789", "text/plain");
  6818. ASSERT_TRUE(res);
  6819. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6820. res = cli_.Post("/test", "12345678", "text/plain");
  6821. ASSERT_TRUE(res);
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. }
  6824. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6825. // Test chunked encoding with payload exceeding the 8-byte limit
  6826. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6827. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6828. ASSERT_TRUE(res);
  6829. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6830. }
  6831. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6832. // Test chunked encoding with payload within the 8-byte limit
  6833. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6834. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. }
  6838. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6839. // Test using send_request to send chunked data exceeding payload limit
  6840. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6841. "Host: " +
  6842. std::string(HOST) + ":" + std::to_string(PORT) +
  6843. "\r\n"
  6844. "Transfer-Encoding: chunked\r\n"
  6845. "Connection: close\r\n"
  6846. "\r\n"
  6847. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6848. "0123456789\r\n"
  6849. "0\r\n" // End chunk
  6850. "\r\n";
  6851. std::string response;
  6852. bool result = send_request(1, chunked_request, &response);
  6853. if (!result) {
  6854. // If send_request fails, it might be because the server closed the
  6855. // connection due to payload limit enforcement, which is acceptable
  6856. SUCCEED()
  6857. << "Server rejected oversized chunked request (connection closed)";
  6858. } else {
  6859. // If we got a response, check if it's an error response or connection was
  6860. // closed early Short response length indicates connection was closed due to
  6861. // payload limit
  6862. if (response.length() <= 10) {
  6863. SUCCEED() << "Server closed connection for oversized chunked request";
  6864. } else {
  6865. // Check for error status codes
  6866. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6867. response.find("Payload Too Large") != std::string::npos ||
  6868. response.find("400") != std::string::npos);
  6869. }
  6870. }
  6871. }
  6872. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6873. // Test request without Content-Length header exceeding payload limit
  6874. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6875. "Host: " +
  6876. std::string(HOST) + ":" +
  6877. std::to_string(PORT) +
  6878. "\r\n"
  6879. "Connection: close\r\n"
  6880. "\r\n";
  6881. // Add payload exceeding the 8-byte limit
  6882. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6883. request_without_content_length += large_payload;
  6884. std::string response;
  6885. bool result = send_request(1, request_without_content_length, &response);
  6886. if (!result) {
  6887. // If send_request fails, server likely closed connection due to payload
  6888. // limit
  6889. SUCCEED() << "Server rejected oversized request without Content-Length "
  6890. "(connection closed)";
  6891. } else {
  6892. // Check if server responded with error or closed connection early
  6893. if (response.length() <= 10) {
  6894. SUCCEED() << "Server closed connection for oversized request without "
  6895. "Content-Length";
  6896. } else {
  6897. // Check for error status codes
  6898. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6899. response.find("Payload Too Large") != std::string::npos ||
  6900. response.find("400") != std::string::npos);
  6901. }
  6902. }
  6903. }
  6904. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6905. // Test request without Content-Length header within payload limit
  6906. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6907. "Host: " +
  6908. std::string(HOST) + ":" +
  6909. std::to_string(PORT) +
  6910. "\r\n"
  6911. "Connection: close\r\n"
  6912. "\r\n";
  6913. // Add payload within the 8-byte limit
  6914. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6915. request_without_content_length += small_payload;
  6916. std::string response;
  6917. bool result = send_request(1, request_without_content_length, &response);
  6918. // For requests without Content-Length, the server may have different behavior
  6919. // The key is that it should not reject due to payload limit for small
  6920. // payloads
  6921. if (result) {
  6922. // Check for any HTTP response (success or error, but not connection closed)
  6923. if (response.length() > 10) {
  6924. SUCCEED()
  6925. << "Server processed request without Content-Length within limit";
  6926. } else {
  6927. // Short response might indicate connection closed, which is acceptable
  6928. SUCCEED() << "Server closed connection for request without "
  6929. "Content-Length (acceptable behavior)";
  6930. }
  6931. } else {
  6932. // Connection failure might be due to protocol requirements
  6933. SUCCEED() << "Connection issue with request without Content-Length "
  6934. "(environment-specific)";
  6935. }
  6936. }
  6937. class LargePayloadMaxLengthTest : public ::testing::Test {
  6938. protected:
  6939. LargePayloadMaxLengthTest()
  6940. : cli_(HOST, PORT)
  6941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6942. ,
  6943. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6944. #endif
  6945. {
  6946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6947. cli_.enable_server_certificate_verification(false);
  6948. #endif
  6949. }
  6950. virtual void SetUp() {
  6951. // Set 10MB payload limit
  6952. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6953. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6954. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6955. res.set_content("Large payload test", "text/plain");
  6956. });
  6957. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6958. svr_.wait_until_ready();
  6959. }
  6960. virtual void TearDown() {
  6961. svr_.stop();
  6962. t_.join();
  6963. }
  6964. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6965. SSLClient cli_;
  6966. SSLServer svr_;
  6967. #else
  6968. Client cli_;
  6969. Server svr_;
  6970. #endif
  6971. thread t_;
  6972. };
  6973. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6974. // Test chunked encoding with payload within 10MB limit
  6975. std::string medium_payload(5 * 1024 * 1024,
  6976. 'A'); // 5MB payload, within 10MB limit
  6977. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6978. ASSERT_TRUE(res);
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. }
  6981. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6982. // Test chunked encoding with payload exceeding 10MB limit
  6983. std::string large_payload(12 * 1024 * 1024,
  6984. 'B'); // 12MB payload, exceeds 10MB limit
  6985. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6986. ASSERT_TRUE(res);
  6987. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6988. }
  6989. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6990. // Test request without Content-Length header within 10MB limit
  6991. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6992. "Host: " +
  6993. std::string(HOST) + ":" +
  6994. std::to_string(PORT) +
  6995. "\r\n"
  6996. "Connection: close\r\n"
  6997. "\r\n";
  6998. // Add 1MB payload (within 10MB limit)
  6999. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7000. request_without_content_length += medium_payload;
  7001. std::string response;
  7002. bool result = send_request(5, request_without_content_length, &response);
  7003. if (result) {
  7004. // Should get a proper HTTP response for payloads within limit
  7005. if (response.length() > 10) {
  7006. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7007. "10MB limit";
  7008. } else {
  7009. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7010. "Content-Length)";
  7011. }
  7012. } else {
  7013. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7014. }
  7015. }
  7016. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7017. // Test request without Content-Length header exceeding 10MB limit
  7018. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7019. "Host: " +
  7020. std::string(HOST) + ":" +
  7021. std::to_string(PORT) +
  7022. "\r\n"
  7023. "Connection: close\r\n"
  7024. "\r\n";
  7025. // Add 12MB payload (exceeds 10MB limit)
  7026. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7027. request_without_content_length += large_payload;
  7028. std::string response;
  7029. bool result = send_request(10, request_without_content_length, &response);
  7030. if (!result) {
  7031. // Server should close connection due to payload limit
  7032. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7033. "(connection closed)";
  7034. } else {
  7035. // Check for error response
  7036. if (response.length() <= 10) {
  7037. SUCCEED()
  7038. << "Server closed connection for 12MB request exceeding 10MB limit";
  7039. } else {
  7040. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7041. response.find("Payload Too Large") != std::string::npos ||
  7042. response.find("400") != std::string::npos);
  7043. }
  7044. }
  7045. }
  7046. TEST(HostAndPortPropertiesTest, NoSSL) {
  7047. httplib::Client cli("www.google.com", 1234);
  7048. ASSERT_EQ("www.google.com", cli.host());
  7049. ASSERT_EQ(1234, cli.port());
  7050. }
  7051. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7052. httplib::Client cli("www.google.com:1234");
  7053. ASSERT_EQ("www.google.com", cli.host());
  7054. ASSERT_EQ(1234, cli.port());
  7055. }
  7056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7057. TEST(HostAndPortPropertiesTest, SSL) {
  7058. httplib::SSLClient cli("www.google.com");
  7059. ASSERT_EQ("www.google.com", cli.host());
  7060. ASSERT_EQ(443, cli.port());
  7061. }
  7062. #endif
  7063. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7064. TEST(SSLClientTest, UpdateCAStore) {
  7065. httplib::SSLClient httplib_client("www.google.com");
  7066. auto ca_store_1 = X509_STORE_new();
  7067. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7068. nullptr);
  7069. httplib_client.set_ca_cert_store(ca_store_1);
  7070. auto ca_store_2 = X509_STORE_new();
  7071. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7072. nullptr);
  7073. httplib_client.set_ca_cert_store(ca_store_2);
  7074. }
  7075. TEST(SSLClientTest, ServerNameIndication_Online) {
  7076. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7077. auto host = "httpbin.org";
  7078. auto path = std::string{"/get"};
  7079. #else
  7080. auto host = "nghttp2.org";
  7081. auto path = std::string{"/httpbin/get"};
  7082. #endif
  7083. SSLClient cli(host, 443);
  7084. auto res = cli.Get(path);
  7085. ASSERT_TRUE(res);
  7086. ASSERT_EQ(StatusCode::OK_200, res->status);
  7087. }
  7088. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7089. // Use a site that will cause SSL verification failure due to self-signed cert
  7090. SSLClient cli("self-signed.badssl.com", 443);
  7091. cli.enable_server_certificate_verification(true);
  7092. auto res = cli.Get("/");
  7093. ASSERT_TRUE(!res);
  7094. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7095. // For SSL server verification errors, ssl_error should be 0, only
  7096. // ssl_openssl_error should be set
  7097. EXPECT_EQ(0, res.ssl_error());
  7098. // Verify OpenSSL error is captured for SSLServerVerification
  7099. // This occurs when SSL_get_verify_result() returns a verification failure
  7100. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7101. res.ssl_openssl_error());
  7102. }
  7103. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7104. // Use a site where hostname doesn't match the certificate
  7105. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7106. SSLClient cli("wrong.host.badssl.com", 443);
  7107. cli.enable_server_certificate_verification(true);
  7108. cli.enable_server_hostname_verification(true);
  7109. auto res = cli.Get("/");
  7110. ASSERT_TRUE(!res);
  7111. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7112. // For SSL hostname verification errors, ssl_error should be 0, only
  7113. // ssl_openssl_error should be set
  7114. EXPECT_EQ(0, res.ssl_error());
  7115. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7116. // This occurs when verify_host() fails due to hostname mismatch
  7117. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7118. res.ssl_openssl_error());
  7119. }
  7120. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7121. Client cli("https://google.com");
  7122. auto res = cli.Get("/");
  7123. ASSERT_TRUE(res);
  7124. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7125. }
  7126. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7127. SSLClient cli("google.com");
  7128. cli.set_ca_cert_path(CA_CERT_FILE);
  7129. auto res = cli.Get("/");
  7130. ASSERT_TRUE(res);
  7131. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7132. }
  7133. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7134. SSLClient cli("google.com");
  7135. cli.enable_server_certificate_verification(true);
  7136. cli.set_ca_cert_path("hello");
  7137. auto res = cli.Get("/");
  7138. ASSERT_TRUE(!res);
  7139. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7140. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7141. // should be set
  7142. EXPECT_EQ(0, res.ssl_error());
  7143. // Verify OpenSSL error is captured for SSLLoadingCerts
  7144. // This error occurs when SSL_CTX_load_verify_locations() fails
  7145. // > openssl errstr 0x80000002
  7146. // error:80000002:system library::No such file or directory
  7147. // > openssl errstr 0xA000126
  7148. // error:0A000126:SSL routines::unexpected eof while reading
  7149. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7150. res.ssl_openssl_error() == 0xA000126);
  7151. }
  7152. TEST(SSLClientTest, ServerCertificateVerification4) {
  7153. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7154. ASSERT_TRUE(svr.is_valid());
  7155. svr.Get("/test", [&](const Request &, Response &res) {
  7156. res.set_content("test", "text/plain");
  7157. svr.stop();
  7158. ASSERT_TRUE(true);
  7159. });
  7160. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7161. auto se = detail::scope_exit([&] {
  7162. t.join();
  7163. ASSERT_FALSE(svr.is_running());
  7164. });
  7165. svr.wait_until_ready();
  7166. SSLClient cli("127.0.0.1", PORT);
  7167. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7168. cli.enable_server_certificate_verification(true);
  7169. cli.set_connection_timeout(30);
  7170. auto res = cli.Get("/test");
  7171. ASSERT_TRUE(res);
  7172. ASSERT_EQ(StatusCode::OK_200, res->status);
  7173. }
  7174. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7175. std::string cert;
  7176. read_file(CA_CERT_FILE, cert);
  7177. SSLClient cli("google.com");
  7178. cli.load_ca_cert_store(cert.data(), cert.size());
  7179. const auto res = cli.Get("/");
  7180. ASSERT_TRUE(res);
  7181. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7182. }
  7183. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7184. // clang-format off
  7185. static constexpr char cert[] =
  7186. "GlobalSign Root CA\n"
  7187. "==================\n"
  7188. "-----BEGIN CERTIFICATE-----\n"
  7189. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7190. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7191. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7192. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7193. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7194. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7195. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7196. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7197. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7198. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7199. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7200. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7201. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7202. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7203. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7204. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7205. "-----END CERTIFICATE-----\n";
  7206. // clang-format on
  7207. SSLClient cli("google.com");
  7208. cli.load_ca_cert_store(cert, sizeof(cert));
  7209. const auto res = cli.Get("/");
  7210. ASSERT_TRUE(res);
  7211. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7212. }
  7213. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7214. SSLClient cli("www.youtube.com");
  7215. cli.set_ca_cert_path(CA_CERT_FILE);
  7216. cli.enable_server_certificate_verification(true);
  7217. cli.set_follow_location(true);
  7218. auto res = cli.Get("/");
  7219. ASSERT_TRUE(res);
  7220. ASSERT_EQ(StatusCode::OK_200, res->status);
  7221. }
  7222. TEST(SSLClientTest, Issue2004_Online) {
  7223. Client client("https://google.com");
  7224. client.set_follow_location(true);
  7225. auto res = client.Get("/");
  7226. ASSERT_TRUE(res);
  7227. ASSERT_EQ(StatusCode::OK_200, res->status);
  7228. auto body = res->body;
  7229. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7230. }
  7231. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7232. // Create SSLClient with invalid cert/key to make is_valid() return false
  7233. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7234. "nonexistent_key.pem");
  7235. // is_valid() should be false due to cert loading failure
  7236. ASSERT_FALSE(cli.is_valid());
  7237. auto res = cli.Get("/");
  7238. ASSERT_FALSE(res);
  7239. EXPECT_EQ(Error::SSLConnection, res.error());
  7240. }
  7241. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7242. // Test for Issue #2251: SSL error not properly reported when client cert
  7243. // and key paths are swapped or mismatched
  7244. // This simulates the scenario where user accidentally swaps the cert and key
  7245. // files
  7246. // Using client cert file as private key and vice versa (completely wrong)
  7247. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7248. // Should fail validation due to cert/key mismatch
  7249. ASSERT_FALSE(cli.is_valid());
  7250. // Attempt to make a request should fail with proper error
  7251. auto res = cli.Get("/");
  7252. ASSERT_FALSE(res);
  7253. EXPECT_EQ(Error::SSLConnection, res.error());
  7254. // SSL error should be recorded in the Result object (this is the key fix for
  7255. // Issue #2251)
  7256. auto openssl_error = res.ssl_openssl_error();
  7257. EXPECT_NE(0u, openssl_error);
  7258. }
  7259. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7260. // Another variant: using valid file paths but with mismatched cert/key pair
  7261. // This tests the case where files exist but contain incompatible key material
  7262. // Using client cert with wrong key (cert2 key)
  7263. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7264. // Should fail validation
  7265. ASSERT_FALSE(cli.is_valid());
  7266. auto res = cli.Get("/");
  7267. ASSERT_FALSE(res);
  7268. // Must report error properly, not appear as success
  7269. EXPECT_EQ(Error::SSLConnection, res.error());
  7270. // OpenSSL error should be captured in Result
  7271. EXPECT_NE(0u, res.ssl_openssl_error());
  7272. }
  7273. #if 0
  7274. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7275. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7276. ASSERT_TRUE(cli != nullptr);
  7277. cli->set_address_family(AF_INET6);
  7278. cli->set_interface("en0");
  7279. auto res = cli->Get("/get");
  7280. ASSERT_TRUE(res);
  7281. ASSERT_EQ(StatusCode::OK_200, res->status);
  7282. }
  7283. #endif
  7284. void ClientCertPresent(
  7285. const std::string &client_cert_file,
  7286. const std::string &client_private_key_file,
  7287. const std::string &client_encrypted_private_key_pass = std::string()) {
  7288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7289. CLIENT_CA_CERT_DIR);
  7290. ASSERT_TRUE(svr.is_valid());
  7291. svr.Get("/test", [&](const Request &req, Response &res) {
  7292. res.set_content("test", "text/plain");
  7293. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7294. ASSERT_TRUE(peer_cert != nullptr);
  7295. auto subject_name = X509_get_subject_name(peer_cert);
  7296. ASSERT_TRUE(subject_name != nullptr);
  7297. std::string common_name;
  7298. {
  7299. char name[BUFSIZ];
  7300. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7301. name, sizeof(name));
  7302. common_name.assign(name, static_cast<size_t>(name_len));
  7303. }
  7304. EXPECT_EQ("Common Name", common_name);
  7305. X509_free(peer_cert);
  7306. });
  7307. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7308. auto se = detail::scope_exit([&] {
  7309. svr.stop();
  7310. t.join();
  7311. ASSERT_FALSE(svr.is_running());
  7312. });
  7313. svr.wait_until_ready();
  7314. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7315. client_encrypted_private_key_pass);
  7316. cli.enable_server_certificate_verification(false);
  7317. cli.set_connection_timeout(30);
  7318. auto res = cli.Get("/test");
  7319. ASSERT_TRUE(res);
  7320. ASSERT_EQ(StatusCode::OK_200, res->status);
  7321. }
  7322. TEST(SSLClientServerTest, ClientCertPresent) {
  7323. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7324. }
  7325. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7326. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7327. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7328. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7329. }
  7330. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7331. void MemoryClientCertPresent(
  7332. const std::string &client_cert_file,
  7333. const std::string &client_private_key_file,
  7334. const std::string &client_encrypted_private_key_pass = std::string()) {
  7335. auto f = fopen(SERVER_CERT_FILE, "r+");
  7336. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7337. fclose(f);
  7338. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7339. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7340. fclose(f);
  7341. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7342. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7343. auto client_ca_cert_store = X509_STORE_new();
  7344. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7345. X509_free(client_cert);
  7346. fclose(f);
  7347. f = fopen(client_cert_file.c_str(), "r+");
  7348. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7349. fclose(f);
  7350. f = fopen(client_private_key_file.c_str(), "r+");
  7351. auto client_private_key = PEM_read_PrivateKey(
  7352. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7353. fclose(f);
  7354. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7355. ASSERT_TRUE(svr.is_valid());
  7356. svr.Get("/test", [&](const Request &req, Response &res) {
  7357. res.set_content("test", "text/plain");
  7358. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7359. ASSERT_TRUE(peer_cert != nullptr);
  7360. auto subject_name = X509_get_subject_name(peer_cert);
  7361. ASSERT_TRUE(subject_name != nullptr);
  7362. std::string common_name;
  7363. {
  7364. char name[BUFSIZ];
  7365. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7366. name, sizeof(name));
  7367. common_name.assign(name, static_cast<size_t>(name_len));
  7368. }
  7369. EXPECT_EQ("Common Name", common_name);
  7370. X509_free(peer_cert);
  7371. });
  7372. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7373. auto se = detail::scope_exit([&] {
  7374. svr.stop();
  7375. t.join();
  7376. ASSERT_FALSE(svr.is_running());
  7377. });
  7378. svr.wait_until_ready();
  7379. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7380. client_encrypted_private_key_pass);
  7381. cli.enable_server_certificate_verification(false);
  7382. cli.set_connection_timeout(30);
  7383. auto res = cli.Get("/test");
  7384. ASSERT_TRUE(res);
  7385. ASSERT_EQ(StatusCode::OK_200, res->status);
  7386. X509_free(server_cert);
  7387. EVP_PKEY_free(server_private_key);
  7388. X509_free(client_cert);
  7389. EVP_PKEY_free(client_private_key);
  7390. }
  7391. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7392. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7393. }
  7394. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7395. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7396. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7397. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7398. }
  7399. #endif
  7400. TEST(SSLClientServerTest, ClientCertMissing) {
  7401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7402. CLIENT_CA_CERT_DIR);
  7403. ASSERT_TRUE(svr.is_valid());
  7404. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7406. auto se = detail::scope_exit([&] {
  7407. svr.stop();
  7408. t.join();
  7409. ASSERT_FALSE(svr.is_running());
  7410. });
  7411. svr.wait_until_ready();
  7412. SSLClient cli(HOST, PORT);
  7413. cli.set_connection_timeout(30);
  7414. auto res = cli.Get("/test");
  7415. ASSERT_TRUE(!res);
  7416. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7417. // For SSL server verification errors, ssl_error should be 0, only
  7418. // ssl_openssl_error should be set
  7419. EXPECT_EQ(0, res.ssl_error());
  7420. // Verify OpenSSL error is captured for SSLServerVerification
  7421. // Note: This test may have different error codes depending on the exact
  7422. // verification failure
  7423. EXPECT_NE(0UL, res.ssl_openssl_error());
  7424. }
  7425. TEST(SSLClientServerTest, TrustDirOptional) {
  7426. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7427. ASSERT_TRUE(svr.is_valid());
  7428. svr.Get("/test", [&](const Request &, Response &res) {
  7429. res.set_content("test", "text/plain");
  7430. });
  7431. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7432. auto se = detail::scope_exit([&] {
  7433. svr.stop();
  7434. t.join();
  7435. ASSERT_FALSE(svr.is_running());
  7436. });
  7437. svr.wait_until_ready();
  7438. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7439. cli.enable_server_certificate_verification(false);
  7440. cli.set_connection_timeout(30);
  7441. auto res = cli.Get("/test");
  7442. ASSERT_TRUE(res);
  7443. ASSERT_EQ(StatusCode::OK_200, res->status);
  7444. }
  7445. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7446. class NoListenSSLServer : public SSLServer {
  7447. public:
  7448. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7449. const char *client_ca_cert_file_path,
  7450. const char *client_ca_cert_dir_path = nullptr)
  7451. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7452. client_ca_cert_dir_path),
  7453. stop_(false) {}
  7454. std::atomic_bool stop_;
  7455. private:
  7456. bool process_and_close_socket(socket_t /*sock*/) override {
  7457. // Don't create SSL context
  7458. while (!stop_.load()) {
  7459. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7460. }
  7461. return true;
  7462. }
  7463. };
  7464. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7465. CLIENT_CA_CERT_FILE);
  7466. ASSERT_TRUE(svr.is_valid());
  7467. svr.Get("/test", [&](const Request &, Response &res) {
  7468. res.set_content("test", "text/plain");
  7469. });
  7470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7471. auto se = detail::scope_exit([&] {
  7472. svr.stop_ = true;
  7473. svr.stop();
  7474. t.join();
  7475. ASSERT_FALSE(svr.is_running());
  7476. });
  7477. svr.wait_until_ready();
  7478. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7479. cli.enable_server_certificate_verification(false);
  7480. cli.set_connection_timeout(1);
  7481. auto res = cli.Get("/test");
  7482. ASSERT_TRUE(!res);
  7483. EXPECT_EQ(Error::SSLConnection, res.error());
  7484. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7485. }
  7486. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7487. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7488. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7489. SSL_CTX_set_options(&ssl_ctx,
  7490. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7491. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7492. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7493. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7494. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7495. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7496. "ECDHE-DSS-AES128-SHA256:"
  7497. "ECDHE-RSA-AES256-SHA256:"
  7498. "ECDHE-DSS-AES256-SHA256:";
  7499. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7500. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7501. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7502. SSL_FILETYPE_PEM) != 1) {
  7503. return false;
  7504. }
  7505. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7506. CLIENT_CA_CERT_DIR);
  7507. SSL_CTX_set_verify(
  7508. &ssl_ctx,
  7509. SSL_VERIFY_PEER |
  7510. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7511. nullptr);
  7512. return true;
  7513. };
  7514. SSLServer svr(setup_ssl_ctx_callback);
  7515. ASSERT_TRUE(svr.is_valid());
  7516. svr.Get("/test", [&](const Request &req, Response &res) {
  7517. res.set_content("test", "text/plain");
  7518. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7519. ASSERT_TRUE(peer_cert != nullptr);
  7520. auto subject_name = X509_get_subject_name(peer_cert);
  7521. ASSERT_TRUE(subject_name != nullptr);
  7522. std::string common_name;
  7523. {
  7524. char name[BUFSIZ];
  7525. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7526. name, sizeof(name));
  7527. common_name.assign(name, static_cast<size_t>(name_len));
  7528. }
  7529. EXPECT_EQ("Common Name", common_name);
  7530. X509_free(peer_cert);
  7531. });
  7532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7533. auto se = detail::scope_exit([&] {
  7534. svr.stop();
  7535. t.join();
  7536. ASSERT_FALSE(svr.is_running());
  7537. });
  7538. svr.wait_until_ready();
  7539. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7540. cli.enable_server_certificate_verification(false);
  7541. cli.set_connection_timeout(30);
  7542. auto res = cli.Get("/test");
  7543. ASSERT_TRUE(res);
  7544. ASSERT_EQ(StatusCode::OK_200, res->status);
  7545. }
  7546. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7548. ASSERT_TRUE(svr.is_valid());
  7549. // Set up a handler to verify client certificate is present
  7550. bool client_cert_verified = false;
  7551. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7552. // Verify that client certificate was provided
  7553. client_cert_verified = true;
  7554. res.set_content("success", "text/plain");
  7555. });
  7556. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7557. auto se = detail::scope_exit([&] {
  7558. svr.stop();
  7559. t.join();
  7560. ASSERT_FALSE(svr.is_running());
  7561. });
  7562. svr.wait_until_ready();
  7563. // Client with certificate
  7564. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7565. cli.enable_server_certificate_verification(false);
  7566. cli.set_connection_timeout(30);
  7567. auto res = cli.Get("/test");
  7568. ASSERT_TRUE(res);
  7569. ASSERT_EQ(StatusCode::OK_200, res->status);
  7570. ASSERT_TRUE(client_cert_verified);
  7571. EXPECT_EQ("success", res->body);
  7572. }
  7573. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7574. // Test that when client CA cert file is provided,
  7575. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7576. // Create a server with client authentication
  7577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7578. ASSERT_TRUE(svr.is_valid());
  7579. // We can't directly access the SSL_CTX from SSLServer to verify,
  7580. // but we can test that the server properly requests client certificates
  7581. // and accepts valid ones from the specified CA
  7582. bool handler_called = false;
  7583. svr.Get("/test", [&](const Request &req, Response &res) {
  7584. handler_called = true;
  7585. // Verify that a client certificate was provided
  7586. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7587. ASSERT_TRUE(peer_cert != nullptr);
  7588. // Get the issuer name
  7589. auto issuer_name = X509_get_issuer_name(peer_cert);
  7590. ASSERT_TRUE(issuer_name != nullptr);
  7591. char issuer_buf[256];
  7592. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7593. // The client certificate should be issued by our test CA
  7594. std::string issuer_str(issuer_buf);
  7595. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7596. X509_free(peer_cert);
  7597. res.set_content("authenticated", "text/plain");
  7598. });
  7599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7600. auto se = detail::scope_exit([&] {
  7601. svr.stop();
  7602. t.join();
  7603. ASSERT_FALSE(svr.is_running());
  7604. });
  7605. svr.wait_until_ready();
  7606. // Connect with a client certificate issued by the CA
  7607. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7608. cli.enable_server_certificate_verification(false);
  7609. cli.set_connection_timeout(30);
  7610. auto res = cli.Get("/test");
  7611. ASSERT_TRUE(res);
  7612. ASSERT_EQ(StatusCode::OK_200, res->status);
  7613. ASSERT_TRUE(handler_called);
  7614. EXPECT_EQ("authenticated", res->body);
  7615. }
  7616. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7617. // Test 1: Valid CA file - no error should be recorded
  7618. {
  7619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7620. CLIENT_CA_CERT_FILE);
  7621. ASSERT_TRUE(svr.is_valid());
  7622. // With valid setup, last_ssl_error should be 0
  7623. EXPECT_EQ(0, svr.ssl_last_error());
  7624. }
  7625. // Test 2: Invalid CA file content
  7626. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7627. {
  7628. // Create a temporary file with completely invalid content
  7629. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7630. {
  7631. std::ofstream ofs(temp_invalid_ca);
  7632. ofs << "This is not a certificate file at all\n";
  7633. ofs << "Just plain text content\n";
  7634. }
  7635. // Create server with invalid CA file
  7636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7637. // Clean up temporary file
  7638. std::remove(temp_invalid_ca);
  7639. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7640. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7641. // Note: SSL_CTX_load_verify_locations typically fails first,
  7642. // but our error handling code path is still exercised
  7643. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7644. }
  7645. }
  7646. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7647. // Test SSL server using X509_STORE constructor with client CA certificates
  7648. // This test verifies that Phase 2 implementation correctly extracts CA names
  7649. // from an X509_STORE and sets them in the SSL context
  7650. // Load the CA certificate into memory
  7651. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7652. ASSERT_NE(nullptr, bio);
  7653. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7654. BIO_free(bio);
  7655. ASSERT_NE(nullptr, ca_cert);
  7656. // Create an X509_STORE and add the CA certificate
  7657. auto store = X509_STORE_new();
  7658. ASSERT_NE(nullptr, store);
  7659. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7660. // Load server certificate and private key
  7661. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7662. ASSERT_NE(nullptr, cert_bio);
  7663. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7664. BIO_free(cert_bio);
  7665. ASSERT_NE(nullptr, server_cert);
  7666. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7667. ASSERT_NE(nullptr, key_bio);
  7668. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7669. BIO_free(key_bio);
  7670. ASSERT_NE(nullptr, server_key);
  7671. // Create SSLServer with X509_STORE constructor
  7672. // Note: X509_STORE ownership is transferred to SSL_CTX
  7673. SSLServer svr(server_cert, server_key, store);
  7674. ASSERT_TRUE(svr.is_valid());
  7675. // No SSL error should be recorded for valid setup
  7676. EXPECT_EQ(0, svr.ssl_last_error());
  7677. // Set up server endpoints
  7678. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7679. res.set_content("ok", "text/plain");
  7680. });
  7681. // Start server in a thread
  7682. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7683. svr.wait_until_ready();
  7684. // Connect with client certificate (using constructor with paths)
  7685. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7686. cli.enable_server_certificate_verification(false);
  7687. auto res = cli.Get("/test-x509store");
  7688. ASSERT_TRUE(res);
  7689. EXPECT_EQ(200, res->status);
  7690. EXPECT_EQ("ok", res->body);
  7691. // Clean up
  7692. X509_free(server_cert);
  7693. EVP_PKEY_free(server_key);
  7694. X509_free(ca_cert);
  7695. svr.stop();
  7696. server_thread.join();
  7697. }
  7698. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7699. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7700. // prepare large data
  7701. std::random_device seed_gen;
  7702. std::mt19937 random(seed_gen());
  7703. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7704. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7705. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7706. // server
  7707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7708. ASSERT_TRUE(svr.is_valid());
  7709. svr.Post("/binary", [&](const Request &req, Response &res) {
  7710. EXPECT_EQ(large_size_byte, req.body.size());
  7711. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7712. res.set_content(req.body, "application/octet-stream");
  7713. });
  7714. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7715. auto se = detail::scope_exit([&] {
  7716. svr.stop();
  7717. listen_thread.join();
  7718. ASSERT_FALSE(svr.is_running());
  7719. });
  7720. svr.wait_until_ready();
  7721. // client POST
  7722. SSLClient cli("localhost", PORT);
  7723. cli.enable_server_certificate_verification(false);
  7724. cli.set_read_timeout(std::chrono::seconds(100));
  7725. cli.set_write_timeout(std::chrono::seconds(100));
  7726. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7727. large_size_byte, "application/octet-stream");
  7728. // compare
  7729. EXPECT_EQ(StatusCode::OK_200, res->status);
  7730. EXPECT_EQ(large_size_byte, res->body.size());
  7731. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7732. }
  7733. #endif
  7734. #ifdef _WIN32
  7735. TEST(CleanupTest, WSACleanup) {
  7736. int ret = WSACleanup();
  7737. ASSERT_EQ(0, ret);
  7738. }
  7739. #endif
  7740. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7741. TEST(NoSSLSupport, SimpleInterface) {
  7742. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7743. }
  7744. #endif
  7745. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7746. TEST(InvalidScheme, SimpleInterface) {
  7747. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7748. }
  7749. #endif
  7750. TEST(NoScheme, SimpleInterface) {
  7751. Client cli("yahoo.com:80");
  7752. ASSERT_TRUE(cli.is_valid());
  7753. }
  7754. TEST(SendAPI, SimpleInterface_Online) {
  7755. Client cli("http://yahoo.com");
  7756. Request req;
  7757. req.method = "GET";
  7758. req.path = "/";
  7759. auto res = cli.send(req);
  7760. ASSERT_TRUE(res);
  7761. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7762. }
  7763. TEST(SendAPI, WithParamsInRequest) {
  7764. Server svr;
  7765. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7766. EXPECT_TRUE(req.has_param("test"));
  7767. EXPECT_EQ("test_value", req.get_param_value("test"));
  7768. });
  7769. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7770. auto se = detail::scope_exit([&] {
  7771. svr.stop();
  7772. t.join();
  7773. ASSERT_FALSE(svr.is_running());
  7774. });
  7775. svr.wait_until_ready();
  7776. Client cli(HOST, PORT);
  7777. {
  7778. Request req;
  7779. req.method = "GET";
  7780. req.path = "/";
  7781. req.params.emplace("test", "test_value");
  7782. auto res = cli.send(req);
  7783. ASSERT_TRUE(res);
  7784. }
  7785. {
  7786. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7787. ASSERT_TRUE(res);
  7788. }
  7789. }
  7790. TEST(ClientImplMethods, GetSocketTest) {
  7791. httplib::Server svr;
  7792. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7793. res.status = StatusCode::OK_200;
  7794. });
  7795. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7796. auto se = detail::scope_exit([&] {
  7797. svr.stop();
  7798. thread.join();
  7799. ASSERT_FALSE(svr.is_running());
  7800. });
  7801. svr.wait_until_ready();
  7802. {
  7803. httplib::Client cli("http://127.0.0.1:3333");
  7804. cli.set_keep_alive(true);
  7805. // Use the behavior of cpp-httplib of opening the connection
  7806. // only when the first request happens. If that changes,
  7807. // this test would be obsolete.
  7808. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7809. // This also implicitly tests the server. But other tests would fail much
  7810. // earlier than this one to be considered.
  7811. auto res = cli.Get("/");
  7812. ASSERT_TRUE(res);
  7813. EXPECT_EQ(StatusCode::OK_200, res->status);
  7814. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7815. }
  7816. }
  7817. // Disabled due to out-of-memory problem on GitHub Actions
  7818. #ifdef _WIN64
  7819. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7820. // allocate content size larger than 2GB in memory
  7821. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7822. char *content = (char *)malloc(content_size);
  7823. ASSERT_TRUE(content);
  7824. Server svr;
  7825. svr.Get("/foo",
  7826. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7827. res.set_content(content, content_size, "application/octet-stream");
  7828. });
  7829. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7830. auto se = detail::scope_exit([&] {
  7831. svr.stop();
  7832. listen_thread.join();
  7833. if (content) free(content);
  7834. ASSERT_FALSE(svr.is_running());
  7835. });
  7836. svr.wait_until_ready();
  7837. Client cli(HOST, PORT);
  7838. auto res = cli.Get("/foo");
  7839. ASSERT_TRUE(res);
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ(content_size, res->body.length());
  7842. }
  7843. #endif
  7844. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7845. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7846. Client cli("http://yahoo.com");
  7847. auto res = cli.Get("/");
  7848. ASSERT_TRUE(res);
  7849. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7850. cli.set_follow_location(true);
  7851. res = cli.Get("/");
  7852. ASSERT_TRUE(res);
  7853. EXPECT_EQ(StatusCode::OK_200, res->status);
  7854. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7855. }
  7856. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7857. Client cli("https://yahoo.com");
  7858. auto res = cli.Get("/");
  7859. ASSERT_TRUE(res);
  7860. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7861. cli.set_follow_location(true);
  7862. res = cli.Get("/");
  7863. ASSERT_TRUE(res);
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7866. }
  7867. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7868. Client cli("https://yahoo.com");
  7869. auto res = cli.Get("/");
  7870. ASSERT_TRUE(res);
  7871. ASSERT_FALSE(!res);
  7872. ASSERT_TRUE(res);
  7873. ASSERT_FALSE(res == nullptr);
  7874. ASSERT_TRUE(res != nullptr);
  7875. EXPECT_EQ(Error::Success, res.error());
  7876. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7877. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7878. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7879. cli.set_follow_location(true);
  7880. res = cli.Get("/");
  7881. ASSERT_TRUE(res);
  7882. EXPECT_EQ(Error::Success, res.error());
  7883. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7884. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7887. }
  7888. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7889. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7890. Client cli("https://cdnjs.cloudflare.com");
  7891. auto res =
  7892. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7893. ASSERT_TRUE(res);
  7894. EXPECT_EQ(StatusCode::OK_200, res->status);
  7895. EXPECT_EQ(287630U, res->body.size());
  7896. EXPECT_EQ("application/javascript; charset=utf-8",
  7897. res->get_header_value("Content-Type"));
  7898. }
  7899. #endif
  7900. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7901. #undef REDIR_HOST // Silence compiler warning
  7902. #define REDIR_HOST "https://httpbingo.org"
  7903. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7904. Client cli(REDIR_HOST);
  7905. cli.set_follow_location(true);
  7906. auto res =
  7907. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7908. ASSERT_TRUE(res);
  7909. EXPECT_EQ(StatusCode::OK_200, res->status);
  7910. }
  7911. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7912. Client cli(REDIR_HOST);
  7913. cli.set_follow_location(true);
  7914. Params params;
  7915. params.emplace("url", "http://example.com");
  7916. params.emplace("status_code", "302");
  7917. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7918. ASSERT_TRUE(res);
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. }
  7921. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7922. Client cli(REDIR_HOST);
  7923. cli.set_follow_location(true);
  7924. Params params;
  7925. params.emplace("url", "http://example.com");
  7926. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7927. ASSERT_TRUE(res);
  7928. EXPECT_EQ(StatusCode::OK_200, res->status);
  7929. }
  7930. TEST(HttpToHttpsRedirectTest, CertFile) {
  7931. Server svr;
  7932. ASSERT_TRUE(svr.is_valid());
  7933. svr.Get("/index", [&](const Request &, Response &res) {
  7934. res.set_redirect("https://127.0.0.1:1235/index");
  7935. svr.stop();
  7936. });
  7937. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7938. ASSERT_TRUE(ssl_svr.is_valid());
  7939. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7940. res.set_content("test", "text/plain");
  7941. ssl_svr.stop();
  7942. });
  7943. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7944. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7945. auto se = detail::scope_exit([&] {
  7946. t2.join();
  7947. t.join();
  7948. ASSERT_FALSE(svr.is_running());
  7949. });
  7950. svr.wait_until_ready();
  7951. ssl_svr.wait_until_ready();
  7952. Client cli("127.0.0.1", PORT);
  7953. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7954. cli.enable_server_certificate_verification(true);
  7955. cli.set_follow_location(true);
  7956. cli.set_connection_timeout(30);
  7957. auto res = cli.Get("/index");
  7958. ASSERT_TRUE(res);
  7959. ASSERT_EQ(StatusCode::OK_200, res->status);
  7960. }
  7961. TEST(SSLClientRedirectTest, CertFile) {
  7962. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7963. ASSERT_TRUE(ssl_svr1.is_valid());
  7964. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7965. res.set_redirect("https://127.0.0.1:1235/index");
  7966. ssl_svr1.stop();
  7967. });
  7968. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7969. ASSERT_TRUE(ssl_svr2.is_valid());
  7970. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7971. res.set_content("test", "text/plain");
  7972. ssl_svr2.stop();
  7973. });
  7974. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7975. thread t2 =
  7976. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7977. auto se = detail::scope_exit([&] {
  7978. t2.join();
  7979. t.join();
  7980. ASSERT_FALSE(ssl_svr1.is_running());
  7981. });
  7982. ssl_svr1.wait_until_ready();
  7983. ssl_svr2.wait_until_ready();
  7984. SSLClient cli("127.0.0.1", PORT);
  7985. std::string cert;
  7986. read_file(SERVER_CERT2_FILE, cert);
  7987. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7988. cli.enable_server_certificate_verification(true);
  7989. cli.set_follow_location(true);
  7990. cli.set_connection_timeout(30);
  7991. auto res = cli.Get("/index");
  7992. ASSERT_TRUE(res);
  7993. ASSERT_EQ(StatusCode::OK_200, res->status);
  7994. }
  7995. TEST(MultipartFormDataTest, LargeData) {
  7996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7997. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7998. const ContentReader &content_reader) {
  7999. if (req.is_multipart_form_data()) {
  8000. std::vector<FormData> items;
  8001. content_reader(
  8002. [&](const FormData &file) {
  8003. items.push_back(file);
  8004. return true;
  8005. },
  8006. [&](const char *data, size_t data_length) {
  8007. items.back().content.append(data, data_length);
  8008. return true;
  8009. });
  8010. EXPECT_TRUE(std::string(items[0].name) == "document");
  8011. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8012. EXPECT_TRUE(items[0].filename == "2MB_data");
  8013. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8014. EXPECT_TRUE(items[1].name == "hello");
  8015. EXPECT_TRUE(items[1].content == "world");
  8016. EXPECT_TRUE(items[1].filename == "");
  8017. EXPECT_TRUE(items[1].content_type == "");
  8018. } else {
  8019. std::string body;
  8020. content_reader([&](const char *data, size_t data_length) {
  8021. body.append(data, data_length);
  8022. return true;
  8023. });
  8024. }
  8025. });
  8026. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8027. auto se = detail::scope_exit([&] {
  8028. svr.stop();
  8029. t.join();
  8030. ASSERT_FALSE(svr.is_running());
  8031. });
  8032. svr.wait_until_ready();
  8033. {
  8034. std::string data(1024 * 1024 * 2, '.');
  8035. std::stringstream buffer;
  8036. buffer << data;
  8037. Client cli("https://localhost:8080");
  8038. cli.enable_server_certificate_verification(false);
  8039. UploadFormDataItems items{
  8040. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8041. {"hello", "world", "", ""},
  8042. };
  8043. auto res = cli.Post("/post", items);
  8044. ASSERT_TRUE(res);
  8045. ASSERT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. }
  8048. TEST(MultipartFormDataTest, DataProviderItems) {
  8049. std::random_device seed_gen;
  8050. std::mt19937 random(seed_gen());
  8051. std::string rand1;
  8052. rand1.resize(1000);
  8053. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8054. std::string rand2;
  8055. rand2.resize(3000);
  8056. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8058. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8059. const ContentReader &content_reader) {
  8060. ASSERT_FALSE(req.is_multipart_form_data());
  8061. std::string body;
  8062. content_reader([&](const char *data, size_t data_length) {
  8063. body.append(data, data_length);
  8064. return true;
  8065. });
  8066. EXPECT_EQ(body, "");
  8067. });
  8068. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8069. const ContentReader &content_reader) {
  8070. ASSERT_TRUE(req.is_multipart_form_data());
  8071. std::vector<FormData> items;
  8072. content_reader(
  8073. [&](const FormData &file) {
  8074. items.push_back(file);
  8075. return true;
  8076. },
  8077. [&](const char *data, size_t data_length) {
  8078. items.back().content.append(data, data_length);
  8079. return true;
  8080. });
  8081. ASSERT_TRUE(items.size() == 2);
  8082. EXPECT_EQ(std::string(items[0].name), "name1");
  8083. EXPECT_EQ(items[0].content, "Testing123");
  8084. EXPECT_EQ(items[0].filename, "filename1");
  8085. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8086. EXPECT_EQ(items[1].name, "name2");
  8087. EXPECT_EQ(items[1].content, "Testing456");
  8088. EXPECT_EQ(items[1].filename, "");
  8089. EXPECT_EQ(items[1].content_type, "");
  8090. });
  8091. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8092. const ContentReader &content_reader) {
  8093. ASSERT_TRUE(req.is_multipart_form_data());
  8094. std::vector<FormData> items;
  8095. content_reader(
  8096. [&](const FormData &file) {
  8097. items.push_back(file);
  8098. return true;
  8099. },
  8100. [&](const char *data, size_t data_length) {
  8101. items.back().content.append(data, data_length);
  8102. return true;
  8103. });
  8104. ASSERT_TRUE(items.size() == 2);
  8105. EXPECT_EQ(items[0].name, "name3");
  8106. EXPECT_EQ(items[0].content, rand1);
  8107. EXPECT_EQ(items[0].filename, "filename3");
  8108. EXPECT_EQ(items[0].content_type, "");
  8109. EXPECT_EQ(items[1].name, "name4");
  8110. EXPECT_EQ(items[1].content, rand2);
  8111. EXPECT_EQ(items[1].filename, "filename4");
  8112. EXPECT_EQ(items[1].content_type, "");
  8113. });
  8114. svr.Post("/post-both", [&](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() == 4);
  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. EXPECT_EQ(items[2].name, "name3");
  8137. EXPECT_EQ(items[2].content, rand1);
  8138. EXPECT_EQ(items[2].filename, "filename3");
  8139. EXPECT_EQ(items[2].content_type, "");
  8140. EXPECT_EQ(items[3].name, "name4");
  8141. EXPECT_EQ(items[3].content, rand2);
  8142. EXPECT_EQ(items[3].filename, "filename4");
  8143. EXPECT_EQ(items[3].content_type, "");
  8144. });
  8145. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8146. auto se = detail::scope_exit([&] {
  8147. svr.stop();
  8148. t.join();
  8149. ASSERT_FALSE(svr.is_running());
  8150. });
  8151. svr.wait_until_ready();
  8152. {
  8153. Client cli("https://localhost:8080");
  8154. cli.enable_server_certificate_verification(false);
  8155. UploadFormDataItems items{
  8156. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8157. {"name2", "Testing456", "", ""}, // not a file
  8158. };
  8159. {
  8160. auto res = cli.Post("/post-none", {}, {}, {});
  8161. ASSERT_TRUE(res);
  8162. ASSERT_EQ(StatusCode::OK_200, res->status);
  8163. }
  8164. FormDataProviderItems providers;
  8165. {
  8166. auto res =
  8167. cli.Post("/post-items", {}, items, providers); // empty providers
  8168. ASSERT_TRUE(res);
  8169. ASSERT_EQ(StatusCode::OK_200, res->status);
  8170. }
  8171. providers.push_back({"name3",
  8172. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8173. // test the offset is given correctly at each step
  8174. if (!offset)
  8175. sink.os.write(rand1.data(), 30);
  8176. else if (offset == 30)
  8177. sink.os.write(rand1.data() + 30, 300);
  8178. else if (offset == 330)
  8179. sink.os.write(rand1.data() + 330, 670);
  8180. else if (offset == rand1.size())
  8181. sink.done();
  8182. return true;
  8183. },
  8184. "filename3",
  8185. {}});
  8186. providers.push_back({"name4",
  8187. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8188. // test the offset is given correctly at each step
  8189. if (!offset)
  8190. sink.os.write(rand2.data(), 2000);
  8191. else if (offset == 2000)
  8192. sink.os.write(rand2.data() + 2000, 1);
  8193. else if (offset == 2001)
  8194. sink.os.write(rand2.data() + 2001, 999);
  8195. else if (offset == rand2.size())
  8196. sink.done();
  8197. return true;
  8198. },
  8199. "filename4",
  8200. {}});
  8201. {
  8202. auto res = cli.Post("/post-providers", {}, {}, providers);
  8203. ASSERT_TRUE(res);
  8204. ASSERT_EQ(StatusCode::OK_200, res->status);
  8205. }
  8206. {
  8207. auto res = cli.Post("/post-both", {}, items, providers);
  8208. ASSERT_TRUE(res);
  8209. ASSERT_EQ(StatusCode::OK_200, res->status);
  8210. }
  8211. }
  8212. }
  8213. TEST(MultipartFormDataTest, BadHeader) {
  8214. Server svr;
  8215. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8216. res.set_content("ok", "text/plain");
  8217. });
  8218. thread t = thread([&] { svr.listen(HOST, PORT); });
  8219. auto se = detail::scope_exit([&] {
  8220. svr.stop();
  8221. t.join();
  8222. ASSERT_FALSE(svr.is_running());
  8223. });
  8224. svr.wait_until_ready();
  8225. const std::string body =
  8226. "This is the preamble. It is to be ignored, though it\r\n"
  8227. "is a handy place for composition agents to include an\r\n"
  8228. "explanatory note to non-MIME conformant readers.\r\n"
  8229. "\r\n"
  8230. "\r\n"
  8231. "--simple boundary\r\n"
  8232. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8233. ": BAD...\r\n"
  8234. "\r\n"
  8235. "value1\r\n"
  8236. "--simple boundary\r\n"
  8237. "Content-Disposition: form-data; name=\"field2\"; "
  8238. "filename=\"example.txt\"\r\n"
  8239. "\r\n"
  8240. "value2\r\n"
  8241. "--simple boundary--\r\n"
  8242. "This is the epilogue. It is also to be ignored.\r\n";
  8243. std::string content_type =
  8244. R"(multipart/form-data; boundary="simple boundary")";
  8245. Client cli(HOST, PORT);
  8246. auto res = cli.Post("/post", body, content_type.c_str());
  8247. ASSERT_TRUE(res);
  8248. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8249. }
  8250. TEST(MultipartFormDataTest, WithPreamble) {
  8251. Server svr;
  8252. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8253. res.set_content("ok", "text/plain");
  8254. });
  8255. thread t = thread([&] { svr.listen(HOST, PORT); });
  8256. auto se = detail::scope_exit([&] {
  8257. svr.stop();
  8258. t.join();
  8259. ASSERT_FALSE(svr.is_running());
  8260. });
  8261. svr.wait_until_ready();
  8262. const std::string body =
  8263. "This is the preamble. It is to be ignored, though it\r\n"
  8264. "is a handy place for composition agents to include an\r\n"
  8265. "explanatory note to non-MIME conformant readers.\r\n"
  8266. "\r\n"
  8267. "\r\n"
  8268. "--simple boundary\r\n"
  8269. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8270. "\r\n"
  8271. "value1\r\n"
  8272. "--simple boundary\r\n"
  8273. "Content-Disposition: form-data; name=\"field2\"; "
  8274. "filename=\"example.txt\"\r\n"
  8275. "\r\n"
  8276. "value2\r\n"
  8277. "--simple boundary--\r\n"
  8278. "This is the epilogue. It is also to be ignored.\r\n";
  8279. std::string content_type =
  8280. R"(multipart/form-data; boundary="simple boundary")";
  8281. Client cli(HOST, PORT);
  8282. auto res = cli.Post("/post", body, content_type.c_str());
  8283. ASSERT_TRUE(res);
  8284. EXPECT_EQ(StatusCode::OK_200, res->status);
  8285. }
  8286. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8288. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8289. const ContentReader &content_reader) {
  8290. if (req.is_multipart_form_data()) {
  8291. std::vector<FormData> items;
  8292. content_reader(
  8293. [&](const FormData &file) {
  8294. items.push_back(file);
  8295. return true;
  8296. },
  8297. [&](const char *data, size_t data_length) {
  8298. items.back().content.append(data, data_length);
  8299. return true;
  8300. });
  8301. EXPECT_TRUE(std::string(items[0].name) == "document");
  8302. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8303. EXPECT_TRUE(items[0].filename == "2MB_data");
  8304. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8305. EXPECT_TRUE(items[1].name == "hello");
  8306. EXPECT_TRUE(items[1].content == "world");
  8307. EXPECT_TRUE(items[1].filename == "");
  8308. EXPECT_TRUE(items[1].content_type == "");
  8309. } else {
  8310. std::string body;
  8311. content_reader([&](const char *data, size_t data_length) {
  8312. body.append(data, data_length);
  8313. return true;
  8314. });
  8315. }
  8316. });
  8317. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8318. auto se = detail::scope_exit([&] {
  8319. svr.stop();
  8320. t.join();
  8321. ASSERT_FALSE(svr.is_running());
  8322. });
  8323. svr.wait_until_ready();
  8324. {
  8325. std::string data(1024 * 1024 * 2, '.');
  8326. std::stringstream buffer;
  8327. buffer << data;
  8328. Client cli("https://localhost:8080");
  8329. cli.enable_server_certificate_verification(false);
  8330. UploadFormDataItems items{
  8331. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8332. {"hello", "world", "", ""},
  8333. };
  8334. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8335. ASSERT_TRUE(res);
  8336. ASSERT_EQ(StatusCode::OK_200, res->status);
  8337. }
  8338. }
  8339. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8340. std::string data(1024 * 1024 * 2, '&');
  8341. std::stringstream buffer;
  8342. buffer << data;
  8343. Client cli("https://localhost:8080");
  8344. UploadFormDataItems items{
  8345. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8346. {"hello", "world", "", ""},
  8347. };
  8348. for (const char &c : " \t\r\n") {
  8349. auto res =
  8350. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8351. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8352. ASSERT_FALSE(res);
  8353. }
  8354. }
  8355. TEST(MultipartFormDataTest, PutFormData) {
  8356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8357. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8358. const ContentReader &content_reader) {
  8359. if (req.is_multipart_form_data()) {
  8360. std::vector<FormData> items;
  8361. content_reader(
  8362. [&](const FormData &file) {
  8363. items.push_back(file);
  8364. return true;
  8365. },
  8366. [&](const char *data, size_t data_length) {
  8367. items.back().content.append(data, data_length);
  8368. return true;
  8369. });
  8370. EXPECT_TRUE(std::string(items[0].name) == "document");
  8371. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8372. EXPECT_TRUE(items[0].filename == "2MB_data");
  8373. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8374. EXPECT_TRUE(items[1].name == "hello");
  8375. EXPECT_TRUE(items[1].content == "world");
  8376. EXPECT_TRUE(items[1].filename == "");
  8377. EXPECT_TRUE(items[1].content_type == "");
  8378. } else {
  8379. std::string body;
  8380. content_reader([&](const char *data, size_t data_length) {
  8381. body.append(data, data_length);
  8382. return true;
  8383. });
  8384. }
  8385. });
  8386. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8387. auto se = detail::scope_exit([&] {
  8388. svr.stop();
  8389. t.join();
  8390. ASSERT_FALSE(svr.is_running());
  8391. });
  8392. svr.wait_until_ready();
  8393. {
  8394. std::string data(1024 * 1024 * 2, '&');
  8395. std::stringstream buffer;
  8396. buffer << data;
  8397. Client cli("https://localhost:8080");
  8398. cli.enable_server_certificate_verification(false);
  8399. UploadFormDataItems items{
  8400. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8401. {"hello", "world", "", ""},
  8402. };
  8403. auto res = cli.Put("/put", items);
  8404. ASSERT_TRUE(res);
  8405. ASSERT_EQ(StatusCode::OK_200, res->status);
  8406. }
  8407. }
  8408. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8410. svr.Put("/put_customboundary",
  8411. [&](const Request &req, const Response & /*res*/,
  8412. const ContentReader &content_reader) {
  8413. if (req.is_multipart_form_data()) {
  8414. std::vector<FormData> items;
  8415. content_reader(
  8416. [&](const FormData &file) {
  8417. items.push_back(file);
  8418. return true;
  8419. },
  8420. [&](const char *data, size_t data_length) {
  8421. items.back().content.append(data, data_length);
  8422. return true;
  8423. });
  8424. EXPECT_TRUE(std::string(items[0].name) == "document");
  8425. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8426. EXPECT_TRUE(items[0].filename == "2MB_data");
  8427. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8428. EXPECT_TRUE(items[1].name == "hello");
  8429. EXPECT_TRUE(items[1].content == "world");
  8430. EXPECT_TRUE(items[1].filename == "");
  8431. EXPECT_TRUE(items[1].content_type == "");
  8432. } else {
  8433. std::string body;
  8434. content_reader([&](const char *data, size_t data_length) {
  8435. body.append(data, data_length);
  8436. return true;
  8437. });
  8438. }
  8439. });
  8440. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8441. auto se = detail::scope_exit([&] {
  8442. svr.stop();
  8443. t.join();
  8444. ASSERT_FALSE(svr.is_running());
  8445. });
  8446. svr.wait_until_ready();
  8447. {
  8448. std::string data(1024 * 1024 * 2, '&');
  8449. std::stringstream buffer;
  8450. buffer << data;
  8451. Client cli("https://localhost:8080");
  8452. cli.enable_server_certificate_verification(false);
  8453. UploadFormDataItems items{
  8454. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8455. {"hello", "world", "", ""},
  8456. };
  8457. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8458. ASSERT_TRUE(res);
  8459. ASSERT_EQ(StatusCode::OK_200, res->status);
  8460. }
  8461. }
  8462. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8463. std::string data(1024 * 1024 * 2, '&');
  8464. std::stringstream buffer;
  8465. buffer << data;
  8466. Client cli("https://localhost:8080");
  8467. cli.enable_server_certificate_verification(false);
  8468. UploadFormDataItems items{
  8469. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8470. {"hello", "world", "", ""},
  8471. };
  8472. for (const char &c : " \t\r\n") {
  8473. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8474. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8475. ASSERT_FALSE(res);
  8476. }
  8477. }
  8478. TEST(MultipartFormDataTest, AlternateFilename) {
  8479. auto handled = false;
  8480. Server svr;
  8481. svr.Post("/test", [&](const Request &req, Response &res) {
  8482. ASSERT_EQ(2u, req.form.files.size());
  8483. ASSERT_EQ(1u, req.form.fields.size());
  8484. // Test files
  8485. const auto &file1 = req.form.get_file("file1");
  8486. ASSERT_EQ("file1", file1.name);
  8487. ASSERT_EQ("A.txt", file1.filename);
  8488. ASSERT_EQ("text/plain", file1.content_type);
  8489. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8490. const auto &file2 = req.form.get_file("file2");
  8491. ASSERT_EQ("file2", file2.name);
  8492. ASSERT_EQ("a.html", file2.filename);
  8493. ASSERT_EQ("text/html", file2.content_type);
  8494. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8495. file2.content);
  8496. // Test text field
  8497. const auto &text = req.form.get_field("text");
  8498. ASSERT_EQ("text default", text);
  8499. res.set_content("ok", "text/plain");
  8500. handled = true;
  8501. });
  8502. thread t = thread([&] { svr.listen(HOST, PORT); });
  8503. auto se = detail::scope_exit([&] {
  8504. svr.stop();
  8505. t.join();
  8506. ASSERT_FALSE(svr.is_running());
  8507. ASSERT_TRUE(handled);
  8508. });
  8509. svr.wait_until_ready();
  8510. auto req = "POST /test HTTP/1.1\r\n"
  8511. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8512. "Content-Length: 399\r\n"
  8513. "\r\n"
  8514. "----------\r\n"
  8515. "Content-Disposition: form-data; name=\"text\"\r\n"
  8516. "\r\n"
  8517. "text default\r\n"
  8518. "----------\r\n"
  8519. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8520. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8521. "Content-Type: text/plain\r\n"
  8522. "\r\n"
  8523. "Content of a.txt.\r\n"
  8524. "\r\n"
  8525. "----------\r\n"
  8526. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8527. "\"a.html\"\r\n"
  8528. "Content-Type: text/html\r\n"
  8529. "\r\n"
  8530. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8531. "\r\n"
  8532. "------------\r\n";
  8533. ASSERT_TRUE(send_request(1, req));
  8534. }
  8535. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8536. auto handled = false;
  8537. Server svr;
  8538. svr.Post("/test", [&](const Request &req, Response &) {
  8539. ASSERT_EQ(2u, req.form.fields.size());
  8540. const auto &text1 = req.form.get_field("text1");
  8541. ASSERT_EQ("text1", text1);
  8542. const auto &text2 = req.form.get_field("text2");
  8543. ASSERT_EQ("text2", text2);
  8544. handled = true;
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. ASSERT_TRUE(handled);
  8552. });
  8553. svr.wait_until_ready();
  8554. auto req = "POST /test HTTP/1.1\r\n"
  8555. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8556. "Content-Length: 146\r\n"
  8557. "\r\n----------\r\n"
  8558. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8559. "\r\n"
  8560. "text1"
  8561. "\r\n----------\r\n"
  8562. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8563. "\r\n"
  8564. "text2"
  8565. "\r\n------------";
  8566. std::string response;
  8567. ASSERT_TRUE(send_request(1, req, &response));
  8568. ASSERT_EQ("200", response.substr(9, 3));
  8569. }
  8570. TEST(MultipartFormDataTest, ContentLength) {
  8571. auto handled = false;
  8572. Server svr;
  8573. svr.Post("/test", [&](const Request &req, Response &) {
  8574. ASSERT_EQ(2u, req.form.fields.size());
  8575. const auto &text1 = req.form.get_field("text1");
  8576. ASSERT_EQ("text1", text1);
  8577. const auto &text2 = req.form.get_field("text2");
  8578. ASSERT_EQ("text2", text2);
  8579. handled = true;
  8580. });
  8581. thread t = thread([&] { svr.listen(HOST, PORT); });
  8582. auto se = detail::scope_exit([&] {
  8583. svr.stop();
  8584. t.join();
  8585. ASSERT_FALSE(svr.is_running());
  8586. ASSERT_TRUE(handled);
  8587. });
  8588. svr.wait_until_ready();
  8589. auto req = "POST /test HTTP/1.1\r\n"
  8590. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8591. "Content-Length: 167\r\n"
  8592. "\r\n----------\r\n"
  8593. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8594. "Content-Length: 5\r\n"
  8595. "\r\n"
  8596. "text1"
  8597. "\r\n----------\r\n"
  8598. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8599. "\r\n"
  8600. "text2"
  8601. "\r\n------------\r\n";
  8602. std::string response;
  8603. ASSERT_TRUE(send_request(1, req, &response));
  8604. ASSERT_EQ("200", response.substr(9, 3));
  8605. }
  8606. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8607. auto handled = false;
  8608. Server svr;
  8609. svr.Post("/test", [&](const Request &req, Response &) {
  8610. ASSERT_EQ(2u, req.form.fields.size());
  8611. const auto &text1 = req.form.get_field("text1");
  8612. ASSERT_EQ("text1", text1);
  8613. // TODO: Add header access for text fields if needed
  8614. const auto &text2 = req.form.get_field("text2");
  8615. ASSERT_EQ("text2", text2);
  8616. // TODO: Header access for text fields needs to be implemented
  8617. // auto &headers = it->second.headers;
  8618. // ASSERT_EQ(3U, headers.size());
  8619. // auto custom_header = headers.find("x-whatever");
  8620. // ASSERT_TRUE(custom_header != headers.end());
  8621. // ASSERT_NE("customvalue", custom_header->second);
  8622. // ASSERT_EQ("CustomValue", custom_header->second);
  8623. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8624. handled = true;
  8625. });
  8626. thread t = thread([&] { svr.listen(HOST, PORT); });
  8627. auto se = detail::scope_exit([&] {
  8628. svr.stop();
  8629. t.join();
  8630. ASSERT_FALSE(svr.is_running());
  8631. ASSERT_TRUE(handled);
  8632. });
  8633. svr.wait_until_ready();
  8634. auto req = "POST /test HTTP/1.1\r\n"
  8635. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8636. "Content-Length: 232\r\n"
  8637. "\r\n----------\r\n"
  8638. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8639. "Content-Length: 5\r\n"
  8640. "X-Test: 1\r\n"
  8641. "\r\n"
  8642. "text1"
  8643. "\r\n----------\r\n"
  8644. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8645. "Content-Type: text/plain\r\n"
  8646. "X-Whatever: CustomValue\r\n"
  8647. "\r\n"
  8648. "text2"
  8649. "\r\n------------\r\n"
  8650. "That should be disregarded. Not even read";
  8651. std::string response;
  8652. ASSERT_TRUE(send_request(1, req, &response));
  8653. ASSERT_EQ("200", response.substr(9, 3));
  8654. }
  8655. #endif
  8656. TEST(MultipartFormDataTest, LargeHeader) {
  8657. auto handled = false;
  8658. Server svr;
  8659. svr.Post("/test", [&](const Request &req, Response &) {
  8660. ASSERT_EQ(1u, req.form.fields.size());
  8661. const auto &text = req.form.get_field("name1");
  8662. ASSERT_EQ("text1", text);
  8663. handled = true;
  8664. });
  8665. thread t = thread([&] { svr.listen(HOST, PORT); });
  8666. auto se = detail::scope_exit([&] {
  8667. svr.stop();
  8668. t.join();
  8669. ASSERT_FALSE(svr.is_running());
  8670. ASSERT_TRUE(handled);
  8671. });
  8672. svr.wait_until_ready();
  8673. auto boundary = std::string("cpp-httplib-multipart-data");
  8674. std::string content = "--" + boundary +
  8675. "\r\n"
  8676. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8677. "\r\n"
  8678. "text1\r\n"
  8679. "--" +
  8680. boundary + "--\r\n";
  8681. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8682. "Content-Type: multipart/form-data;boundary=" +
  8683. boundary +
  8684. "\r\n"
  8685. "Content-Length: " +
  8686. std::to_string(content.size()) +
  8687. "\r\n"
  8688. "Dummy-Header: ";
  8689. std::string header_suffix = "\r\n"
  8690. "\r\n";
  8691. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8692. size_t header_dummy_size =
  8693. read_buff_size -
  8694. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8695. auto header_dummy = std::string(header_dummy_size, '@');
  8696. auto req = header_prefix + header_dummy + header_suffix + content;
  8697. std::string response;
  8698. ASSERT_TRUE(send_request(1, req, &response));
  8699. ASSERT_EQ("200", response.substr(9, 3));
  8700. }
  8701. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8702. static constexpr unsigned int number_of_tasks{1000000};
  8703. std::atomic_uint count{0};
  8704. std::unique_ptr<TaskQueue> task_queue{
  8705. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8706. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8707. auto queued = task_queue->enqueue(
  8708. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8709. EXPECT_TRUE(queued);
  8710. }
  8711. EXPECT_NO_THROW(task_queue->shutdown());
  8712. EXPECT_EQ(number_of_tasks, count.load());
  8713. }
  8714. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8715. static constexpr unsigned int number_of_tasks{1000000};
  8716. static constexpr unsigned int qlimit{2};
  8717. unsigned int queued_count{0};
  8718. std::atomic_uint count{0};
  8719. std::unique_ptr<TaskQueue> task_queue{
  8720. new ThreadPool{/*num_threads=*/1, qlimit}};
  8721. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8722. if (task_queue->enqueue(
  8723. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8724. queued_count++;
  8725. }
  8726. }
  8727. EXPECT_NO_THROW(task_queue->shutdown());
  8728. EXPECT_EQ(queued_count, count.load());
  8729. EXPECT_TRUE(queued_count <= number_of_tasks);
  8730. EXPECT_TRUE(queued_count >= qlimit);
  8731. }
  8732. TEST(TaskQueueTest, MaxQueuedRequests) {
  8733. static constexpr unsigned int qlimit{3};
  8734. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8735. std::condition_variable sem_cv;
  8736. std::mutex sem_mtx;
  8737. int credits = 0;
  8738. bool queued;
  8739. /* Fill up the queue with tasks that will block until we give them credits to
  8740. * complete. */
  8741. for (unsigned int n = 0; n <= qlimit;) {
  8742. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8743. std::unique_lock<std::mutex> lock(sem_mtx);
  8744. while (credits <= 0) {
  8745. sem_cv.wait(lock);
  8746. }
  8747. /* Consume the credit and signal the test code if they are all gone. */
  8748. if (--credits == 0) { sem_cv.notify_one(); }
  8749. });
  8750. if (n < qlimit) {
  8751. /* The first qlimit enqueues must succeed. */
  8752. EXPECT_TRUE(queued);
  8753. } else {
  8754. /* The last one will succeed only when the worker thread
  8755. * starts and dequeues the first blocking task. Although
  8756. * not necessary for the correctness of this test, we sleep for
  8757. * a short while to avoid busy waiting. */
  8758. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8759. }
  8760. if (queued) { n++; }
  8761. }
  8762. /* Further enqueues must fail since the queue is full. */
  8763. for (auto i = 0; i < 4; i++) {
  8764. queued = task_queue->enqueue([] {});
  8765. EXPECT_FALSE(queued);
  8766. }
  8767. /* Give the credits to allow the previous tasks to complete. */
  8768. {
  8769. std::unique_lock<std::mutex> lock(sem_mtx);
  8770. credits += qlimit + 1;
  8771. }
  8772. sem_cv.notify_all();
  8773. /* Wait for all the credits to be consumed. */
  8774. {
  8775. std::unique_lock<std::mutex> lock(sem_mtx);
  8776. while (credits > 0) {
  8777. sem_cv.wait(lock);
  8778. }
  8779. }
  8780. /* Check that we are able again to enqueue at least qlimit tasks. */
  8781. for (unsigned int i = 0; i < qlimit; i++) {
  8782. queued = task_queue->enqueue([] {});
  8783. EXPECT_TRUE(queued);
  8784. }
  8785. EXPECT_NO_THROW(task_queue->shutdown());
  8786. }
  8787. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8788. Server svr;
  8789. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8790. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8791. });
  8792. svr.Get("/hello", [](const Request &req, Response &res) {
  8793. res.set_content(req.get_param_value("key"), "text/plain");
  8794. });
  8795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8796. auto se = detail::scope_exit([&] {
  8797. svr.stop();
  8798. thread.join();
  8799. ASSERT_FALSE(svr.is_running());
  8800. });
  8801. svr.wait_until_ready();
  8802. {
  8803. Client cli(HOST, PORT);
  8804. cli.set_follow_location(true);
  8805. auto res = cli.Get("/");
  8806. ASSERT_TRUE(res);
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. EXPECT_EQ("val&key2=val2", res->body);
  8809. }
  8810. }
  8811. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8812. Server svr;
  8813. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8814. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8815. });
  8816. svr.Get("/hello", [](const Request &req, Response &res) {
  8817. res.set_content(req.get_param_value("key"), "text/plain");
  8818. });
  8819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8820. auto se = detail::scope_exit([&] {
  8821. svr.stop();
  8822. thread.join();
  8823. ASSERT_FALSE(svr.is_running());
  8824. });
  8825. svr.wait_until_ready();
  8826. {
  8827. Client cli(HOST, PORT);
  8828. cli.set_follow_location(true);
  8829. auto res = cli.Get("/");
  8830. ASSERT_TRUE(res);
  8831. EXPECT_EQ(StatusCode::OK_200, res->status);
  8832. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8833. }
  8834. }
  8835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8836. TEST(RedirectTest, Issue2185_Online) {
  8837. SSLClient client("github.com");
  8838. client.set_follow_location(true);
  8839. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8840. "Coollab-Windows.zip");
  8841. ASSERT_TRUE(res);
  8842. EXPECT_EQ(StatusCode::OK_200, res->status);
  8843. EXPECT_EQ(9920427U, res->body.size());
  8844. }
  8845. #endif
  8846. TEST(VulnerabilityTest, CRLFInjection) {
  8847. Server svr;
  8848. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8849. res.set_content("Hello 1", "text/plain");
  8850. });
  8851. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8852. res.set_content("Hello 2", "text/plain");
  8853. });
  8854. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8855. res.set_content("Hello 3", "text/plain");
  8856. });
  8857. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8858. res.set_content("Hello 4", "text/plain");
  8859. });
  8860. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8861. for (const auto &x : req.headers) {
  8862. auto key = x.first;
  8863. EXPECT_STRNE("evil", key.c_str());
  8864. }
  8865. });
  8866. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8867. auto se = detail::scope_exit([&] {
  8868. svr.stop();
  8869. thread.join();
  8870. ASSERT_FALSE(svr.is_running());
  8871. });
  8872. svr.wait_until_ready();
  8873. {
  8874. Client cli(HOST, PORT);
  8875. cli.Post("/test1", "A=B",
  8876. "application/x-www-form-urlencoded\r\nevil: hello1");
  8877. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8878. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8879. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8880. }
  8881. }
  8882. TEST(PathParamsTest, StaticMatch) {
  8883. const auto pattern = "/users/all";
  8884. detail::PathParamsMatcher matcher(pattern);
  8885. Request request;
  8886. request.path = "/users/all";
  8887. ASSERT_TRUE(matcher.match(request));
  8888. std::unordered_map<std::string, std::string> expected_params = {};
  8889. EXPECT_EQ(request.path_params, expected_params);
  8890. }
  8891. TEST(PathParamsTest, StaticMismatch) {
  8892. const auto pattern = "/users/all";
  8893. detail::PathParamsMatcher matcher(pattern);
  8894. Request request;
  8895. request.path = "/users/1";
  8896. ASSERT_FALSE(matcher.match(request));
  8897. }
  8898. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8899. const auto pattern = "/users/:id/subscriptions";
  8900. detail::PathParamsMatcher matcher(pattern);
  8901. Request request;
  8902. request.path = "/users/42/subscriptions";
  8903. ASSERT_TRUE(matcher.match(request));
  8904. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8905. EXPECT_EQ(request.path_params, expected_params);
  8906. }
  8907. TEST(PathParamsTest, SingleParamInTheEnd) {
  8908. const auto pattern = "/users/:id";
  8909. detail::PathParamsMatcher matcher(pattern);
  8910. Request request;
  8911. request.path = "/users/24";
  8912. ASSERT_TRUE(matcher.match(request));
  8913. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8914. EXPECT_EQ(request.path_params, expected_params);
  8915. }
  8916. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8917. const auto pattern = "/users/:id/";
  8918. detail::PathParamsMatcher matcher(pattern);
  8919. Request request;
  8920. request.path = "/users/42/";
  8921. ASSERT_TRUE(matcher.match(request));
  8922. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8923. EXPECT_EQ(request.path_params, expected_params);
  8924. }
  8925. TEST(PathParamsTest, EmptyParam) {
  8926. const auto pattern = "/users/:id/";
  8927. detail::PathParamsMatcher matcher(pattern);
  8928. Request request;
  8929. request.path = "/users//";
  8930. ASSERT_TRUE(matcher.match(request));
  8931. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8932. EXPECT_EQ(request.path_params, expected_params);
  8933. }
  8934. TEST(PathParamsTest, FragmentMismatch) {
  8935. const auto pattern = "/users/:id/";
  8936. detail::PathParamsMatcher matcher(pattern);
  8937. Request request;
  8938. request.path = "/admins/24/";
  8939. ASSERT_FALSE(matcher.match(request));
  8940. }
  8941. TEST(PathParamsTest, ExtraFragments) {
  8942. const auto pattern = "/users/:id";
  8943. detail::PathParamsMatcher matcher(pattern);
  8944. Request request;
  8945. request.path = "/users/42/subscriptions";
  8946. ASSERT_FALSE(matcher.match(request));
  8947. }
  8948. TEST(PathParamsTest, MissingTrailingParam) {
  8949. const auto pattern = "/users/:id";
  8950. detail::PathParamsMatcher matcher(pattern);
  8951. Request request;
  8952. request.path = "/users";
  8953. ASSERT_FALSE(matcher.match(request));
  8954. }
  8955. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8956. const auto pattern = "/users/:id/subscriptions";
  8957. detail::PathParamsMatcher matcher(pattern);
  8958. Request request;
  8959. request.path = "/users/subscriptions";
  8960. ASSERT_FALSE(matcher.match(request));
  8961. }
  8962. TEST(PathParamsTest, MultipleParams) {
  8963. const auto pattern = "/users/:userid/subscriptions/:subid";
  8964. detail::PathParamsMatcher matcher(pattern);
  8965. Request request;
  8966. request.path = "/users/42/subscriptions/2";
  8967. ASSERT_TRUE(matcher.match(request));
  8968. std::unordered_map<std::string, std::string> expected_params = {
  8969. {"userid", "42"}, {"subid", "2"}};
  8970. EXPECT_EQ(request.path_params, expected_params);
  8971. }
  8972. TEST(PathParamsTest, SequenceOfParams) {
  8973. const auto pattern = "/values/:x/:y/:z";
  8974. detail::PathParamsMatcher matcher(pattern);
  8975. Request request;
  8976. request.path = "/values/1/2/3";
  8977. ASSERT_TRUE(matcher.match(request));
  8978. std::unordered_map<std::string, std::string> expected_params = {
  8979. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8980. EXPECT_EQ(request.path_params, expected_params);
  8981. }
  8982. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8983. const auto pattern = "/prefix:suffix";
  8984. detail::PathParamsMatcher matcher(pattern);
  8985. Request request;
  8986. request.path = "/prefix:suffix";
  8987. ASSERT_TRUE(matcher.match(request));
  8988. const std::unordered_map<std::string, std::string> expected_params = {};
  8989. EXPECT_EQ(request.path_params, expected_params);
  8990. }
  8991. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8992. // If ipv6 regex working, regex match codepath is taken.
  8993. // else port will default to 80 in Client impl
  8994. int clientImplMagicPort = 80;
  8995. int port = 4321;
  8996. // above ports must be different to avoid false negative
  8997. EXPECT_NE(clientImplMagicPort, port);
  8998. std::string ipV6TestURL = "http://[ff06::c3]";
  8999. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9000. CLIENT_PRIVATE_KEY_FILE);
  9001. EXPECT_EQ(cli.port(), port);
  9002. }
  9003. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9004. auto file_path = "./www/dir/index.html";
  9005. auto dir_path = "./www/dir";
  9006. detail::FileStat stat_file(file_path);
  9007. EXPECT_TRUE(stat_file.is_file());
  9008. EXPECT_FALSE(stat_file.is_dir());
  9009. detail::FileStat stat_dir(dir_path);
  9010. EXPECT_FALSE(stat_dir.is_file());
  9011. EXPECT_TRUE(stat_dir.is_dir());
  9012. }
  9013. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9014. // IPv4 with default HTTP port (80)
  9015. EXPECT_EQ("example.com",
  9016. detail::make_host_and_port_string("example.com", 80, false));
  9017. // IPv4 with default HTTPS port (443)
  9018. EXPECT_EQ("example.com",
  9019. detail::make_host_and_port_string("example.com", 443, true));
  9020. // IPv4 with non-default HTTP port
  9021. EXPECT_EQ("example.com:8080",
  9022. detail::make_host_and_port_string("example.com", 8080, false));
  9023. // IPv4 with non-default HTTPS port
  9024. EXPECT_EQ("example.com:8443",
  9025. detail::make_host_and_port_string("example.com", 8443, true));
  9026. // IPv6 with default HTTP port (80)
  9027. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9028. // IPv6 with default HTTPS port (443)
  9029. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9030. // IPv6 with non-default HTTP port
  9031. EXPECT_EQ("[::1]:8080",
  9032. detail::make_host_and_port_string("::1", 8080, false));
  9033. // IPv6 with non-default HTTPS port
  9034. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9035. // IPv6 full address with default port
  9036. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9037. detail::make_host_and_port_string(
  9038. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9039. // IPv6 full address with non-default port
  9040. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9041. detail::make_host_and_port_string(
  9042. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9043. // IPv6 localhost with non-default port
  9044. EXPECT_EQ("[::1]:3000",
  9045. detail::make_host_and_port_string("::1", 3000, false));
  9046. // IPv6 with zone ID (link-local address) with default port
  9047. EXPECT_EQ("[fe80::1%eth0]",
  9048. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9049. // IPv6 with zone ID (link-local address) with non-default port
  9050. EXPECT_EQ("[fe80::1%eth0]:8080",
  9051. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9052. // Edge case: Port 443 with is_ssl=false (should add port)
  9053. EXPECT_EQ("example.com:443",
  9054. detail::make_host_and_port_string("example.com", 443, false));
  9055. // Edge case: Port 80 with is_ssl=true (should add port)
  9056. EXPECT_EQ("example.com:80",
  9057. detail::make_host_and_port_string("example.com", 80, true));
  9058. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9059. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9060. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9061. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9062. // Security fix: Already bracketed IPv6 should not get double brackets
  9063. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9064. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9065. EXPECT_EQ("[::1]:8080",
  9066. detail::make_host_and_port_string("[::1]", 8080, false));
  9067. EXPECT_EQ("[2001:db8::1]:8080",
  9068. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9069. EXPECT_EQ("[fe80::1%eth0]",
  9070. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9071. EXPECT_EQ("[fe80::1%eth0]:8080",
  9072. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9073. // Edge case: Empty host (should return as-is)
  9074. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9075. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9076. // This is a known limitation but shouldn't crash
  9077. EXPECT_EQ("[host:name]",
  9078. detail::make_host_and_port_string("host:name", 80, false));
  9079. // Port number edge cases (no validation, but should not crash)
  9080. EXPECT_EQ("example.com:0",
  9081. detail::make_host_and_port_string("example.com", 0, false));
  9082. EXPECT_EQ("example.com:-1",
  9083. detail::make_host_and_port_string("example.com", -1, false));
  9084. EXPECT_EQ("example.com:65535",
  9085. detail::make_host_and_port_string("example.com", 65535, false));
  9086. EXPECT_EQ("example.com:65536",
  9087. detail::make_host_and_port_string("example.com", 65536, false));
  9088. }
  9089. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9090. Server svr;
  9091. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9092. EXPECT_EQ(res.status, 400);
  9093. });
  9094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9095. auto se = detail::scope_exit([&] {
  9096. svr.stop();
  9097. thread.join();
  9098. ASSERT_FALSE(svr.is_running());
  9099. });
  9100. svr.wait_until_ready();
  9101. Client cli(HOST, PORT);
  9102. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9103. }
  9104. TEST(InvalidHeaderCharsTest, is_field_name) {
  9105. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9106. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9107. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9108. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9109. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9110. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9111. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9112. EXPECT_FALSE(detail::fields::is_field_name(""));
  9113. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9114. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9115. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9116. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9117. }
  9118. TEST(InvalidHeaderCharsTest, is_field_value) {
  9119. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9120. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9121. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9122. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9123. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9124. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9125. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9126. EXPECT_TRUE(detail::fields::is_field_value(""));
  9127. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9128. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9129. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9130. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9131. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9132. }
  9133. TEST(InvalidHeaderCharsTest, OnServer) {
  9134. Server svr;
  9135. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9136. std::string header = "Not Set";
  9137. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9138. res.set_header(header, "value");
  9139. res.set_content("Page Content Page Content", "text/plain");
  9140. });
  9141. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9142. std::string header = "Not Set";
  9143. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9144. res.set_header("X-Test", header);
  9145. res.set_content("Page Content Page Content", "text/plain");
  9146. });
  9147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9148. auto se = detail::scope_exit([&] {
  9149. svr.stop();
  9150. thread.join();
  9151. ASSERT_FALSE(svr.is_running());
  9152. });
  9153. svr.wait_until_ready();
  9154. Client cli(HOST, PORT);
  9155. {
  9156. auto res = cli.Get(
  9157. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9158. ASSERT_TRUE(res);
  9159. EXPECT_EQ("Page Content Page Content", res->body);
  9160. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9161. }
  9162. {
  9163. auto res = cli.Get(
  9164. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9165. ASSERT_TRUE(res);
  9166. EXPECT_EQ("Page Content Page Content", res->body);
  9167. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9168. }
  9169. }
  9170. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9171. auto handled = false;
  9172. Server svr;
  9173. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9174. thread t = thread([&] { svr.listen(HOST, PORT); });
  9175. auto se = detail::scope_exit([&] {
  9176. svr.stop();
  9177. t.join();
  9178. ASSERT_FALSE(svr.is_running());
  9179. ASSERT_FALSE(handled);
  9180. });
  9181. svr.wait_until_ready();
  9182. auto req = "POST /test HTTP/1.1\r\n"
  9183. "Content-Length: x\r\n"
  9184. "\r\n";
  9185. std::string response;
  9186. ASSERT_TRUE(send_request(1, req, &response));
  9187. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9188. response.substr(0, response.find("\r\n")));
  9189. }
  9190. #ifndef _WIN32
  9191. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9192. static constexpr char reject[] = "Unauthorized";
  9193. static constexpr char accept[] = "Upload accepted";
  9194. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9195. Server svr;
  9196. svr.set_expect_100_continue_handler(
  9197. [](const Request & /*req*/, Response &res) {
  9198. res.status = StatusCode::Unauthorized_401;
  9199. res.set_content(reject, "text/plain");
  9200. return res.status;
  9201. });
  9202. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9203. res.set_content(accept, "text/plain");
  9204. });
  9205. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9206. auto se = detail::scope_exit([&] {
  9207. svr.stop();
  9208. thread.join();
  9209. ASSERT_FALSE(svr.is_running());
  9210. });
  9211. svr.wait_until_ready();
  9212. {
  9213. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9214. curl_easy_init(), &curl_easy_cleanup};
  9215. ASSERT_NE(curl, nullptr);
  9216. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9217. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9218. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9219. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9220. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9221. &curl_slist_free_all};
  9222. ASSERT_NE(list, nullptr);
  9223. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9224. struct read_data {
  9225. size_t read_size;
  9226. size_t total_size;
  9227. } data = {0, total_size};
  9228. using read_callback_t =
  9229. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9230. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9231. void *userdata) -> size_t {
  9232. read_data *data = (read_data *)userdata;
  9233. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9234. std::fill_n(ptr, size * nmemb, 'A');
  9235. data->read_size += size * nmemb;
  9236. return size * nmemb;
  9237. };
  9238. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9239. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9240. std::vector<char> buffer;
  9241. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9242. using write_callback_t =
  9243. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9244. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9245. void *userdata) -> size_t {
  9246. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9247. buffer->reserve(buffer->size() + size * nmemb + 1);
  9248. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9249. return size * nmemb;
  9250. };
  9251. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9252. {
  9253. const auto res = curl_easy_perform(curl.get());
  9254. ASSERT_EQ(res, CURLE_OK);
  9255. }
  9256. {
  9257. auto response_code = long{};
  9258. const auto res =
  9259. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9260. ASSERT_EQ(res, CURLE_OK);
  9261. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9262. }
  9263. {
  9264. auto dl = curl_off_t{};
  9265. const auto res =
  9266. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9267. ASSERT_EQ(res, CURLE_OK);
  9268. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9269. }
  9270. {
  9271. buffer.push_back('\0');
  9272. ASSERT_STRCASEEQ(buffer.data(), reject);
  9273. }
  9274. }
  9275. }
  9276. #endif
  9277. template <typename S, typename C>
  9278. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9279. svr.Get("/stream", [&](const Request &, Response &res) {
  9280. auto data = new std::string("01234567890123456789");
  9281. res.set_content_provider(
  9282. data->size(), "text/plain",
  9283. [&, data](size_t offset, size_t length, DataSink &sink) {
  9284. const size_t DATA_CHUNK_SIZE = 4;
  9285. const auto &d = *data;
  9286. std::this_thread::sleep_for(std::chrono::seconds(1));
  9287. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9288. return true;
  9289. },
  9290. [data](bool success) {
  9291. EXPECT_FALSE(success);
  9292. delete data;
  9293. });
  9294. });
  9295. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9296. auto i = new size_t(0);
  9297. res.set_content_provider(
  9298. "text/plain",
  9299. [i](size_t, DataSink &sink) {
  9300. if (*i < 5) {
  9301. std::this_thread::sleep_for(std::chrono::seconds(1));
  9302. sink.write("abcd", 4);
  9303. (*i)++;
  9304. } else {
  9305. sink.done();
  9306. }
  9307. return true;
  9308. },
  9309. [i](bool success) {
  9310. EXPECT_FALSE(success);
  9311. delete i;
  9312. });
  9313. });
  9314. svr.Get("/chunked", [&](const Request &, Response &res) {
  9315. auto i = new size_t(0);
  9316. res.set_chunked_content_provider(
  9317. "text/plain",
  9318. [i](size_t, DataSink &sink) {
  9319. if (*i < 5) {
  9320. std::this_thread::sleep_for(std::chrono::seconds(1));
  9321. sink.os << "abcd";
  9322. (*i)++;
  9323. } else {
  9324. sink.done();
  9325. }
  9326. return true;
  9327. },
  9328. [i](bool success) {
  9329. EXPECT_FALSE(success);
  9330. delete i;
  9331. });
  9332. });
  9333. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9334. auto se = detail::scope_exit([&] {
  9335. svr.stop();
  9336. listen_thread.join();
  9337. ASSERT_FALSE(svr.is_running());
  9338. });
  9339. svr.wait_until_ready();
  9340. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9341. {
  9342. auto start = std::chrono::steady_clock::now();
  9343. auto res = cli.Get("/stream");
  9344. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9345. std::chrono::steady_clock::now() - start)
  9346. .count();
  9347. ASSERT_FALSE(res);
  9348. EXPECT_EQ(Error::Read, res.error());
  9349. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9350. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9351. }
  9352. {
  9353. auto start = std::chrono::steady_clock::now();
  9354. auto res = cli.Get("/stream_without_length");
  9355. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9356. std::chrono::steady_clock::now() - start)
  9357. .count();
  9358. ASSERT_FALSE(res);
  9359. EXPECT_EQ(Error::Read, res.error());
  9360. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9361. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9362. }
  9363. {
  9364. auto start = std::chrono::steady_clock::now();
  9365. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9366. EXPECT_EQ("abcd", string(data, data_length));
  9367. return true;
  9368. });
  9369. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9370. std::chrono::steady_clock::now() - start)
  9371. .count();
  9372. ASSERT_FALSE(res);
  9373. EXPECT_EQ(Error::Read, res.error());
  9374. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9375. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9376. }
  9377. }
  9378. TEST(MaxTimeoutTest, ContentStream) {
  9379. time_t timeout = 2000;
  9380. time_t threshold = 200;
  9381. Server svr;
  9382. Client cli("localhost", PORT);
  9383. max_timeout_test(svr, cli, timeout, threshold);
  9384. }
  9385. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9386. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9387. time_t timeout = 2000;
  9388. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9390. SSLClient cli("localhost", PORT);
  9391. cli.enable_server_certificate_verification(false);
  9392. max_timeout_test(svr, cli, timeout, threshold);
  9393. }
  9394. #endif
  9395. class EventDispatcher {
  9396. public:
  9397. EventDispatcher() {}
  9398. bool wait_event(DataSink *sink) {
  9399. unique_lock<mutex> lk(m_);
  9400. int id = id_;
  9401. // Wait with timeout to prevent hanging if client disconnects
  9402. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9403. [&] { return cid_ == id; })) {
  9404. return false; // Timeout occurred
  9405. }
  9406. sink->write(message_.data(), message_.size());
  9407. return true;
  9408. }
  9409. void send_event(const string &message) {
  9410. lock_guard<mutex> lk(m_);
  9411. cid_ = id_++;
  9412. message_ = message;
  9413. cv_.notify_all();
  9414. }
  9415. private:
  9416. mutex m_;
  9417. condition_variable cv_;
  9418. atomic_int id_{0};
  9419. atomic_int cid_{-1};
  9420. string message_;
  9421. };
  9422. TEST(ClientInThreadTest, Issue2068) {
  9423. EventDispatcher ed;
  9424. Server svr;
  9425. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9426. res.set_chunked_content_provider("text/event-stream",
  9427. [&](size_t /*offset*/, DataSink &sink) {
  9428. return ed.wait_event(&sink);
  9429. });
  9430. });
  9431. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9432. svr.wait_until_ready();
  9433. thread event_thread([&] {
  9434. int id = 0;
  9435. while (svr.is_running()) {
  9436. this_thread::sleep_for(chrono::milliseconds(500));
  9437. std::stringstream ss;
  9438. ss << "data: " << id << "\n\n";
  9439. ed.send_event(ss.str());
  9440. id++;
  9441. }
  9442. });
  9443. auto se = detail::scope_exit([&] {
  9444. svr.stop();
  9445. listen_thread.join();
  9446. event_thread.join();
  9447. ASSERT_FALSE(svr.is_running());
  9448. });
  9449. {
  9450. auto client = detail::make_unique<Client>(HOST, PORT);
  9451. client->set_read_timeout(std::chrono::minutes(10));
  9452. std::atomic<bool> stop{false};
  9453. std::thread t([&] {
  9454. client->Get("/event1",
  9455. [&](const char *, size_t) -> bool { return !stop; });
  9456. });
  9457. std::this_thread::sleep_for(std::chrono::seconds(2));
  9458. stop = true;
  9459. client->stop();
  9460. t.join();
  9461. // Reset client after thread has finished
  9462. client.reset();
  9463. }
  9464. }
  9465. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9466. Server svr;
  9467. svr.Get("/", [](const Request &req, Response &res) {
  9468. EXPECT_EQ(2U, req.trailers.size());
  9469. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9470. // Denied
  9471. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9472. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9473. // Accepted
  9474. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9475. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9476. EXPECT_TRUE(req.has_trailer("X-World"));
  9477. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9478. res.set_content("ok", "text/plain");
  9479. });
  9480. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. t.join();
  9484. ASSERT_FALSE(svr.is_running());
  9485. });
  9486. svr.wait_until_ready();
  9487. const std::string req = "GET / HTTP/1.1\r\n"
  9488. "Transfer-Encoding: chunked\r\n"
  9489. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9490. "\r\n"
  9491. "0\r\n"
  9492. "Content-Length: 10\r\n"
  9493. "Host: internal.local\r\n"
  9494. "Content-Type: malicious/content\r\n"
  9495. "Cookie: any\r\n"
  9496. "Set-Cookie: any\r\n"
  9497. "X-Forwarded-For: attacker.com\r\n"
  9498. "X-Real-Ip: 1.1.1.1\r\n"
  9499. "X-Hello: hello\r\n"
  9500. "X-World: world\r\n"
  9501. "\r\n";
  9502. std::string res;
  9503. ASSERT_TRUE(send_request(1, req, &res));
  9504. }
  9505. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9506. Server svr;
  9507. std::string observed_remote_addr;
  9508. std::string observed_xff;
  9509. svr.Get("/ip", [&](const Request &req, Response &res) {
  9510. observed_remote_addr = req.remote_addr;
  9511. observed_xff = req.get_header_value("X-Forwarded-For");
  9512. res.set_content("ok", "text/plain");
  9513. });
  9514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. Client cli(HOST, PORT);
  9522. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9523. ASSERT_TRUE(res);
  9524. EXPECT_EQ(StatusCode::OK_200, res->status);
  9525. EXPECT_EQ(observed_xff, "203.0.113.66");
  9526. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9527. observed_remote_addr == "127.0.0.1");
  9528. }
  9529. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9530. Server svr;
  9531. svr.set_trusted_proxies({"203.0.113.66"});
  9532. std::string observed_remote_addr;
  9533. std::string observed_xff;
  9534. svr.Get("/ip", [&](const Request &req, Response &res) {
  9535. observed_remote_addr = req.remote_addr;
  9536. observed_xff = req.get_header_value("X-Forwarded-For");
  9537. res.set_content("ok", "text/plain");
  9538. });
  9539. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9540. auto se = detail::scope_exit([&] {
  9541. svr.stop();
  9542. t.join();
  9543. ASSERT_FALSE(svr.is_running());
  9544. });
  9545. svr.wait_until_ready();
  9546. Client cli(HOST, PORT);
  9547. auto res = cli.Get("/ip");
  9548. ASSERT_TRUE(res);
  9549. EXPECT_EQ(StatusCode::OK_200, res->status);
  9550. EXPECT_EQ(observed_xff, "");
  9551. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9552. observed_remote_addr == "127.0.0.1");
  9553. }
  9554. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9555. Server svr;
  9556. svr.set_trusted_proxies({"203.0.113.66"});
  9557. std::string observed_remote_addr;
  9558. std::string observed_xff;
  9559. svr.Get("/ip", [&](const Request &req, Response &res) {
  9560. observed_remote_addr = req.remote_addr;
  9561. observed_xff = req.get_header_value("X-Forwarded-For");
  9562. res.set_content("ok", "text/plain");
  9563. });
  9564. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9565. auto se = detail::scope_exit([&] {
  9566. svr.stop();
  9567. t.join();
  9568. ASSERT_FALSE(svr.is_running());
  9569. });
  9570. svr.wait_until_ready();
  9571. Client cli(HOST, PORT);
  9572. auto res =
  9573. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9574. ASSERT_TRUE(res);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9577. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9578. }
  9579. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9580. Server svr;
  9581. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9582. std::string observed_remote_addr;
  9583. std::string observed_xff;
  9584. svr.Get("/ip", [&](const Request &req, Response &res) {
  9585. observed_remote_addr = req.remote_addr;
  9586. observed_xff = req.get_header_value("X-Forwarded-For");
  9587. res.set_content("ok", "text/plain");
  9588. });
  9589. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9590. auto se = detail::scope_exit([&] {
  9591. svr.stop();
  9592. t.join();
  9593. ASSERT_FALSE(svr.is_running());
  9594. });
  9595. svr.wait_until_ready();
  9596. Client cli(HOST, PORT);
  9597. auto res = cli.Get(
  9598. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9599. ASSERT_TRUE(res);
  9600. EXPECT_EQ(StatusCode::OK_200, res->status);
  9601. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9602. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9603. }
  9604. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9605. Server svr;
  9606. svr.set_trusted_proxies({"192.0.2.45"});
  9607. std::string observed_remote_addr;
  9608. std::string observed_xff;
  9609. svr.Get("/ip", [&](const Request &req, Response &res) {
  9610. observed_remote_addr = req.remote_addr;
  9611. observed_xff = req.get_header_value("X-Forwarded-For");
  9612. res.set_content("ok", "text/plain");
  9613. });
  9614. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9615. auto se = detail::scope_exit([&] {
  9616. svr.stop();
  9617. t.join();
  9618. ASSERT_FALSE(svr.is_running());
  9619. });
  9620. svr.wait_until_ready();
  9621. Client cli(HOST, PORT);
  9622. auto res =
  9623. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9624. ASSERT_TRUE(res);
  9625. EXPECT_EQ(StatusCode::OK_200, res->status);
  9626. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9627. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9628. }
  9629. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9630. Server svr;
  9631. svr.set_trusted_proxies({"192.0.2.45"});
  9632. std::string observed_remote_addr;
  9633. std::string observed_xff;
  9634. svr.Get("/ip", [&](const Request &req, Response &res) {
  9635. observed_remote_addr = req.remote_addr;
  9636. observed_xff = req.get_header_value("X-Forwarded-For");
  9637. res.set_content("ok", "text/plain");
  9638. });
  9639. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9640. auto se = detail::scope_exit([&] {
  9641. svr.stop();
  9642. t.join();
  9643. ASSERT_FALSE(svr.is_running());
  9644. });
  9645. svr.wait_until_ready();
  9646. Client cli(HOST, PORT);
  9647. auto res = cli.Get(
  9648. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9649. ASSERT_TRUE(res);
  9650. EXPECT_EQ(StatusCode::OK_200, res->status);
  9651. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9652. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9653. }
  9654. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9655. Server svr;
  9656. svr.set_trusted_proxies({"192.0.2.45"});
  9657. std::string observed_remote_addr;
  9658. std::string observed_xff;
  9659. svr.Get("/ip", [&](const Request &req, Response &res) {
  9660. observed_remote_addr = req.remote_addr;
  9661. observed_xff = req.get_header_value("X-Forwarded-For");
  9662. res.set_content("ok", "text/plain");
  9663. });
  9664. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9665. auto se = detail::scope_exit([&] {
  9666. svr.stop();
  9667. t.join();
  9668. ASSERT_FALSE(svr.is_running());
  9669. });
  9670. svr.wait_until_ready();
  9671. Client cli(HOST, PORT);
  9672. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9673. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9674. ASSERT_TRUE(res);
  9675. EXPECT_EQ(StatusCode::OK_200, res->status);
  9676. // Header parser trims surrounding whitespace of the header value
  9677. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9678. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9679. }
  9680. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9681. Server svr;
  9682. svr.Post("/post", [&](const Request &req, Response &res) {
  9683. res.set_content(req.body, "text/plain");
  9684. });
  9685. svr.Put("/put", [&](const Request &req, Response &res) {
  9686. res.set_content(req.body, "text/plain");
  9687. });
  9688. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9689. res.set_content(req.body, "text/plain");
  9690. });
  9691. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9692. res.set_content(req.body, "text/plain");
  9693. });
  9694. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. t.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. std::string resp;
  9702. // POST without Content-Length
  9703. ASSERT_TRUE(send_request(5,
  9704. "POST /post HTTP/1.1\r\n"
  9705. "Host: localhost\r\n"
  9706. "Connection: close\r\n"
  9707. "\r\n",
  9708. &resp));
  9709. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9710. // PUT without Content-Length
  9711. resp.clear();
  9712. ASSERT_TRUE(send_request(5,
  9713. "PUT /put HTTP/1.1\r\n"
  9714. "Host: localhost\r\n"
  9715. "Connection: close\r\n"
  9716. "\r\n",
  9717. &resp));
  9718. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9719. // PATCH without Content-Length
  9720. resp.clear();
  9721. ASSERT_TRUE(send_request(5,
  9722. "PATCH /patch HTTP/1.1\r\n"
  9723. "Host: localhost\r\n"
  9724. "Connection: close\r\n"
  9725. "\r\n",
  9726. &resp));
  9727. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9728. // DELETE without Content-Length
  9729. resp.clear();
  9730. ASSERT_TRUE(send_request(5,
  9731. "DELETE /delete HTTP/1.1\r\n"
  9732. "Host: localhost\r\n"
  9733. "Connection: close\r\n"
  9734. "\r\n",
  9735. &resp));
  9736. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9737. }
  9738. //==============================================================================
  9739. // open_stream() Tests
  9740. //==============================================================================
  9741. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9742. std::string result;
  9743. char buf[8192];
  9744. ssize_t n;
  9745. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9746. result.append(buf, static_cast<size_t>(n));
  9747. }
  9748. return result;
  9749. }
  9750. // Mock stream for unit tests
  9751. class MockStream : public Stream {
  9752. public:
  9753. std::string data;
  9754. size_t pos = 0;
  9755. ssize_t error_after = -1; // -1 = no error
  9756. explicit MockStream(const std::string &d, ssize_t err = -1)
  9757. : data(d), error_after(err) {}
  9758. bool is_readable() const override { return true; }
  9759. bool wait_readable() const override { return true; }
  9760. bool wait_writable() const override { return true; }
  9761. ssize_t read(char *ptr, size_t size) override {
  9762. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9763. if (pos >= data.size()) return 0;
  9764. size_t limit =
  9765. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9766. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9767. std::memcpy(ptr, data.data() + pos, to_read);
  9768. pos += to_read;
  9769. return static_cast<ssize_t>(to_read);
  9770. }
  9771. ssize_t write(const char *, size_t) override { return -1; }
  9772. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9773. ip = "127.0.0.1";
  9774. port = 0;
  9775. }
  9776. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9777. ip = "127.0.0.1";
  9778. port = 0;
  9779. }
  9780. socket_t socket() const override { return INVALID_SOCKET; }
  9781. time_t duration() const override { return 0; }
  9782. };
  9783. TEST(StreamHandleTest, Basic) {
  9784. ClientImpl::StreamHandle handle;
  9785. EXPECT_FALSE(handle.is_valid());
  9786. handle.response = detail::make_unique<Response>();
  9787. handle.error = Error::Connection;
  9788. EXPECT_FALSE(handle.is_valid());
  9789. handle.error = Error::Success;
  9790. EXPECT_TRUE(handle.is_valid());
  9791. }
  9792. TEST(BodyReaderTest, Basic) {
  9793. MockStream stream("Hello, World!");
  9794. detail::BodyReader reader;
  9795. reader.stream = &stream;
  9796. reader.content_length = 13;
  9797. char buf[32];
  9798. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9799. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9800. EXPECT_TRUE(reader.eof);
  9801. }
  9802. TEST(BodyReaderTest, NoStream) {
  9803. detail::BodyReader reader;
  9804. char buf[32];
  9805. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9806. EXPECT_EQ(Error::Connection, reader.last_error);
  9807. }
  9808. TEST(BodyReaderTest, Error) {
  9809. MockStream stream("Hello, World!", 5);
  9810. detail::BodyReader reader;
  9811. reader.stream = &stream;
  9812. reader.content_length = 13;
  9813. char buf[32];
  9814. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9815. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9816. EXPECT_EQ(Error::Read, reader.last_error);
  9817. }
  9818. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9819. // Mock-based StreamHandle tests relying on private internals are removed.
  9820. class OpenStreamTest : public ::testing::Test {
  9821. protected:
  9822. void SetUp() override {
  9823. svr_.Get("/hello", [](const Request &, Response &res) {
  9824. res.set_content("Hello World!", "text/plain");
  9825. });
  9826. svr_.Get("/large", [](const Request &, Response &res) {
  9827. res.set_content(std::string(10000, 'X'), "text/plain");
  9828. });
  9829. svr_.Get("/chunked", [](const Request &, Response &res) {
  9830. res.set_chunked_content_provider("text/plain",
  9831. [](size_t offset, DataSink &sink) {
  9832. if (offset < 15) {
  9833. sink.write("chunk", 5);
  9834. return true;
  9835. }
  9836. sink.done();
  9837. return true;
  9838. });
  9839. });
  9840. svr_.Get("/compressible", [](const Request &, Response &res) {
  9841. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9842. DataSink &sink) {
  9843. if (offset < 100 * 1024) {
  9844. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9845. sink.write(chunk.data(), chunk.size());
  9846. return true;
  9847. }
  9848. sink.done();
  9849. return true;
  9850. });
  9851. });
  9852. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9853. [](const Request & /*req*/, Response &res) {
  9854. auto i = new int(0);
  9855. res.set_header("Trailer", "Content-Length, X-Allowed");
  9856. res.set_chunked_content_provider(
  9857. "text/plain",
  9858. [i](size_t /*offset*/, DataSink &sink) {
  9859. switch (*i) {
  9860. case 0: sink.os << "123"; break;
  9861. case 1: sink.os << "456"; break;
  9862. case 2: sink.os << "789"; break;
  9863. case 3: {
  9864. sink.done_with_trailer(
  9865. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9866. } break;
  9867. }
  9868. (*i)++;
  9869. return true;
  9870. },
  9871. [i](bool success) {
  9872. EXPECT_TRUE(success);
  9873. delete i;
  9874. });
  9875. });
  9876. // Echo headers endpoint for header-related tests
  9877. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9878. std::string body;
  9879. for (const auto &h : req.headers) {
  9880. body.append(h.first);
  9881. body.push_back(':');
  9882. body.append(h.second);
  9883. body.push_back('\n');
  9884. }
  9885. res.set_content(body, "text/plain");
  9886. });
  9887. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9888. std::string body;
  9889. for (const auto &h : req.headers) {
  9890. body.append(h.first);
  9891. body.push_back(':');
  9892. body.append(h.second);
  9893. body.push_back('\n');
  9894. }
  9895. res.set_content(body, "text/plain");
  9896. });
  9897. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9898. svr_.wait_until_ready();
  9899. }
  9900. void TearDown() override {
  9901. svr_.stop();
  9902. if (thread_.joinable()) thread_.join();
  9903. }
  9904. Server svr_;
  9905. std::thread thread_;
  9906. };
  9907. TEST_F(OpenStreamTest, Basic) {
  9908. Client cli("127.0.0.1", 8787);
  9909. auto handle = cli.open_stream("GET", "/hello");
  9910. EXPECT_TRUE(handle.is_valid());
  9911. EXPECT_EQ("Hello World!", read_all(handle));
  9912. }
  9913. TEST_F(OpenStreamTest, SmallBuffer) {
  9914. Client cli("127.0.0.1", 8787);
  9915. auto handle = cli.open_stream("GET", "/hello");
  9916. std::string result;
  9917. char buf[4];
  9918. ssize_t n;
  9919. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9920. result.append(buf, static_cast<size_t>(n));
  9921. EXPECT_EQ("Hello World!", result);
  9922. }
  9923. TEST_F(OpenStreamTest, DefaultHeaders) {
  9924. Client cli("127.0.0.1", 8787);
  9925. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9926. {
  9927. auto handle = cli.open_stream("GET", "/echo-headers");
  9928. ASSERT_TRUE(handle.is_valid());
  9929. auto body = read_all(handle);
  9930. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  9931. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  9932. std::string::npos);
  9933. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  9934. }
  9935. // open_stream POST with body and no explicit content_type should NOT add
  9936. // text/plain Content-Type (behavior differs from non-streaming path), but
  9937. // should include Content-Length
  9938. {
  9939. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  9940. ASSERT_TRUE(handle.is_valid());
  9941. auto body = read_all(handle);
  9942. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  9943. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  9944. }
  9945. // open_stream POST with explicit Content-Type should preserve it
  9946. {
  9947. auto handle = cli.open_stream("POST", "/echo-headers", {},
  9948. {{"Content-Type", "application/custom"}},
  9949. "{}", "application/custom");
  9950. ASSERT_TRUE(handle.is_valid());
  9951. auto body = read_all(handle);
  9952. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  9953. }
  9954. // User-specified User-Agent must not be overwritten for stream API
  9955. {
  9956. auto handle = cli.open_stream("GET", "/echo-headers", {},
  9957. {{"User-Agent", "MyAgent/1.2"}});
  9958. ASSERT_TRUE(handle.is_valid());
  9959. auto body = read_all(handle);
  9960. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  9961. }
  9962. }
  9963. TEST_F(OpenStreamTest, Large) {
  9964. Client cli("127.0.0.1", 8787);
  9965. auto handle = cli.open_stream("GET", "/large");
  9966. EXPECT_EQ(10000u, read_all(handle).size());
  9967. }
  9968. TEST_F(OpenStreamTest, ConnectionError) {
  9969. Client cli("127.0.0.1", 9999);
  9970. auto handle = cli.open_stream("GET", "/hello");
  9971. EXPECT_FALSE(handle.is_valid());
  9972. }
  9973. TEST_F(OpenStreamTest, Chunked) {
  9974. Client cli("127.0.0.1", 8787);
  9975. auto handle = cli.open_stream("GET", "/chunked");
  9976. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  9977. "Transfer-Encoding") == "chunked");
  9978. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  9979. }
  9980. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  9981. Client cli("127.0.0.1", 8787);
  9982. auto handle =
  9983. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  9984. ASSERT_TRUE(handle.is_valid());
  9985. // Consume body to allow trailers to be received/parsed
  9986. auto body = read_all(handle);
  9987. // Explicitly parse trailers (ensure trailers are available for assertion)
  9988. handle.parse_trailers_if_needed();
  9989. EXPECT_EQ(std::string("123456789"), body);
  9990. // The response should include a Trailer header declaring both names
  9991. ASSERT_TRUE(handle.response);
  9992. EXPECT_TRUE(handle.response->has_header("Trailer"));
  9993. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  9994. handle.response->get_header_value("Trailer"));
  9995. // Prohibited trailer must not be present
  9996. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  9997. // Allowed trailer should be present
  9998. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  9999. EXPECT_EQ(std::string("yes"),
  10000. handle.response->get_trailer_value("X-Allowed"));
  10001. // Verify trailers are NOT present as regular headers
  10002. EXPECT_EQ(std::string(""),
  10003. handle.response->get_header_value("Content-Length"));
  10004. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10005. }
  10006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10007. TEST_F(OpenStreamTest, Gzip) {
  10008. Client cli("127.0.0.1", 8787);
  10009. auto handle = cli.open_stream("GET", "/compressible", {},
  10010. {{"Accept-Encoding", "gzip"}});
  10011. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10012. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10013. }
  10014. #endif
  10015. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10016. TEST_F(OpenStreamTest, Brotli) {
  10017. Client cli("127.0.0.1", 8787);
  10018. auto handle =
  10019. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10020. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10021. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10022. }
  10023. #endif
  10024. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10025. TEST_F(OpenStreamTest, Zstd) {
  10026. Client cli("127.0.0.1", 8787);
  10027. auto handle = cli.open_stream("GET", "/compressible", {},
  10028. {{"Accept-Encoding", "zstd"}});
  10029. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10030. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10031. }
  10032. #endif
  10033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10034. class SSLOpenStreamTest : public ::testing::Test {
  10035. protected:
  10036. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10037. void SetUp() override {
  10038. svr_.Get("/hello", [](const Request &, Response &res) {
  10039. res.set_content("Hello SSL World!", "text/plain");
  10040. });
  10041. svr_.Get("/chunked", [](const Request &, Response &res) {
  10042. res.set_chunked_content_provider("text/plain",
  10043. [](size_t offset, DataSink &sink) {
  10044. if (offset < 15) {
  10045. sink.write("chunk", 5);
  10046. return true;
  10047. }
  10048. sink.done();
  10049. return true;
  10050. });
  10051. });
  10052. svr_.Post("/echo", [](const Request &req, Response &res) {
  10053. res.set_content(req.body, req.get_header_value("Content-Type"));
  10054. });
  10055. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10056. std::string body = req.body;
  10057. res.set_chunked_content_provider(
  10058. "text/plain", [body](size_t offset, DataSink &sink) {
  10059. if (offset < body.size()) {
  10060. sink.write(body.data() + offset, body.size() - offset);
  10061. }
  10062. sink.done();
  10063. return true;
  10064. });
  10065. });
  10066. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10067. svr_.wait_until_ready();
  10068. }
  10069. void TearDown() override {
  10070. svr_.stop();
  10071. if (thread_.joinable()) thread_.join();
  10072. }
  10073. SSLServer svr_;
  10074. std::thread thread_;
  10075. };
  10076. TEST_F(SSLOpenStreamTest, Basic) {
  10077. SSLClient cli("127.0.0.1", 8788);
  10078. cli.enable_server_certificate_verification(false);
  10079. auto handle = cli.open_stream("GET", "/hello");
  10080. ASSERT_TRUE(handle.is_valid());
  10081. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10082. }
  10083. TEST_F(SSLOpenStreamTest, Chunked) {
  10084. SSLClient cli("127.0.0.1", 8788);
  10085. cli.enable_server_certificate_verification(false);
  10086. auto handle = cli.open_stream("GET", "/chunked");
  10087. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10088. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10089. "Transfer-Encoding") == "chunked");
  10090. auto body = read_all(handle);
  10091. EXPECT_EQ("chunkchunkchunk", body);
  10092. }
  10093. TEST_F(SSLOpenStreamTest, Post) {
  10094. SSLClient cli("127.0.0.1", 8788);
  10095. cli.enable_server_certificate_verification(false);
  10096. auto handle =
  10097. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10098. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10099. EXPECT_EQ(200, handle.response->status);
  10100. auto body = read_all(handle);
  10101. EXPECT_EQ("Hello SSL POST", body);
  10102. }
  10103. TEST_F(SSLOpenStreamTest, PostChunked) {
  10104. SSLClient cli("127.0.0.1", 8788);
  10105. cli.enable_server_certificate_verification(false);
  10106. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10107. "Chunked SSL Data", "text/plain");
  10108. ASSERT_TRUE(handle.is_valid());
  10109. EXPECT_EQ(200, handle.response->status);
  10110. auto body = read_all(handle);
  10111. EXPECT_EQ("Chunked SSL Data", body);
  10112. }
  10113. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10114. //==============================================================================
  10115. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10116. // results for various scenarios.
  10117. //==============================================================================
  10118. TEST(ParityTest, GetVsOpenStream) {
  10119. Server svr;
  10120. const std::string path = "/parity";
  10121. const std::string content = "Parity test content: hello world";
  10122. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10123. res.set_content(content, "text/plain");
  10124. });
  10125. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. });
  10131. svr.wait_until_ready();
  10132. Client cli(HOST, PORT);
  10133. // Non-stream path
  10134. auto r1 = cli.Get(path);
  10135. ASSERT_TRUE(r1);
  10136. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10137. // Stream path
  10138. auto h = cli.open_stream("GET", path);
  10139. ASSERT_TRUE(h.is_valid());
  10140. EXPECT_EQ(r1->body, read_all(h));
  10141. }
  10142. // Helper to compress data with provided compressor type T
  10143. template <typename Compressor>
  10144. static std::string compress_payload_for_parity(const std::string &in) {
  10145. std::string out;
  10146. Compressor compressor;
  10147. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10148. [&](const char *data, size_t n) {
  10149. out.append(data, n);
  10150. return true;
  10151. });
  10152. EXPECT_TRUE(ok);
  10153. return out;
  10154. }
  10155. // Helper function for compression parity tests
  10156. template <typename Compressor>
  10157. static void test_compression_parity(const std::string &original,
  10158. const std::string &path,
  10159. const std::string &encoding) {
  10160. const std::string compressed =
  10161. compress_payload_for_parity<Compressor>(original);
  10162. Server svr;
  10163. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10164. res.set_content(compressed, "application/octet-stream");
  10165. res.set_header("Content-Encoding", encoding);
  10166. });
  10167. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10168. auto se = detail::scope_exit([&] {
  10169. svr.stop();
  10170. t.join();
  10171. ASSERT_FALSE(svr.is_running());
  10172. });
  10173. svr.wait_until_ready();
  10174. Client cli("localhost", 1234);
  10175. // Non-streaming
  10176. {
  10177. auto res = cli.Get(path);
  10178. ASSERT_TRUE(res);
  10179. EXPECT_EQ(StatusCode::OK_200, res->status);
  10180. EXPECT_EQ(original, res->body);
  10181. }
  10182. // Streaming
  10183. {
  10184. auto h = cli.open_stream("GET", path);
  10185. ASSERT_TRUE(h.is_valid());
  10186. EXPECT_EQ(original, read_all(h));
  10187. }
  10188. }
  10189. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10190. TEST(ParityTest, Gzip) {
  10191. test_compression_parity<detail::gzip_compressor>(
  10192. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10193. }
  10194. #endif
  10195. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10196. TEST(ParityTest, Brotli) {
  10197. test_compression_parity<detail::brotli_compressor>(
  10198. "Hello, brotli parity test payload", "/parity-br", "br");
  10199. }
  10200. #endif
  10201. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10202. TEST(ParityTest, Zstd) {
  10203. test_compression_parity<detail::zstd_compressor>(
  10204. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10205. }
  10206. #endif
  10207. //==============================================================================
  10208. // New Stream API Tests
  10209. //==============================================================================
  10210. inline std::string read_body(httplib::stream::Result &result) {
  10211. std::string body;
  10212. while (result.next()) {
  10213. body.append(result.data(), result.size());
  10214. }
  10215. return body;
  10216. }
  10217. TEST(ClientConnectionTest, Basic) {
  10218. httplib::ClientConnection conn;
  10219. EXPECT_FALSE(conn.is_open());
  10220. conn.sock = 1;
  10221. EXPECT_TRUE(conn.is_open());
  10222. httplib::ClientConnection conn2(std::move(conn));
  10223. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10224. conn2.sock = INVALID_SOCKET;
  10225. }
  10226. // Unified test server for all stream::* tests
  10227. class StreamApiTest : public ::testing::Test {
  10228. protected:
  10229. void SetUp() override {
  10230. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10231. res.set_content("Hello World!", "text/plain");
  10232. });
  10233. svr_.Get("/echo-params",
  10234. [](const httplib::Request &req, httplib::Response &res) {
  10235. std::string r;
  10236. for (const auto &p : req.params) {
  10237. if (!r.empty()) r += "&";
  10238. r += p.first + "=" + p.second;
  10239. }
  10240. res.set_content(r, "text/plain");
  10241. });
  10242. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10243. res.set_content(req.body, req.get_header_value("Content-Type"));
  10244. });
  10245. svr_.Post("/echo-headers",
  10246. [](const httplib::Request &req, httplib::Response &res) {
  10247. std::string r;
  10248. for (const auto &h : req.headers)
  10249. r += h.first + ": " + h.second + "\n";
  10250. res.set_content(r, "text/plain");
  10251. });
  10252. svr_.Post("/echo-params",
  10253. [](const httplib::Request &req, httplib::Response &res) {
  10254. std::string r = "params:";
  10255. for (const auto &p : req.params)
  10256. r += p.first + "=" + p.second + ";";
  10257. res.set_content(r + " body:" + req.body, "text/plain");
  10258. });
  10259. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10260. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10261. });
  10262. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10263. res.set_content("PUT:" + req.body, "text/plain");
  10264. });
  10265. svr_.Patch("/echo",
  10266. [](const httplib::Request &req, httplib::Response &res) {
  10267. res.set_content("PATCH:" + req.body, "text/plain");
  10268. });
  10269. svr_.Delete(
  10270. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10271. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10272. "text/plain");
  10273. });
  10274. svr_.Get("/head-test",
  10275. [](const httplib::Request &, httplib::Response &res) {
  10276. res.set_content("body for HEAD", "text/plain");
  10277. });
  10278. svr_.Options("/options",
  10279. [](const httplib::Request &, httplib::Response &res) {
  10280. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10281. });
  10282. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10283. svr_.wait_until_ready();
  10284. }
  10285. void TearDown() override {
  10286. svr_.stop();
  10287. if (thread_.joinable()) thread_.join();
  10288. }
  10289. httplib::Server svr_;
  10290. std::thread thread_;
  10291. };
  10292. // stream::Get tests
  10293. TEST_F(StreamApiTest, GetBasic) {
  10294. httplib::Client cli("localhost", 8790);
  10295. auto result = httplib::stream::Get(cli, "/hello");
  10296. ASSERT_TRUE(result.is_valid());
  10297. EXPECT_EQ(200, result.status());
  10298. EXPECT_EQ("Hello World!", read_body(result));
  10299. }
  10300. TEST_F(StreamApiTest, GetWithParams) {
  10301. httplib::Client cli("localhost", 8790);
  10302. httplib::Params params{{"foo", "bar"}};
  10303. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10304. ASSERT_TRUE(result.is_valid());
  10305. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10306. }
  10307. TEST_F(StreamApiTest, GetConnectionError) {
  10308. httplib::Client cli("localhost", 9999);
  10309. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10310. }
  10311. TEST_F(StreamApiTest, Get404) {
  10312. httplib::Client cli("localhost", 8790);
  10313. auto result = httplib::stream::Get(cli, "/nonexistent");
  10314. EXPECT_TRUE(result.is_valid());
  10315. EXPECT_EQ(404, result.status());
  10316. }
  10317. // stream::Post tests
  10318. TEST_F(StreamApiTest, PostBasic) {
  10319. httplib::Client cli("localhost", 8790);
  10320. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10321. "application/json");
  10322. ASSERT_TRUE(result.is_valid());
  10323. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10324. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10325. }
  10326. TEST_F(StreamApiTest, PostWithHeaders) {
  10327. httplib::Client cli("localhost", 8790);
  10328. httplib::Headers headers{{"X-Custom", "value"}};
  10329. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10330. "text/plain");
  10331. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10332. }
  10333. TEST_F(StreamApiTest, PostWithParams) {
  10334. httplib::Client cli("localhost", 8790);
  10335. httplib::Params params{{"k", "v"}};
  10336. auto result =
  10337. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10338. auto body = read_body(result);
  10339. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10340. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10341. }
  10342. TEST_F(StreamApiTest, PostLarge) {
  10343. httplib::Client cli("localhost", 8790);
  10344. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10345. size_t total = 0;
  10346. while (result.next()) {
  10347. total += result.size();
  10348. }
  10349. EXPECT_EQ(100u * 1024u, total);
  10350. }
  10351. // stream::Put/Patch tests
  10352. TEST_F(StreamApiTest, PutAndPatch) {
  10353. httplib::Client cli("localhost", 8790);
  10354. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10355. EXPECT_EQ("PUT:test", read_body(put));
  10356. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10357. EXPECT_EQ("PATCH:test", read_body(patch));
  10358. }
  10359. // stream::Delete tests
  10360. TEST_F(StreamApiTest, Delete) {
  10361. httplib::Client cli("localhost", 8790);
  10362. auto del1 = httplib::stream::Delete(cli, "/resource");
  10363. EXPECT_EQ("Deleted", read_body(del1));
  10364. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10365. EXPECT_EQ("Deleted:data", read_body(del2));
  10366. }
  10367. // stream::Head/Options tests
  10368. TEST_F(StreamApiTest, HeadAndOptions) {
  10369. httplib::Client cli("localhost", 8790);
  10370. auto head = httplib::stream::Head(cli, "/head-test");
  10371. EXPECT_TRUE(head.is_valid());
  10372. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10373. auto opts = httplib::stream::Options(cli, "/options");
  10374. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10375. }
  10376. // SSL stream::* tests
  10377. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10378. class SSLStreamApiTest : public ::testing::Test {
  10379. protected:
  10380. void SetUp() override {
  10381. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10382. res.set_content("Hello SSL!", "text/plain");
  10383. });
  10384. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10385. res.set_content(req.body, "text/plain");
  10386. });
  10387. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10388. svr_.wait_until_ready();
  10389. }
  10390. void TearDown() override {
  10391. svr_.stop();
  10392. if (thread_.joinable()) thread_.join();
  10393. }
  10394. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10395. std::thread thread_;
  10396. };
  10397. TEST_F(SSLStreamApiTest, GetAndPost) {
  10398. httplib::SSLClient cli("127.0.0.1", 8803);
  10399. cli.enable_server_certificate_verification(false);
  10400. auto get = httplib::stream::Get(cli, "/hello");
  10401. EXPECT_EQ("Hello SSL!", read_body(get));
  10402. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10403. EXPECT_EQ("test", read_body(post));
  10404. }
  10405. #endif