test.cc 344 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <atomic>
  13. #include <chrono>
  14. #include <cstdio>
  15. #include <fstream>
  16. #include <future>
  17. #include <limits>
  18. #include <memory>
  19. #include <sstream>
  20. #include <stdexcept>
  21. #include <thread>
  22. #include <type_traits>
  23. #include <vector>
  24. #define SERVER_CERT_FILE "./cert.pem"
  25. #define SERVER_CERT2_FILE "./cert2.pem"
  26. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  27. #define CA_CERT_FILE "./ca-bundle.crt"
  28. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  29. #define CLIENT_CA_CERT_DIR "."
  30. #define CLIENT_CERT_FILE "./client.cert.pem"
  31. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  32. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  33. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  35. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  36. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  38. using namespace std;
  39. using namespace httplib;
  40. const char *HOST = "localhost";
  41. const int PORT = 1234;
  42. const string LONG_QUERY_VALUE = string(25000, '@');
  43. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  44. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  45. const string TOO_LONG_QUERY_URL =
  46. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  47. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  48. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  49. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  50. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  51. return file.name == key;
  52. });
  53. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  54. return *it;
  55. #else
  56. if (it != items.end()) { return *it; }
  57. throw std::runtime_error("invalid multipart form data name error");
  58. #endif
  59. }
  60. static void read_file(const std::string &path, std::string &out) {
  61. std::ifstream fs(path, std::ios_base::binary);
  62. if (!fs) throw std::runtime_error("File not found: " + path);
  63. fs.seekg(0, std::ios_base::end);
  64. auto size = fs.tellg();
  65. fs.seekg(0);
  66. out.resize(static_cast<size_t>(size));
  67. fs.read(&out[0], static_cast<std::streamsize>(size));
  68. }
  69. class UnixSocketTest : public ::testing::Test {
  70. protected:
  71. void TearDown() override { std::remove(pathname_.c_str()); }
  72. void client_GET(const std::string &addr) {
  73. httplib::Client cli{addr};
  74. cli.set_address_family(AF_UNIX);
  75. ASSERT_TRUE(cli.is_valid());
  76. const auto &result = cli.Get(pattern_);
  77. ASSERT_TRUE(result) << "error: " << result.error();
  78. const auto &resp = result.value();
  79. EXPECT_EQ(resp.status, StatusCode::OK_200);
  80. EXPECT_EQ(resp.body, content_);
  81. }
  82. const std::string pathname_{"./httplib-server.sock"};
  83. const std::string pattern_{"/hi"};
  84. const std::string content_{"Hello World!"};
  85. };
  86. TEST_F(UnixSocketTest, pathname) {
  87. httplib::Server svr;
  88. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  89. res.set_content(content_, "text/plain");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. }
  103. #if defined(__linux__) || \
  104. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  105. TEST_F(UnixSocketTest, PeerPid) {
  106. httplib::Server svr;
  107. std::string remote_port_val;
  108. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  109. res.set_content(content_, "text/plain");
  110. remote_port_val = req.get_header_value("REMOTE_PORT");
  111. });
  112. std::thread t{[&] {
  113. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  114. }};
  115. auto se = detail::scope_exit([&] {
  116. svr.stop();
  117. t.join();
  118. ASSERT_FALSE(svr.is_running());
  119. });
  120. svr.wait_until_ready();
  121. ASSERT_TRUE(svr.is_running());
  122. client_GET(pathname_);
  123. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  124. }
  125. #endif
  126. #ifdef __linux__
  127. TEST_F(UnixSocketTest, abstract) {
  128. constexpr char svr_path[]{"\x00httplib-server.sock"};
  129. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  130. httplib::Server svr;
  131. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  132. res.set_content(content_, "text/plain");
  133. });
  134. std::thread t{[&] {
  135. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  136. }};
  137. auto se = detail::scope_exit([&] {
  138. svr.stop();
  139. t.join();
  140. ASSERT_FALSE(svr.is_running());
  141. });
  142. svr.wait_until_ready();
  143. ASSERT_TRUE(svr.is_running());
  144. client_GET(abstract_addr);
  145. }
  146. #endif
  147. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  148. httplib::Server svr;
  149. std::string received_host_header;
  150. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  151. // Capture the Host header sent by the client
  152. auto host_iter = req.headers.find("Host");
  153. if (host_iter != req.headers.end()) {
  154. received_host_header = host_iter->second;
  155. }
  156. res.set_content(content_, "text/plain");
  157. });
  158. std::thread t{[&] {
  159. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  160. }};
  161. auto se = detail::scope_exit([&] {
  162. svr.stop();
  163. t.join();
  164. ASSERT_FALSE(svr.is_running());
  165. });
  166. svr.wait_until_ready();
  167. ASSERT_TRUE(svr.is_running());
  168. // Test that Host header is automatically set to "localhost" for Unix socket
  169. // connections
  170. httplib::Client cli{pathname_};
  171. cli.set_address_family(AF_UNIX);
  172. ASSERT_TRUE(cli.is_valid());
  173. const auto &result = cli.Get(pattern_);
  174. ASSERT_TRUE(result) << "error: " << result.error();
  175. const auto &resp = result.value();
  176. EXPECT_EQ(resp.status, StatusCode::OK_200);
  177. EXPECT_EQ(resp.body, content_);
  178. // Verify that Host header was automatically set to "localhost"
  179. EXPECT_EQ(received_host_header, "localhost");
  180. }
  181. #ifndef _WIN32
  182. TEST(SocketStream, wait_writable_UNIX) {
  183. int fds[2];
  184. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  185. const auto asSocketStream = [&](socket_t fd,
  186. std::function<bool(Stream &)> func) {
  187. return detail::process_client_socket(
  188. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  189. };
  190. asSocketStream(fds[0], [&](Stream &s0) {
  191. EXPECT_EQ(s0.socket(), fds[0]);
  192. EXPECT_TRUE(s0.wait_writable());
  193. EXPECT_EQ(0, close(fds[1]));
  194. EXPECT_FALSE(s0.wait_writable());
  195. return true;
  196. });
  197. EXPECT_EQ(0, close(fds[0]));
  198. }
  199. TEST(SocketStream, wait_writable_INET) {
  200. sockaddr_in addr;
  201. memset(&addr, 0, sizeof(addr));
  202. addr.sin_family = AF_INET;
  203. addr.sin_port = htons(PORT + 1);
  204. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  205. int disconnected_svr_sock = -1;
  206. std::thread svr{[&] {
  207. const int s = socket(AF_INET, SOCK_STREAM, 0);
  208. ASSERT_LE(0, s);
  209. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  210. ASSERT_EQ(0, listen(s, 1));
  211. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  212. ASSERT_EQ(0, close(s));
  213. }};
  214. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  215. std::thread cli{[&] {
  216. const int s = socket(AF_INET, SOCK_STREAM, 0);
  217. ASSERT_LE(0, s);
  218. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  219. ASSERT_EQ(0, close(s));
  220. }};
  221. cli.join();
  222. svr.join();
  223. ASSERT_NE(disconnected_svr_sock, -1);
  224. const auto asSocketStream = [&](socket_t fd,
  225. std::function<bool(Stream &)> func) {
  226. return detail::process_client_socket(
  227. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  228. };
  229. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  230. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  231. EXPECT_FALSE(ss.wait_writable());
  232. return true;
  233. });
  234. ASSERT_EQ(0, close(disconnected_svr_sock));
  235. }
  236. #endif // #ifndef _WIN32
  237. TEST(ClientTest, MoveConstructible) {
  238. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  239. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  240. }
  241. TEST(ClientTest, MoveAssignable) {
  242. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  243. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  244. }
  245. #ifdef _WIN32
  246. TEST(StartupTest, WSAStartup) {
  247. WSADATA wsaData;
  248. int ret = WSAStartup(0x0002, &wsaData);
  249. ASSERT_EQ(0, ret);
  250. }
  251. #endif
  252. TEST(DecodePathTest, PercentCharacter) {
  253. EXPECT_EQ(
  254. decode_path_component(
  255. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  256. u8"descrip=Gastos áéíóúñÑ 6");
  257. }
  258. TEST(DecodePathTest, PercentCharacterNUL) {
  259. string expected;
  260. expected.push_back('x');
  261. expected.push_back('\0');
  262. expected.push_back('x');
  263. EXPECT_EQ(decode_path_component("x%00x"), expected);
  264. }
  265. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  266. string unescapedCharacters = "-_.!~*'()";
  267. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  268. }
  269. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  270. string reservedCharacters = ";,/?:@&=+$";
  271. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  272. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  273. }
  274. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  275. string chineseCharacters = u8"中国語";
  276. string russianCharacters = u8"дом";
  277. string brazilianCharacters = u8"óculos";
  278. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  279. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  280. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  281. "%D0%B4%D0%BE%D0%BC");
  282. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  283. }
  284. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  285. string unescapedCharacters = "-_.!~*'()";
  286. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  287. }
  288. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  289. string reservedCharacters = ";,/?:@&=+$";
  290. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  291. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  292. }
  293. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  294. string chineseCharacters = u8"中国語";
  295. string russianCharacters = u8"дом";
  296. string brazilianCharacters = u8"óculos";
  297. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  298. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  299. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  300. "%D0%B4%D0%BE%D0%BC");
  301. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  302. }
  303. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  304. // Issue #2082 use case: encoding path component with ampersand
  305. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  306. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  307. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  308. }
  309. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  310. string unescapedCharacters = "-_.!~*'()";
  311. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  312. }
  313. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  314. string reservedCharacters = ";,/?:@&=+$#";
  315. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  316. }
  317. TEST(EncodeUriTest, TestUTF8Characters) {
  318. string chineseCharacters = u8"中国語";
  319. string russianCharacters = u8"дом";
  320. string brazilianCharacters = u8"óculos";
  321. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  322. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  323. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  324. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  325. }
  326. TEST(EncodeUriTest, TestCompleteUri) {
  327. string uri =
  328. "https://example.com/path/to/resource?query=value&param=test#fragment";
  329. EXPECT_EQ(
  330. httplib::encode_uri(uri),
  331. "https://example.com/path/to/resource?query=value&param=test#fragment");
  332. }
  333. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  334. string uri =
  335. "https://example.com/path with spaces/file name.html?q=hello world";
  336. EXPECT_EQ(httplib::encode_uri(uri),
  337. "https://example.com/path%20with%20spaces/"
  338. "file%20name.html?q=hello%20world");
  339. }
  340. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  341. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  342. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  343. }
  344. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  345. string unescapedCharacters = "-_.!~*'()";
  346. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  347. }
  348. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  349. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  350. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  351. string encodedBrazilian = "%C3%B3culos";
  352. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  353. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  354. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  355. }
  356. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  357. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  358. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  359. "Piri Tommy Villiers - on & on");
  360. }
  361. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  362. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  363. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  364. }
  365. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  366. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  367. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  368. }
  369. TEST(DecodeUriTest, TestUTF8Characters) {
  370. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  371. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  372. string encodedBrazilian = "%C3%B3culos";
  373. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  374. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  375. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  376. }
  377. TEST(DecodeUriTest, TestCompleteUri) {
  378. string encodedUri = "https://example.com/path%20with%20spaces/"
  379. "file%20name.html?q=hello%20world";
  380. EXPECT_EQ(
  381. httplib::decode_uri(encodedUri),
  382. "https://example.com/path with spaces/file name.html?q=hello world");
  383. }
  384. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  385. string original =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. string encoded = httplib::encode_uri(original);
  388. string decoded = httplib::decode_uri(encoded);
  389. EXPECT_EQ(decoded, original);
  390. }
  391. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  392. string original = "Piri Tommy Villiers - on & on";
  393. string encoded = httplib::encode_uri_component(original);
  394. string decoded = httplib::decode_uri_component(encoded);
  395. EXPECT_EQ(decoded, original);
  396. }
  397. TEST(TrimTests, TrimStringTests) {
  398. EXPECT_EQ("abc", detail::trim_copy("abc"));
  399. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  400. EXPECT_TRUE(detail::trim_copy("").empty());
  401. }
  402. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  403. // Simple case without quality values
  404. std::vector<std::string> result1;
  405. EXPECT_TRUE(detail::parse_accept_header(
  406. "text/html,application/json,text/plain", result1));
  407. EXPECT_EQ(result1.size(), 3U);
  408. EXPECT_EQ(result1[0], "text/html");
  409. EXPECT_EQ(result1[1], "application/json");
  410. EXPECT_EQ(result1[2], "text/plain");
  411. // With quality values
  412. std::vector<std::string> result2;
  413. EXPECT_TRUE(detail::parse_accept_header(
  414. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  415. EXPECT_EQ(result2.size(), 3U);
  416. EXPECT_EQ(result2[0], "application/json"); // highest q value
  417. EXPECT_EQ(result2[1], "text/html");
  418. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  419. }
  420. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  421. // Mixed with and without quality values
  422. std::vector<std::string> result;
  423. EXPECT_TRUE(detail::parse_accept_header(
  424. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  425. EXPECT_EQ(result.size(), 3U);
  426. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  427. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  428. EXPECT_EQ(result[2], "application/json"); // q=0.5
  429. }
  430. TEST(ParseAcceptHeaderTest, EdgeCases) {
  431. // Empty header
  432. std::vector<std::string> empty_result;
  433. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  434. EXPECT_TRUE(empty_result.empty());
  435. // Single type
  436. std::vector<std::string> single_result;
  437. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  438. EXPECT_EQ(single_result.size(), 1U);
  439. EXPECT_EQ(single_result[0], "application/json");
  440. // Wildcard types
  441. std::vector<std::string> wildcard_result;
  442. EXPECT_TRUE(detail::parse_accept_header(
  443. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  444. EXPECT_EQ(wildcard_result.size(), 3U);
  445. EXPECT_EQ(wildcard_result[0], "application/json");
  446. EXPECT_EQ(wildcard_result[1], "text/*");
  447. EXPECT_EQ(wildcard_result[2], "*/*");
  448. }
  449. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  450. // Common browser Accept header
  451. std::vector<std::string> browser_result;
  452. EXPECT_TRUE(
  453. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  454. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  455. browser_result));
  456. EXPECT_EQ(browser_result.size(), 6U);
  457. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  458. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  459. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  460. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  461. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  462. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  463. // API client header
  464. std::vector<std::string> api_result;
  465. EXPECT_TRUE(detail::parse_accept_header(
  466. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  467. api_result));
  468. EXPECT_EQ(api_result.size(), 3U);
  469. EXPECT_EQ(api_result[0], "application/json");
  470. EXPECT_EQ(api_result[1], "application/xml");
  471. EXPECT_EQ(api_result[2], "text/plain");
  472. }
  473. TEST(ParseAcceptHeaderTest, SpecialCases) {
  474. // Quality value with 3 decimal places
  475. std::vector<std::string> decimal_result;
  476. EXPECT_TRUE(detail::parse_accept_header(
  477. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  478. EXPECT_EQ(decimal_result.size(), 2U);
  479. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  480. EXPECT_EQ(decimal_result[1], "text/html");
  481. // Zero quality (should still be included but with lowest priority)
  482. std::vector<std::string> zero_q_result;
  483. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  484. zero_q_result));
  485. EXPECT_EQ(zero_q_result.size(), 2U);
  486. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  487. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  488. // No spaces around commas
  489. std::vector<std::string> no_space_result;
  490. EXPECT_TRUE(detail::parse_accept_header(
  491. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  492. no_space_result));
  493. EXPECT_EQ(no_space_result.size(), 3U);
  494. EXPECT_EQ(no_space_result[0], "text/html");
  495. EXPECT_EQ(no_space_result[1], "application/json");
  496. EXPECT_EQ(no_space_result[2], "text/plain");
  497. }
  498. TEST(ParseAcceptHeaderTest, InvalidCases) {
  499. std::vector<std::string> result;
  500. // Invalid quality value (> 1.0)
  501. EXPECT_FALSE(
  502. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  503. // Invalid quality value (< 0.0)
  504. EXPECT_FALSE(
  505. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  506. // Invalid quality value (not a number)
  507. EXPECT_FALSE(detail::parse_accept_header(
  508. "text/html;q=invalid,application/json", result));
  509. // Empty quality value
  510. EXPECT_FALSE(
  511. detail::parse_accept_header("text/html;q=,application/json", result));
  512. // Invalid media type format (no slash and not wildcard)
  513. EXPECT_FALSE(
  514. detail::parse_accept_header("invalidtype,application/json", result));
  515. // Empty media type
  516. result.clear();
  517. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  518. // Only commas
  519. result.clear();
  520. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  521. // Valid cases should still work
  522. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  523. EXPECT_EQ(result.size(), 1U);
  524. EXPECT_EQ(result[0], "*/*");
  525. EXPECT_TRUE(detail::parse_accept_header("*", result));
  526. EXPECT_EQ(result.size(), 1U);
  527. EXPECT_EQ(result[0], "*");
  528. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  529. EXPECT_EQ(result.size(), 1U);
  530. EXPECT_EQ(result[0], "text/*");
  531. }
  532. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  533. Server svr;
  534. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  535. EXPECT_EQ(req.accept_content_types.size(), 3U);
  536. EXPECT_EQ(req.accept_content_types[0], "application/json");
  537. EXPECT_EQ(req.accept_content_types[1], "text/html");
  538. EXPECT_EQ(req.accept_content_types[2], "*/*");
  539. res.set_content("ok", "text/plain");
  540. });
  541. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  542. EXPECT_TRUE(false);
  543. res.set_content("bad request", "text/plain");
  544. });
  545. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  546. auto se = detail::scope_exit([&] {
  547. svr.stop();
  548. listen_thread.join();
  549. ASSERT_FALSE(svr.is_running());
  550. });
  551. svr.wait_until_ready();
  552. Client cli("localhost", PORT);
  553. {
  554. auto res =
  555. cli.Get("/accept_ok",
  556. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  557. ASSERT_TRUE(res);
  558. EXPECT_EQ(StatusCode::OK_200, res->status);
  559. }
  560. {
  561. auto res = cli.Get("/accept_bad_request",
  562. {{"Accept", "text/html;q=abc,application/json"}});
  563. ASSERT_TRUE(res);
  564. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  565. }
  566. }
  567. TEST(DivideTest, DivideStringTests) {
  568. auto divide = [](const std::string &str, char d) {
  569. std::string lhs;
  570. std::string rhs;
  571. detail::divide(str, d,
  572. [&](const char *lhs_data, std::size_t lhs_size,
  573. const char *rhs_data, std::size_t rhs_size) {
  574. lhs.assign(lhs_data, lhs_size);
  575. rhs.assign(rhs_data, rhs_size);
  576. });
  577. return std::make_pair(std::move(lhs), std::move(rhs));
  578. };
  579. {
  580. const auto res = divide("", '=');
  581. EXPECT_EQ(res.first, "");
  582. EXPECT_EQ(res.second, "");
  583. }
  584. {
  585. const auto res = divide("=", '=');
  586. EXPECT_EQ(res.first, "");
  587. EXPECT_EQ(res.second, "");
  588. }
  589. {
  590. const auto res = divide(" ", '=');
  591. EXPECT_EQ(res.first, " ");
  592. EXPECT_EQ(res.second, "");
  593. }
  594. {
  595. const auto res = divide("a", '=');
  596. EXPECT_EQ(res.first, "a");
  597. EXPECT_EQ(res.second, "");
  598. }
  599. {
  600. const auto res = divide("a=", '=');
  601. EXPECT_EQ(res.first, "a");
  602. EXPECT_EQ(res.second, "");
  603. }
  604. {
  605. const auto res = divide("=b", '=');
  606. EXPECT_EQ(res.first, "");
  607. EXPECT_EQ(res.second, "b");
  608. }
  609. {
  610. const auto res = divide("a=b", '=');
  611. EXPECT_EQ(res.first, "a");
  612. EXPECT_EQ(res.second, "b");
  613. }
  614. {
  615. const auto res = divide("a=b=", '=');
  616. EXPECT_EQ(res.first, "a");
  617. EXPECT_EQ(res.second, "b=");
  618. }
  619. {
  620. const auto res = divide("a=b=c", '=');
  621. EXPECT_EQ(res.first, "a");
  622. EXPECT_EQ(res.second, "b=c");
  623. }
  624. }
  625. TEST(SplitTest, ParseQueryString) {
  626. string s = "key1=val1&key2=val2&key3=val3";
  627. Params dic;
  628. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  629. [&](const char *b, const char *e) {
  630. string key, val;
  631. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  632. if (key.empty()) {
  633. key.assign(b2, e2);
  634. } else {
  635. val.assign(b2, e2);
  636. }
  637. });
  638. dic.emplace(key, val);
  639. });
  640. EXPECT_EQ("val1", dic.find("key1")->second);
  641. EXPECT_EQ("val2", dic.find("key2")->second);
  642. EXPECT_EQ("val3", dic.find("key3")->second);
  643. }
  644. TEST(SplitTest, ParseInvalidQueryTests) {
  645. {
  646. string s = " ";
  647. Params dict;
  648. detail::parse_query_text(s, dict);
  649. EXPECT_TRUE(dict.empty());
  650. }
  651. {
  652. string s = " = =";
  653. Params dict;
  654. detail::parse_query_text(s, dict);
  655. EXPECT_TRUE(dict.empty());
  656. }
  657. }
  658. TEST(ParseQueryTest, ParseQueryString) {
  659. {
  660. std::string s = "key1=val1&key2=val2&key3=val3";
  661. Params dic;
  662. detail::parse_query_text(s, dic);
  663. EXPECT_EQ("val1", dic.find("key1")->second);
  664. EXPECT_EQ("val2", dic.find("key2")->second);
  665. EXPECT_EQ("val3", dic.find("key3")->second);
  666. }
  667. {
  668. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  669. Params dic;
  670. detail::parse_query_text(s, dic);
  671. EXPECT_EQ("", dic.find("key1")->second);
  672. EXPECT_EQ("val1", dic.find("key2")->second);
  673. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  674. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  675. }
  676. }
  677. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  678. Params dic;
  679. EXPECT_EQ(detail::params_to_query_str(dic), "");
  680. dic.emplace("key1", "val1");
  681. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  682. dic.emplace("key2", "val2");
  683. dic.emplace("key3", "val3");
  684. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  685. }
  686. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  687. string content_type = "multipart/form-data; boundary=something";
  688. string boundary;
  689. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  690. EXPECT_TRUE(ret);
  691. EXPECT_EQ(boundary, "something");
  692. }
  693. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  694. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  695. string boundary;
  696. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  697. EXPECT_TRUE(ret);
  698. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  699. }
  700. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  701. string content_type =
  702. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  703. string boundary;
  704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  705. EXPECT_TRUE(ret);
  706. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  707. }
  708. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  709. string content_type =
  710. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  711. string boundary;
  712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  713. EXPECT_TRUE(ret);
  714. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  715. }
  716. TEST(GetHeaderValueTest, DefaultValue) {
  717. Headers headers = {{"Dummy", "Dummy"}};
  718. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  719. EXPECT_STREQ("text/plain", val);
  720. }
  721. TEST(GetHeaderValueTest, DefaultValueInt) {
  722. Headers headers = {{"Dummy", "Dummy"}};
  723. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  724. EXPECT_EQ(100ull, val);
  725. }
  726. TEST(GetHeaderValueTest, RegularValue) {
  727. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  728. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  729. EXPECT_STREQ("text/html", val);
  730. }
  731. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  732. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  733. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  734. EXPECT_STREQ("text/html", val);
  735. }
  736. TEST(GetHeaderValueTest, SetContent) {
  737. Response res;
  738. res.set_content("html", "text/html");
  739. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  740. res.set_content("text", "text/plain");
  741. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  742. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  743. }
  744. TEST(GetHeaderValueTest, RegularValueInt) {
  745. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  746. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  747. EXPECT_EQ(100ull, val);
  748. }
  749. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  750. Headers headers = {{"Content-Length", "x"}};
  751. auto is_invalid_value = false;
  752. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  753. is_invalid_value);
  754. EXPECT_EQ(0ull, val);
  755. EXPECT_TRUE(is_invalid_value);
  756. }
  757. TEST(GetHeaderValueTest, Range) {
  758. {
  759. Headers headers = {make_range_header({{1, -1}})};
  760. auto val = detail::get_header_value(headers, "Range", 0, 0);
  761. EXPECT_STREQ("bytes=1-", val);
  762. }
  763. {
  764. Headers headers = {make_range_header({{-1, 1}})};
  765. auto val = detail::get_header_value(headers, "Range", 0, 0);
  766. EXPECT_STREQ("bytes=-1", val);
  767. }
  768. {
  769. Headers headers = {make_range_header({{1, 10}})};
  770. auto val = detail::get_header_value(headers, "Range", 0, 0);
  771. EXPECT_STREQ("bytes=1-10", val);
  772. }
  773. {
  774. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  775. auto val = detail::get_header_value(headers, "Range", 0, 0);
  776. EXPECT_STREQ("bytes=1-10, 100-", val);
  777. }
  778. {
  779. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  780. auto val = detail::get_header_value(headers, "Range", 0, 0);
  781. EXPECT_STREQ("bytes=1-10, 100-200", val);
  782. }
  783. {
  784. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  785. auto val = detail::get_header_value(headers, "Range", 0, 0);
  786. EXPECT_STREQ("bytes=0-0, -1", val);
  787. }
  788. }
  789. TEST(ParseHeaderValueTest, Range) {
  790. {
  791. Ranges ranges;
  792. auto ret = detail::parse_range_header("bytes=1-", ranges);
  793. EXPECT_TRUE(ret);
  794. EXPECT_EQ(1u, ranges.size());
  795. EXPECT_EQ(1u, ranges[0].first);
  796. EXPECT_EQ(-1, ranges[0].second);
  797. }
  798. {
  799. Ranges ranges;
  800. auto ret = detail::parse_range_header("bytes=-1", ranges);
  801. EXPECT_TRUE(ret);
  802. EXPECT_EQ(1u, ranges.size());
  803. EXPECT_EQ(-1, ranges[0].first);
  804. EXPECT_EQ(1u, ranges[0].second);
  805. }
  806. {
  807. Ranges ranges;
  808. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  809. EXPECT_TRUE(ret);
  810. EXPECT_EQ(1u, ranges.size());
  811. EXPECT_EQ(1u, ranges[0].first);
  812. EXPECT_EQ(10u, ranges[0].second);
  813. }
  814. {
  815. Ranges ranges;
  816. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  817. EXPECT_FALSE(ret);
  818. }
  819. {
  820. Ranges ranges;
  821. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  822. EXPECT_TRUE(ret);
  823. EXPECT_EQ(2u, ranges.size());
  824. EXPECT_EQ(1u, ranges[0].first);
  825. EXPECT_EQ(10u, ranges[0].second);
  826. EXPECT_EQ(100u, ranges[1].first);
  827. EXPECT_EQ(-1, ranges[1].second);
  828. }
  829. {
  830. Ranges ranges;
  831. auto ret =
  832. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  833. EXPECT_TRUE(ret);
  834. EXPECT_EQ(3u, ranges.size());
  835. EXPECT_EQ(1u, ranges[0].first);
  836. EXPECT_EQ(10u, ranges[0].second);
  837. EXPECT_EQ(100u, ranges[1].first);
  838. EXPECT_EQ(200u, ranges[1].second);
  839. EXPECT_EQ(300u, ranges[2].first);
  840. EXPECT_EQ(400u, ranges[2].second);
  841. }
  842. {
  843. Ranges ranges;
  844. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  845. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  846. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  847. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  848. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  849. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  850. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  851. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  852. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  853. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  854. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  855. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  856. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  857. EXPECT_TRUE(ranges.empty());
  858. }
  859. }
  860. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  861. Request req;
  862. req.set_header("Accept-Encoding", "gzip");
  863. Response res;
  864. res.set_header("Content-Type", "text/plain");
  865. auto ret = detail::encoding_type(req, res);
  866. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  867. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  868. #else
  869. EXPECT_TRUE(ret == detail::EncodingType::None);
  870. #endif
  871. }
  872. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  873. Request req;
  874. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  875. Response res;
  876. res.set_header("Content-Type", "text/plain");
  877. auto ret = detail::encoding_type(req, res);
  878. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  879. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  880. #elif CPPHTTPLIB_ZLIB_SUPPORT
  881. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  882. #elif CPPHTTPLIB_ZSTD_SUPPORT
  883. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  884. #else
  885. EXPECT_TRUE(ret == detail::EncodingType::None);
  886. #endif
  887. }
  888. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  889. Request req;
  890. req.set_header("Accept-Encoding",
  891. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  892. Response res;
  893. res.set_header("Content-Type", "text/plain");
  894. auto ret = detail::encoding_type(req, res);
  895. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  896. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  897. #elif CPPHTTPLIB_ZLIB_SUPPORT
  898. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  899. #elif CPPHTTPLIB_ZSTD_SUPPORT
  900. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  901. #else
  902. EXPECT_TRUE(ret == detail::EncodingType::None);
  903. #endif
  904. }
  905. TEST(BufferStreamTest, read) {
  906. detail::BufferStream strm1;
  907. Stream &strm = strm1;
  908. EXPECT_EQ(5, strm.write("hello"));
  909. char buf[512];
  910. EXPECT_EQ(2, strm.read(buf, 2));
  911. EXPECT_EQ('h', buf[0]);
  912. EXPECT_EQ('e', buf[1]);
  913. EXPECT_EQ(2, strm.read(buf, 2));
  914. EXPECT_EQ('l', buf[0]);
  915. EXPECT_EQ('l', buf[1]);
  916. EXPECT_EQ(1, strm.read(buf, 1));
  917. EXPECT_EQ('o', buf[0]);
  918. EXPECT_EQ(0, strm.read(buf, 1));
  919. }
  920. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  921. auto host = "www.httpwatch.com";
  922. auto ip = hosted_at(host);
  923. EXPECT_EQ("23.96.13.243", ip);
  924. std::vector<std::string> addrs;
  925. hosted_at(host, addrs);
  926. EXPECT_EQ(1u, addrs.size());
  927. }
  928. #if 0 // It depends on each test environment...
  929. TEST(HostnameToIPConversionTest, YouTube_Online) {
  930. auto host = "www.youtube.com";
  931. std::vector<std::string> addrs;
  932. hosted_at(host, addrs);
  933. EXPECT_EQ(20u, addrs.size());
  934. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  935. EXPECT_TRUE(it != addrs.end());
  936. }
  937. #endif
  938. class ChunkedEncodingTest : public ::testing::Test {
  939. protected:
  940. ChunkedEncodingTest()
  941. : cli_(HOST, PORT)
  942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  943. ,
  944. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  945. #endif
  946. {
  947. cli_.set_connection_timeout(2);
  948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  949. cli_.enable_server_certificate_verification(false);
  950. #endif
  951. }
  952. virtual void SetUp() {
  953. read_file("./image.jpg", image_data_);
  954. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  955. res.set_content("Hello World!", "text/plain");
  956. });
  957. svr_.Get(
  958. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  959. res.set_chunked_content_provider(
  960. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  961. size_t remaining = image_data_.size() - offset;
  962. if (remaining == 0) {
  963. sink.done();
  964. } else {
  965. constexpr size_t CHUNK_SIZE = 1024;
  966. size_t send_size = std::min(CHUNK_SIZE, remaining);
  967. sink.write(&image_data_[offset], send_size);
  968. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  969. }
  970. return true;
  971. });
  972. });
  973. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  974. svr_.wait_until_ready();
  975. }
  976. virtual void TearDown() {
  977. svr_.stop();
  978. if (!request_threads_.empty()) {
  979. std::this_thread::sleep_for(std::chrono::seconds(1));
  980. for (auto &t : request_threads_) {
  981. t.join();
  982. }
  983. }
  984. t_.join();
  985. }
  986. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  987. SSLClient cli_;
  988. SSLServer svr_;
  989. #else
  990. Client cli_;
  991. Server svr_;
  992. #endif
  993. thread t_;
  994. std::vector<thread> request_threads_;
  995. std::string image_data_;
  996. };
  997. TEST_F(ChunkedEncodingTest, NormalGet) {
  998. auto res = cli_.Get("/chunked");
  999. ASSERT_TRUE(res);
  1000. std::string out;
  1001. read_file("./image.jpg", out);
  1002. EXPECT_EQ(StatusCode::OK_200, res->status);
  1003. EXPECT_EQ(out, res->body);
  1004. }
  1005. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1006. std::string body;
  1007. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1008. body.append(data, data_length);
  1009. return true;
  1010. });
  1011. ASSERT_TRUE(res);
  1012. std::string out;
  1013. read_file("./image.jpg", out);
  1014. EXPECT_EQ(StatusCode::OK_200, res->status);
  1015. EXPECT_EQ(out, body);
  1016. }
  1017. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1018. std::string body;
  1019. auto res = cli_.Get(
  1020. "/chunked",
  1021. [&](const Response &response) {
  1022. EXPECT_EQ(StatusCode::OK_200, response.status);
  1023. return true;
  1024. },
  1025. [&](const char *data, size_t data_length) {
  1026. body.append(data, data_length);
  1027. return true;
  1028. });
  1029. ASSERT_TRUE(res);
  1030. std::string out;
  1031. read_file("./image.jpg", out);
  1032. EXPECT_EQ(StatusCode::OK_200, res->status);
  1033. EXPECT_EQ(out, body);
  1034. }
  1035. TEST(RangeTest, FromHTTPBin_Online) {
  1036. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1037. auto host = "httpbin.org";
  1038. auto path = std::string{"/range/32"};
  1039. #else
  1040. auto host = "nghttp2.org";
  1041. auto path = std::string{"/httpbin/range/32"};
  1042. #endif
  1043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1044. auto port = 443;
  1045. SSLClient cli(host, port);
  1046. #else
  1047. auto port = 80;
  1048. Client cli(host, port);
  1049. #endif
  1050. cli.set_connection_timeout(5);
  1051. {
  1052. auto res = cli.Get(path);
  1053. ASSERT_TRUE(res);
  1054. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1055. EXPECT_EQ(StatusCode::OK_200, res->status);
  1056. }
  1057. {
  1058. Headers headers = {make_range_header({{1, -1}})};
  1059. auto res = cli.Get(path, headers);
  1060. ASSERT_TRUE(res);
  1061. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1063. }
  1064. {
  1065. Headers headers = {make_range_header({{1, 10}})};
  1066. auto res = cli.Get(path, headers);
  1067. ASSERT_TRUE(res);
  1068. EXPECT_EQ("bcdefghijk", res->body);
  1069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1070. }
  1071. {
  1072. Headers headers = {make_range_header({{0, 31}})};
  1073. auto res = cli.Get(path, headers);
  1074. ASSERT_TRUE(res);
  1075. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1076. EXPECT_EQ(StatusCode::OK_200, res->status);
  1077. }
  1078. {
  1079. Headers headers = {make_range_header({{0, -1}})};
  1080. auto res = cli.Get(path, headers);
  1081. ASSERT_TRUE(res);
  1082. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. }
  1085. {
  1086. Headers headers = {make_range_header({{0, 32}})};
  1087. auto res = cli.Get(path, headers);
  1088. ASSERT_TRUE(res);
  1089. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1090. }
  1091. }
  1092. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1093. auto host = "unresolvableaddress.local";
  1094. auto path = std::string{"/"};
  1095. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1096. auto port = 443;
  1097. SSLClient cli(host, port);
  1098. #else
  1099. auto port = 80;
  1100. Client cli(host, port);
  1101. #endif
  1102. cli.set_connection_timeout(1);
  1103. {
  1104. auto res = cli.Get(path);
  1105. ASSERT_FALSE(res);
  1106. }
  1107. std::this_thread::sleep_for(std::chrono::seconds(8));
  1108. }
  1109. TEST(ConnectionErrorTest, InvalidHost) {
  1110. auto host = "-abcde.com";
  1111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1112. auto port = 443;
  1113. SSLClient cli(host, port);
  1114. #else
  1115. auto port = 80;
  1116. Client cli(host, port);
  1117. #endif
  1118. cli.set_connection_timeout(std::chrono::seconds(2));
  1119. auto res = cli.Get("/");
  1120. ASSERT_TRUE(!res);
  1121. EXPECT_EQ(Error::Connection, res.error());
  1122. }
  1123. TEST(ConnectionErrorTest, InvalidHost2) {
  1124. auto host = "httpbin.org/";
  1125. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1126. SSLClient cli(host);
  1127. #else
  1128. Client cli(host);
  1129. #endif
  1130. cli.set_connection_timeout(std::chrono::seconds(2));
  1131. auto res = cli.Get("/");
  1132. ASSERT_TRUE(!res);
  1133. EXPECT_EQ(Error::Connection, res.error());
  1134. }
  1135. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1136. auto host = "httpbin.org/";
  1137. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1138. SSLClient cli(host);
  1139. #else
  1140. Client cli(host);
  1141. #endif
  1142. cli.set_connection_timeout(std::chrono::seconds(2));
  1143. auto res = cli.Get("/");
  1144. ASSERT_TRUE(!res);
  1145. stringstream s;
  1146. s << "error code: " << res.error();
  1147. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1148. }
  1149. TEST(ConnectionErrorTest, InvalidPort) {
  1150. auto host = "localhost";
  1151. auto port = 44380;
  1152. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1153. SSLClient cli(host, port);
  1154. #else
  1155. Client cli(host, port);
  1156. #endif
  1157. cli.set_connection_timeout(std::chrono::seconds(2));
  1158. auto res = cli.Get("/");
  1159. ASSERT_TRUE(!res);
  1160. EXPECT_TRUE(Error::Connection == res.error() ||
  1161. Error::ConnectionTimeout == res.error());
  1162. }
  1163. TEST(ConnectionErrorTest, Timeout_Online) {
  1164. auto host = "google.com";
  1165. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1166. auto port = 44380;
  1167. SSLClient cli(host, port);
  1168. #else
  1169. auto port = 8080;
  1170. Client cli(host, port);
  1171. #endif
  1172. cli.set_connection_timeout(std::chrono::seconds(2));
  1173. // only probe one address type so that the error reason
  1174. // correlates to the timed-out IPv4, not the unsupported
  1175. // IPv6 connection attempt
  1176. cli.set_address_family(AF_INET);
  1177. auto res = cli.Get("/");
  1178. ASSERT_TRUE(!res);
  1179. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1180. }
  1181. TEST(CancelTest, NoCancel_Online) {
  1182. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1183. auto host = "httpbin.org";
  1184. auto path = std::string{"/range/32"};
  1185. #else
  1186. auto host = "nghttp2.org";
  1187. auto path = std::string{"/httpbin/range/32"};
  1188. #endif
  1189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1190. auto port = 443;
  1191. SSLClient cli(host, port);
  1192. #else
  1193. auto port = 80;
  1194. Client cli(host, port);
  1195. #endif
  1196. cli.set_connection_timeout(std::chrono::seconds(5));
  1197. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1198. ASSERT_TRUE(res);
  1199. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1200. EXPECT_EQ(StatusCode::OK_200, res->status);
  1201. }
  1202. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1203. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1204. auto host = "httpbin.org";
  1205. auto path = std::string{"/range/32"};
  1206. #else
  1207. auto host = "nghttp2.org";
  1208. auto path = std::string{"/httpbin/range/32"};
  1209. #endif
  1210. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1211. auto port = 443;
  1212. SSLClient cli(host, port);
  1213. #else
  1214. auto port = 80;
  1215. Client cli(host, port);
  1216. #endif
  1217. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1218. cli.set_connection_timeout(std::chrono::seconds(5));
  1219. ASSERT_TRUE(!res);
  1220. EXPECT_EQ(Error::Canceled, res.error());
  1221. }
  1222. TEST(CancelTest, WithCancelLargePayload_Online) {
  1223. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1224. auto host = "httpbin.org";
  1225. auto path = std::string{"/range/65536"};
  1226. #else
  1227. auto host = "nghttp2.org";
  1228. auto path = std::string{"/httpbin/range/65536"};
  1229. #endif
  1230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1231. auto port = 443;
  1232. SSLClient cli(host, port);
  1233. #else
  1234. auto port = 80;
  1235. Client cli(host, port);
  1236. #endif
  1237. cli.set_connection_timeout(std::chrono::seconds(5));
  1238. uint32_t count = 0;
  1239. auto res =
  1240. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1241. ASSERT_TRUE(!res);
  1242. EXPECT_EQ(Error::Canceled, res.error());
  1243. }
  1244. TEST(CancelTest, NoCancelPost) {
  1245. Server svr;
  1246. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1247. res.set_content("Hello World!", "text/plain");
  1248. });
  1249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1250. auto se = detail::scope_exit([&] {
  1251. svr.stop();
  1252. thread.join();
  1253. ASSERT_FALSE(svr.is_running());
  1254. });
  1255. svr.wait_until_ready();
  1256. Client cli(HOST, PORT);
  1257. cli.set_connection_timeout(std::chrono::seconds(5));
  1258. auto res =
  1259. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1260. "application/json", [](uint64_t, uint64_t) { return true; });
  1261. ASSERT_TRUE(res);
  1262. EXPECT_EQ("Hello World!", res->body);
  1263. EXPECT_EQ(StatusCode::OK_200, res->status);
  1264. }
  1265. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1266. Server svr;
  1267. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1268. res.set_content("Hello World!", "text/plain");
  1269. });
  1270. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1271. auto se = detail::scope_exit([&] {
  1272. svr.stop();
  1273. thread.join();
  1274. ASSERT_FALSE(svr.is_running());
  1275. });
  1276. svr.wait_until_ready();
  1277. Client cli(HOST, PORT);
  1278. cli.set_connection_timeout(std::chrono::seconds(5));
  1279. auto res =
  1280. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1281. "application/json", [](uint64_t, uint64_t) { return false; });
  1282. ASSERT_TRUE(!res);
  1283. EXPECT_EQ(Error::Canceled, res.error());
  1284. }
  1285. TEST(CancelTest, WithCancelLargePayloadPost) {
  1286. Server svr;
  1287. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1288. res.set_content(LARGE_DATA, "text/plain");
  1289. });
  1290. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1291. auto se = detail::scope_exit([&] {
  1292. svr.stop();
  1293. thread.join();
  1294. ASSERT_FALSE(svr.is_running());
  1295. });
  1296. svr.wait_until_ready();
  1297. Client cli(HOST, PORT);
  1298. cli.set_connection_timeout(std::chrono::seconds(5));
  1299. auto res =
  1300. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1301. "application/json", [](uint64_t, uint64_t) { return false; });
  1302. ASSERT_TRUE(!res);
  1303. EXPECT_EQ(Error::Canceled, res.error());
  1304. }
  1305. TEST(CancelTest, NoCancelPut) {
  1306. Server svr;
  1307. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1308. res.set_content("Hello World!", "text/plain");
  1309. });
  1310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1311. auto se = detail::scope_exit([&] {
  1312. svr.stop();
  1313. thread.join();
  1314. ASSERT_FALSE(svr.is_running());
  1315. });
  1316. svr.wait_until_ready();
  1317. Client cli(HOST, PORT);
  1318. cli.set_connection_timeout(std::chrono::seconds(5));
  1319. auto res =
  1320. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1321. "application/json", [](uint64_t, uint64_t) { return true; });
  1322. ASSERT_TRUE(res);
  1323. EXPECT_EQ("Hello World!", res->body);
  1324. EXPECT_EQ(StatusCode::OK_200, res->status);
  1325. }
  1326. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1327. Server svr;
  1328. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1329. res.set_content("Hello World!", "text/plain");
  1330. });
  1331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1332. auto se = detail::scope_exit([&] {
  1333. svr.stop();
  1334. thread.join();
  1335. ASSERT_FALSE(svr.is_running());
  1336. });
  1337. svr.wait_until_ready();
  1338. Client cli(HOST, PORT);
  1339. cli.set_connection_timeout(std::chrono::seconds(5));
  1340. auto res =
  1341. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1342. "application/json", [](uint64_t, uint64_t) { return false; });
  1343. ASSERT_TRUE(!res);
  1344. EXPECT_EQ(Error::Canceled, res.error());
  1345. }
  1346. TEST(CancelTest, WithCancelLargePayloadPut) {
  1347. Server svr;
  1348. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1349. res.set_content(LARGE_DATA, "text/plain");
  1350. });
  1351. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1352. auto se = detail::scope_exit([&] {
  1353. svr.stop();
  1354. thread.join();
  1355. ASSERT_FALSE(svr.is_running());
  1356. });
  1357. svr.wait_until_ready();
  1358. Client cli(HOST, PORT);
  1359. cli.set_connection_timeout(std::chrono::seconds(5));
  1360. auto res =
  1361. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1362. "application/json", [](uint64_t, uint64_t) { return false; });
  1363. ASSERT_TRUE(!res);
  1364. EXPECT_EQ(Error::Canceled, res.error());
  1365. }
  1366. TEST(CancelTest, NoCancelPatch) {
  1367. Server svr;
  1368. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1369. res.set_content("Hello World!", "text/plain");
  1370. });
  1371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1372. auto se = detail::scope_exit([&] {
  1373. svr.stop();
  1374. thread.join();
  1375. ASSERT_FALSE(svr.is_running());
  1376. });
  1377. svr.wait_until_ready();
  1378. Client cli(HOST, PORT);
  1379. cli.set_connection_timeout(std::chrono::seconds(5));
  1380. auto res =
  1381. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1382. "application/json", [](uint64_t, uint64_t) { return true; });
  1383. ASSERT_TRUE(res);
  1384. EXPECT_EQ("Hello World!", res->body);
  1385. EXPECT_EQ(StatusCode::OK_200, res->status);
  1386. }
  1387. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1388. Server svr;
  1389. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1390. res.set_content("Hello World!", "text/plain");
  1391. });
  1392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1393. auto se = detail::scope_exit([&] {
  1394. svr.stop();
  1395. thread.join();
  1396. ASSERT_FALSE(svr.is_running());
  1397. });
  1398. svr.wait_until_ready();
  1399. Client cli(HOST, PORT);
  1400. cli.set_connection_timeout(std::chrono::seconds(5));
  1401. auto res =
  1402. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1403. "application/json", [](uint64_t, uint64_t) { return false; });
  1404. ASSERT_TRUE(!res);
  1405. EXPECT_EQ(Error::Canceled, res.error());
  1406. }
  1407. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1408. Server svr;
  1409. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1410. res.set_content(LARGE_DATA, "text/plain");
  1411. });
  1412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1413. auto se = detail::scope_exit([&] {
  1414. svr.stop();
  1415. thread.join();
  1416. ASSERT_FALSE(svr.is_running());
  1417. });
  1418. svr.wait_until_ready();
  1419. Client cli(HOST, PORT);
  1420. cli.set_connection_timeout(std::chrono::seconds(5));
  1421. auto res =
  1422. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1423. "application/json", [](uint64_t, uint64_t) { return false; });
  1424. ASSERT_TRUE(!res);
  1425. EXPECT_EQ(Error::Canceled, res.error());
  1426. }
  1427. TEST(CancelTest, NoCancelDelete) {
  1428. Server svr;
  1429. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1430. res.set_content("Hello World!", "text/plain");
  1431. });
  1432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1433. auto se = detail::scope_exit([&] {
  1434. svr.stop();
  1435. thread.join();
  1436. ASSERT_FALSE(svr.is_running());
  1437. });
  1438. svr.wait_until_ready();
  1439. Client cli(HOST, PORT);
  1440. cli.set_connection_timeout(std::chrono::seconds(5));
  1441. auto res =
  1442. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1443. "application/json", [](uint64_t, uint64_t) { return true; });
  1444. ASSERT_TRUE(res);
  1445. EXPECT_EQ("Hello World!", res->body);
  1446. EXPECT_EQ(StatusCode::OK_200, res->status);
  1447. }
  1448. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1449. Server svr;
  1450. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1451. res.set_content("Hello World!", "text/plain");
  1452. });
  1453. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1454. auto se = detail::scope_exit([&] {
  1455. svr.stop();
  1456. thread.join();
  1457. ASSERT_FALSE(svr.is_running());
  1458. });
  1459. svr.wait_until_ready();
  1460. Client cli(HOST, PORT);
  1461. cli.set_connection_timeout(std::chrono::seconds(5));
  1462. auto res =
  1463. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1464. "application/json", [](uint64_t, uint64_t) { return false; });
  1465. ASSERT_TRUE(!res);
  1466. EXPECT_EQ(Error::Canceled, res.error());
  1467. }
  1468. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1469. Server svr;
  1470. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1471. res.set_content(LARGE_DATA, "text/plain");
  1472. });
  1473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1474. auto se = detail::scope_exit([&] {
  1475. svr.stop();
  1476. thread.join();
  1477. ASSERT_FALSE(svr.is_running());
  1478. });
  1479. svr.wait_until_ready();
  1480. Client cli(HOST, PORT);
  1481. cli.set_connection_timeout(std::chrono::seconds(5));
  1482. auto res =
  1483. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1484. "application/json", [](uint64_t, uint64_t) { return false; });
  1485. ASSERT_TRUE(!res);
  1486. EXPECT_EQ(Error::Canceled, res.error());
  1487. }
  1488. static std::string remove_whitespace(const std::string &input) {
  1489. std::string output;
  1490. output.reserve(input.size());
  1491. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1492. [](unsigned char c) { return !std::isspace(c); });
  1493. return output;
  1494. }
  1495. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1496. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1497. auto host = "httpbin.org";
  1498. auto path = std::string{"/basic-auth/hello/world"};
  1499. #else
  1500. auto host = "nghttp2.org";
  1501. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1502. #endif
  1503. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1504. auto port = 443;
  1505. SSLClient cli(host, port);
  1506. #else
  1507. auto port = 80;
  1508. Client cli(host, port);
  1509. #endif
  1510. {
  1511. auto res = cli.Get(path);
  1512. ASSERT_TRUE(res);
  1513. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1514. }
  1515. {
  1516. auto res =
  1517. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1518. ASSERT_TRUE(res);
  1519. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1520. remove_whitespace(res->body));
  1521. EXPECT_EQ(StatusCode::OK_200, res->status);
  1522. }
  1523. {
  1524. cli.set_basic_auth("hello", "world");
  1525. auto res = cli.Get(path);
  1526. ASSERT_TRUE(res);
  1527. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1528. remove_whitespace(res->body));
  1529. EXPECT_EQ(StatusCode::OK_200, res->status);
  1530. }
  1531. {
  1532. cli.set_basic_auth("hello", "bad");
  1533. auto res = cli.Get(path);
  1534. ASSERT_TRUE(res);
  1535. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1536. }
  1537. {
  1538. cli.set_basic_auth("bad", "world");
  1539. auto res = cli.Get(path);
  1540. ASSERT_TRUE(res);
  1541. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1542. }
  1543. }
  1544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1545. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1546. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1547. auto host = "httpbin.org";
  1548. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1549. auto paths = std::vector<std::string>{
  1550. "/digest-auth/auth/hello/world/MD5",
  1551. "/digest-auth/auth/hello/world/SHA-256",
  1552. "/digest-auth/auth/hello/world/SHA-512",
  1553. "/digest-auth/auth-int/hello/world/MD5",
  1554. };
  1555. #else
  1556. auto host = "nghttp2.org";
  1557. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1558. auto paths = std::vector<std::string>{
  1559. "/httpbin/digest-auth/auth/hello/world/MD5",
  1560. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1561. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1562. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1563. };
  1564. #endif
  1565. auto port = 443;
  1566. SSLClient cli(host, port);
  1567. {
  1568. auto res = cli.Get(unauth_path);
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1571. }
  1572. {
  1573. cli.set_digest_auth("hello", "world");
  1574. for (const auto &path : paths) {
  1575. auto res = cli.Get(path.c_str());
  1576. ASSERT_TRUE(res);
  1577. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1578. remove_whitespace(res->body));
  1579. EXPECT_EQ(StatusCode::OK_200, res->status);
  1580. }
  1581. cli.set_digest_auth("hello", "bad");
  1582. for (const auto &path : paths) {
  1583. auto res = cli.Get(path.c_str());
  1584. ASSERT_TRUE(res);
  1585. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1586. }
  1587. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1588. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1589. // cli.set_digest_auth("bad", "world");
  1590. // for (const auto& path : paths) {
  1591. // auto res = cli.Get(path.c_str());
  1592. // ASSERT_TRUE(res);
  1593. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1594. // }
  1595. }
  1596. }
  1597. #endif
  1598. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1599. auto host = "google.com";
  1600. auto another_host = "example.com";
  1601. auto wrong_ip = "0.0.0.0";
  1602. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1603. SSLClient cli(host);
  1604. #else
  1605. Client cli(host);
  1606. #endif
  1607. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1608. auto res = cli.Get("/");
  1609. ASSERT_TRUE(res);
  1610. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1611. }
  1612. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1613. auto host = "google.com";
  1614. auto wrong_ip = "0.0.0.0";
  1615. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1616. SSLClient cli(host);
  1617. #else
  1618. Client cli(host);
  1619. #endif
  1620. cli.set_hostname_addr_map({{host, wrong_ip}});
  1621. auto res = cli.Get("/");
  1622. ASSERT_TRUE(!res);
  1623. EXPECT_EQ(Error::Connection, res.error());
  1624. }
  1625. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1626. auto host = "nghttp2.org";
  1627. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1628. SSLClient cli(host);
  1629. #else
  1630. Client cli(host);
  1631. #endif
  1632. cli.set_follow_location(true);
  1633. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1634. ASSERT_TRUE(res);
  1635. EXPECT_EQ(StatusCode::OK_200, res->status);
  1636. }
  1637. TEST(RedirectTest, Redirect_Online) {
  1638. auto host = "nghttp2.org";
  1639. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1640. SSLClient cli(host);
  1641. #else
  1642. Client cli(host);
  1643. #endif
  1644. cli.set_follow_location(true);
  1645. auto res = cli.Get("/httpbin/redirect/3");
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::OK_200, res->status);
  1648. }
  1649. TEST(RelativeRedirectTest, Redirect_Online) {
  1650. auto host = "nghttp2.org";
  1651. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1652. SSLClient cli(host);
  1653. #else
  1654. Client cli(host);
  1655. #endif
  1656. cli.set_follow_location(true);
  1657. auto res = cli.Get("/httpbin/relative-redirect/3");
  1658. ASSERT_TRUE(res);
  1659. EXPECT_EQ(StatusCode::OK_200, res->status);
  1660. }
  1661. TEST(TooManyRedirectTest, Redirect_Online) {
  1662. auto host = "nghttp2.org";
  1663. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1664. SSLClient cli(host);
  1665. #else
  1666. Client cli(host);
  1667. #endif
  1668. cli.set_follow_location(true);
  1669. auto res = cli.Get("/httpbin/redirect/21");
  1670. ASSERT_TRUE(!res);
  1671. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1672. }
  1673. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1674. TEST(YahooRedirectTest, Redirect_Online) {
  1675. Client cli("yahoo.com");
  1676. auto res = cli.Get("/");
  1677. ASSERT_TRUE(res);
  1678. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1679. cli.set_follow_location(true);
  1680. res = cli.Get("/");
  1681. ASSERT_TRUE(res);
  1682. EXPECT_EQ(StatusCode::OK_200, res->status);
  1683. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1684. }
  1685. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1686. #define REDIR_HOST "httpbingo.org"
  1687. #define REDIR_PATH "/redirect-to"
  1688. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1689. SSLClient cli(REDIR_HOST);
  1690. cli.set_follow_location(true);
  1691. auto res =
  1692. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1693. ASSERT_TRUE(res);
  1694. EXPECT_EQ(StatusCode::OK_200, res->status);
  1695. }
  1696. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1697. SSLClient cli(REDIR_HOST);
  1698. cli.set_follow_location(true);
  1699. Params params;
  1700. params.emplace("url", "http://example.com");
  1701. params.emplace("status_code", "302");
  1702. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1703. ASSERT_TRUE(res);
  1704. EXPECT_EQ(StatusCode::OK_200, res->status);
  1705. }
  1706. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1707. SSLClient cli(REDIR_HOST);
  1708. cli.set_follow_location(true);
  1709. Params params;
  1710. params.emplace("url", "http://example.com");
  1711. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1712. ASSERT_TRUE(res);
  1713. EXPECT_EQ(StatusCode::OK_200, res->status);
  1714. }
  1715. TEST(UrlWithSpace, Redirect_Online) {
  1716. SSLClient cli("edge.forgecdn.net");
  1717. cli.set_follow_location(true);
  1718. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1719. ASSERT_TRUE(res);
  1720. EXPECT_EQ(StatusCode::OK_200, res->status);
  1721. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1722. }
  1723. #endif
  1724. #if !defined(_WIN32) && !defined(_WIN64)
  1725. TEST(ReceiveSignals, Signal) {
  1726. auto setupSignalHandlers = []() {
  1727. struct sigaction act;
  1728. sigemptyset(&act.sa_mask);
  1729. act.sa_flags = SA_SIGINFO;
  1730. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1731. switch (sig) {
  1732. case SIGINT:
  1733. default: break;
  1734. }
  1735. };
  1736. ::sigaction(SIGINT, &act, nullptr);
  1737. };
  1738. Server svr;
  1739. int port = 0;
  1740. auto thread = std::thread([&]() {
  1741. setupSignalHandlers();
  1742. port = svr.bind_to_any_port("localhost");
  1743. svr.listen_after_bind();
  1744. });
  1745. auto se = detail::scope_exit([&] {
  1746. svr.stop();
  1747. thread.join();
  1748. ASSERT_FALSE(svr.is_running());
  1749. });
  1750. svr.wait_until_ready();
  1751. ASSERT_TRUE(svr.is_running());
  1752. pthread_kill(thread.native_handle(), SIGINT);
  1753. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1754. ASSERT_TRUE(svr.is_running());
  1755. }
  1756. #endif
  1757. TEST(RedirectToDifferentPort, Redirect) {
  1758. Server svr1;
  1759. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1760. res.set_content("Hello World!", "text/plain");
  1761. });
  1762. int svr1_port = 0;
  1763. auto thread1 = std::thread([&]() {
  1764. svr1_port = svr1.bind_to_any_port("localhost");
  1765. svr1.listen_after_bind();
  1766. });
  1767. Server svr2;
  1768. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1769. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1770. });
  1771. int svr2_port = 0;
  1772. auto thread2 = std::thread([&]() {
  1773. svr2_port = svr2.bind_to_any_port("localhost");
  1774. svr2.listen_after_bind();
  1775. });
  1776. auto se = detail::scope_exit([&] {
  1777. svr2.stop();
  1778. thread2.join();
  1779. svr1.stop();
  1780. thread1.join();
  1781. ASSERT_FALSE(svr2.is_running());
  1782. ASSERT_FALSE(svr1.is_running());
  1783. });
  1784. svr1.wait_until_ready();
  1785. svr2.wait_until_ready();
  1786. Client cli("localhost", svr2_port);
  1787. cli.set_follow_location(true);
  1788. auto res = cli.Get("/2");
  1789. ASSERT_TRUE(res);
  1790. EXPECT_EQ(StatusCode::OK_200, res->status);
  1791. EXPECT_EQ("Hello World!", res->body);
  1792. }
  1793. TEST(RedirectFromPageWithContent, Redirect) {
  1794. Server svr;
  1795. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1796. res.set_content("___", "text/plain");
  1797. res.set_redirect("/2");
  1798. });
  1799. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1800. res.set_content("Hello World!", "text/plain");
  1801. });
  1802. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1803. auto se = detail::scope_exit([&] {
  1804. svr.stop();
  1805. th.join();
  1806. ASSERT_FALSE(svr.is_running());
  1807. });
  1808. svr.wait_until_ready();
  1809. {
  1810. Client cli("localhost", PORT);
  1811. cli.set_follow_location(true);
  1812. std::string body;
  1813. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1814. body.append(data, data_length);
  1815. return true;
  1816. });
  1817. ASSERT_TRUE(res);
  1818. EXPECT_EQ(StatusCode::OK_200, res->status);
  1819. EXPECT_EQ("Hello World!", body);
  1820. }
  1821. {
  1822. Client cli("localhost", PORT);
  1823. std::string body;
  1824. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1825. body.append(data, data_length);
  1826. return true;
  1827. });
  1828. ASSERT_TRUE(res);
  1829. EXPECT_EQ(StatusCode::Found_302, res->status);
  1830. EXPECT_EQ("___", body);
  1831. }
  1832. }
  1833. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1834. Server svr;
  1835. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1836. res.set_content("___", "text/plain");
  1837. // res.set_redirect("/2");
  1838. res.set_redirect("http://[::1]:1234/2");
  1839. });
  1840. svr.Get("/2", [&](const Request &req, Response &res) {
  1841. auto host_header = req.headers.find("Host");
  1842. ASSERT_TRUE(host_header != req.headers.end());
  1843. EXPECT_EQ("[::1]:1234", host_header->second);
  1844. res.set_content("Hello World!", "text/plain");
  1845. });
  1846. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1847. auto se = detail::scope_exit([&] {
  1848. svr.stop();
  1849. th.join();
  1850. ASSERT_FALSE(svr.is_running());
  1851. });
  1852. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1853. // actually starts anything, so the condition !svr.is_running() will
  1854. // always remain true, and the loop never stops.
  1855. // This basically counts how many milliseconds have passed since the
  1856. // call to svr.listen(), and if after 5 seconds nothing started yet
  1857. // aborts the test.
  1858. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1859. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1860. ASSERT_LT(milliseconds, 5000U);
  1861. }
  1862. {
  1863. Client cli("http://[::1]:1234");
  1864. cli.set_follow_location(true);
  1865. std::string body;
  1866. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1867. body.append(data, data_length);
  1868. return true;
  1869. });
  1870. ASSERT_TRUE(res);
  1871. EXPECT_EQ(StatusCode::OK_200, res->status);
  1872. EXPECT_EQ("Hello World!", body);
  1873. }
  1874. {
  1875. Client cli("http://[::1]:1234");
  1876. std::string body;
  1877. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1878. body.append(data, data_length);
  1879. return true;
  1880. });
  1881. ASSERT_TRUE(res);
  1882. EXPECT_EQ(StatusCode::Found_302, res->status);
  1883. EXPECT_EQ("___", body);
  1884. }
  1885. }
  1886. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1887. Server svr;
  1888. svr.Get("/foo", [](const Request &req, Response &res) {
  1889. auto a = req.params.find("a");
  1890. if (a != req.params.end()) {
  1891. res.set_content((*a).second, "text/plain");
  1892. res.status = StatusCode::OK_200;
  1893. } else {
  1894. res.status = StatusCode::BadRequest_400;
  1895. }
  1896. });
  1897. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. thread.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. svr.wait_until_ready();
  1904. {
  1905. Client cli(HOST, PORT);
  1906. cli.set_path_encode(false);
  1907. auto res = cli.Get("/foo?a=explicitly+encoded");
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(StatusCode::OK_200, res->status);
  1910. // This expects it back with a space, as the `+` won't have been
  1911. // url-encoded, and server-side the params get decoded turning `+`
  1912. // into spaces.
  1913. EXPECT_EQ("explicitly encoded", res->body);
  1914. }
  1915. }
  1916. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1917. Server svr;
  1918. svr.Get("/", [](const Request &req, Response &) {
  1919. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1920. });
  1921. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1922. auto se = detail::scope_exit([&] {
  1923. svr.stop();
  1924. thread.join();
  1925. ASSERT_FALSE(svr.is_running());
  1926. });
  1927. svr.wait_until_ready();
  1928. {
  1929. Client cli(HOST, PORT);
  1930. cli.set_path_encode(false);
  1931. auto res = cli.Get("/?something=%0A");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::OK_200, res->status);
  1934. }
  1935. }
  1936. TEST(BindServerTest, DISABLED_BindDualStack) {
  1937. Server svr;
  1938. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1939. res.set_content("Hello World!", "text/plain");
  1940. });
  1941. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1942. auto se = detail::scope_exit([&] {
  1943. svr.stop();
  1944. thread.join();
  1945. ASSERT_FALSE(svr.is_running());
  1946. });
  1947. svr.wait_until_ready();
  1948. {
  1949. Client cli("127.0.0.1", PORT);
  1950. auto res = cli.Get("/1");
  1951. ASSERT_TRUE(res);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. EXPECT_EQ("Hello World!", res->body);
  1954. }
  1955. {
  1956. Client cli("::1", PORT);
  1957. auto res = cli.Get("/1");
  1958. ASSERT_TRUE(res);
  1959. EXPECT_EQ(StatusCode::OK_200, res->status);
  1960. EXPECT_EQ("Hello World!", res->body);
  1961. }
  1962. }
  1963. TEST(BindServerTest, BindAndListenSeparately) {
  1964. Server svr;
  1965. int port = svr.bind_to_any_port("0.0.0.0");
  1966. ASSERT_TRUE(svr.is_valid());
  1967. ASSERT_TRUE(port > 0);
  1968. svr.stop();
  1969. }
  1970. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1971. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1972. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1973. CLIENT_CA_CERT_DIR);
  1974. int port = svr.bind_to_any_port("0.0.0.0");
  1975. ASSERT_TRUE(svr.is_valid());
  1976. ASSERT_TRUE(port > 0);
  1977. svr.stop();
  1978. }
  1979. #endif
  1980. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1981. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1982. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1983. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1984. int port = svr.bind_to_any_port("0.0.0.0");
  1985. ASSERT_TRUE(svr.is_valid());
  1986. ASSERT_TRUE(port > 0);
  1987. svr.stop();
  1988. }
  1989. #endif
  1990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1991. X509 *readCertificate(const std::string &strFileName) {
  1992. std::ifstream inStream(strFileName);
  1993. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1994. std::istreambuf_iterator<char>());
  1995. if (strCertPEM.empty()) return (nullptr);
  1996. BIO *pbCert = BIO_new(BIO_s_mem());
  1997. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1998. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1999. BIO_free(pbCert);
  2000. return (pCert);
  2001. }
  2002. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2003. std::ifstream inStream(strFileName);
  2004. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2005. std::istreambuf_iterator<char>());
  2006. if (strPrivateKeyPEM.empty()) return (nullptr);
  2007. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2008. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2009. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2010. BIO_free(pbPrivKey);
  2011. return (pPrivateKey);
  2012. }
  2013. TEST(BindServerTest, UpdateCerts) {
  2014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2015. int port = svr.bind_to_any_port("0.0.0.0");
  2016. ASSERT_TRUE(svr.is_valid());
  2017. ASSERT_TRUE(port > 0);
  2018. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2019. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2020. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2021. ASSERT_TRUE(cert != nullptr);
  2022. ASSERT_TRUE(ca_cert != nullptr);
  2023. ASSERT_TRUE(key != nullptr);
  2024. X509_STORE *cert_store = X509_STORE_new();
  2025. X509_STORE_add_cert(cert_store, ca_cert);
  2026. svr.update_certs(cert, key, cert_store);
  2027. ASSERT_TRUE(svr.is_valid());
  2028. svr.stop();
  2029. X509_free(cert);
  2030. X509_free(ca_cert);
  2031. EVP_PKEY_free(key);
  2032. }
  2033. #endif
  2034. TEST(ErrorHandlerTest, ContentLength) {
  2035. Server svr;
  2036. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2037. res.status = StatusCode::OK_200;
  2038. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2039. "text/html"); // <= Content-Length still 13
  2040. });
  2041. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2042. res.set_content("Hello World!\n", "text/plain");
  2043. res.status = 524;
  2044. });
  2045. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2046. auto se = detail::scope_exit([&] {
  2047. svr.stop();
  2048. thread.join();
  2049. ASSERT_FALSE(svr.is_running());
  2050. });
  2051. svr.wait_until_ready();
  2052. {
  2053. Client cli(HOST, PORT);
  2054. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2055. ASSERT_TRUE(res);
  2056. EXPECT_EQ(StatusCode::OK_200, res->status);
  2057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2058. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2059. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2060. }
  2061. }
  2062. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2063. TEST(ExceptionTest, WithoutExceptionHandler) {
  2064. Server svr;
  2065. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2066. throw std::runtime_error("exception...");
  2067. });
  2068. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2069. throw std::runtime_error("exception\r\n...");
  2070. });
  2071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2072. auto se = detail::scope_exit([&] {
  2073. svr.stop();
  2074. listen_thread.join();
  2075. ASSERT_FALSE(svr.is_running());
  2076. });
  2077. svr.wait_until_ready();
  2078. Client cli("localhost", PORT);
  2079. {
  2080. auto res = cli.Get("/exception");
  2081. ASSERT_TRUE(res);
  2082. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2083. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2084. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2085. }
  2086. {
  2087. auto res = cli.Get("/unknown");
  2088. ASSERT_TRUE(res);
  2089. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2090. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2091. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2092. }
  2093. }
  2094. TEST(ExceptionTest, WithExceptionHandler) {
  2095. Server svr;
  2096. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2097. std::exception_ptr ep) {
  2098. EXPECT_FALSE(ep == nullptr);
  2099. try {
  2100. std::rethrow_exception(ep);
  2101. } catch (std::exception &e) {
  2102. EXPECT_EQ("abc", std::string(e.what()));
  2103. } catch (...) {}
  2104. res.status = StatusCode::InternalServerError_500;
  2105. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2106. "text/html"); // <= Content-Length still 13 at this point
  2107. });
  2108. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2109. res.set_content("Hello World!\n", "text/plain");
  2110. throw std::runtime_error("abc");
  2111. });
  2112. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2113. auto se = detail::scope_exit([&] {
  2114. svr.stop();
  2115. thread.join();
  2116. ASSERT_FALSE(svr.is_running());
  2117. });
  2118. svr.wait_until_ready();
  2119. for (size_t i = 0; i < 10; i++) {
  2120. Client cli(HOST, PORT);
  2121. for (size_t j = 0; j < 100; j++) {
  2122. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2123. ASSERT_TRUE(res);
  2124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2126. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2128. }
  2129. cli.set_keep_alive(true);
  2130. for (size_t j = 0; j < 100; j++) {
  2131. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2135. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2136. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2137. }
  2138. }
  2139. }
  2140. TEST(ExceptionTest, AndErrorHandler) {
  2141. Server svr;
  2142. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2143. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2144. });
  2145. svr.set_exception_handler(
  2146. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2147. EXPECT_FALSE(ep == nullptr);
  2148. try {
  2149. std::rethrow_exception(ep);
  2150. } catch (std::exception &e) {
  2151. res.set_content(e.what(), "text/html");
  2152. } catch (...) {}
  2153. res.status = StatusCode::InternalServerError_500;
  2154. });
  2155. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2156. throw std::runtime_error("EXCEPTION");
  2157. });
  2158. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2159. res.set_content("ERROR", "text/html");
  2160. res.status = StatusCode::InternalServerError_500;
  2161. });
  2162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2163. auto se = detail::scope_exit([&] {
  2164. svr.stop();
  2165. thread.join();
  2166. ASSERT_FALSE(svr.is_running());
  2167. });
  2168. svr.wait_until_ready();
  2169. Client cli(HOST, PORT);
  2170. {
  2171. auto res = cli.Get("/exception");
  2172. ASSERT_TRUE(res);
  2173. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2174. EXPECT_EQ("EXCEPTION", res->body);
  2175. }
  2176. {
  2177. auto res = cli.Get("/error");
  2178. ASSERT_TRUE(res);
  2179. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2180. EXPECT_EQ("ERROR", res->body);
  2181. }
  2182. {
  2183. auto res = cli.Get("/invalid");
  2184. ASSERT_TRUE(res);
  2185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2186. EXPECT_EQ("NOT_FOUND", res->body);
  2187. }
  2188. }
  2189. #endif
  2190. TEST(NoContentTest, ContentLength) {
  2191. Server svr;
  2192. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2193. res.status = StatusCode::NoContent_204;
  2194. });
  2195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2196. auto se = detail::scope_exit([&] {
  2197. svr.stop();
  2198. thread.join();
  2199. ASSERT_FALSE(svr.is_running());
  2200. });
  2201. svr.wait_until_ready();
  2202. {
  2203. Client cli(HOST, PORT);
  2204. auto res = cli.Get("/hi");
  2205. ASSERT_TRUE(res);
  2206. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2207. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2208. }
  2209. }
  2210. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2213. ASSERT_TRUE(svr.is_valid());
  2214. #else
  2215. Server svr;
  2216. #endif
  2217. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2218. if (req.path == "/routing_handler") {
  2219. res.set_header("PRE_ROUTING", "on");
  2220. res.set_content("Routing Handler", "text/plain");
  2221. return httplib::Server::HandlerResponse::Handled;
  2222. }
  2223. return httplib::Server::HandlerResponse::Unhandled;
  2224. });
  2225. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2226. res.set_content("Error", "text/html");
  2227. });
  2228. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2229. if (req.path == "/routing_handler") {
  2230. res.set_header("POST_ROUTING", "on");
  2231. }
  2232. });
  2233. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2234. res.set_content("Hello World!\n", "text/plain");
  2235. });
  2236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2237. auto se = detail::scope_exit([&] {
  2238. svr.stop();
  2239. thread.join();
  2240. ASSERT_FALSE(svr.is_running());
  2241. });
  2242. svr.wait_until_ready();
  2243. {
  2244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2245. SSLClient cli(HOST, PORT);
  2246. cli.enable_server_certificate_verification(false);
  2247. #else
  2248. Client cli(HOST, PORT);
  2249. #endif
  2250. auto res = cli.Get("/routing_handler");
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ("Routing Handler", res->body);
  2254. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2255. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2256. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2257. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2258. }
  2259. {
  2260. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2261. SSLClient cli(HOST, PORT);
  2262. cli.enable_server_certificate_verification(false);
  2263. #else
  2264. Client cli(HOST, PORT);
  2265. #endif
  2266. auto res = cli.Get("/hi");
  2267. ASSERT_TRUE(res);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ("Hello World!\n", res->body);
  2270. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2271. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2272. }
  2273. {
  2274. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2275. SSLClient cli(HOST, PORT);
  2276. cli.enable_server_certificate_verification(false);
  2277. #else
  2278. Client cli(HOST, PORT);
  2279. #endif
  2280. auto res = cli.Get("/aaa");
  2281. ASSERT_TRUE(res);
  2282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2283. EXPECT_EQ("Error", res->body);
  2284. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2285. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2286. }
  2287. }
  2288. TEST(RequestHandlerTest, PreRequestHandler) {
  2289. auto route_path = "/user/:user";
  2290. Server svr;
  2291. svr.Get("/hi", [](const Request &, Response &res) {
  2292. res.set_content("hi", "text/plain");
  2293. });
  2294. svr.Get(route_path, [](const Request &req, Response &res) {
  2295. res.set_content(req.path_params.at("user"), "text/plain");
  2296. });
  2297. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2298. if (req.matched_route == route_path) {
  2299. auto user = req.path_params.at("user");
  2300. if (user != "john") {
  2301. res.status = StatusCode::Forbidden_403;
  2302. res.set_content("error", "text/html");
  2303. return Server::HandlerResponse::Handled;
  2304. }
  2305. }
  2306. return Server::HandlerResponse::Unhandled;
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. {
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("hi", res->body);
  2321. }
  2322. {
  2323. auto res = cli.Get("/user/john");
  2324. ASSERT_TRUE(res);
  2325. EXPECT_EQ(StatusCode::OK_200, res->status);
  2326. EXPECT_EQ("john", res->body);
  2327. }
  2328. {
  2329. auto res = cli.Get("/user/invalid-user");
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2332. EXPECT_EQ("error", res->body);
  2333. }
  2334. }
  2335. TEST(InvalidFormatTest, StatusCode) {
  2336. Server svr;
  2337. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!\n", "text/plain");
  2339. res.status = 9999; // Status should be a three-digit code...
  2340. });
  2341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2342. auto se = detail::scope_exit([&] {
  2343. svr.stop();
  2344. thread.join();
  2345. ASSERT_FALSE(svr.is_running());
  2346. });
  2347. svr.wait_until_ready();
  2348. {
  2349. Client cli(HOST, PORT);
  2350. auto res = cli.Get("/hi");
  2351. ASSERT_FALSE(res);
  2352. }
  2353. }
  2354. TEST(URLFragmentTest, WithFragment) {
  2355. Server svr;
  2356. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2357. EXPECT_TRUE(req.target == "/hi");
  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. {
  2367. Client cli(HOST, PORT);
  2368. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2369. EXPECT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. res = cli.Get("/hi%23key1=val1=key2=val2");
  2372. EXPECT_TRUE(res);
  2373. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2374. }
  2375. }
  2376. TEST(HeaderWriter, SetHeaderWriter) {
  2377. Server svr;
  2378. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2379. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2380. return detail::write_headers(strm, hdrs);
  2381. });
  2382. svr.Get("/hi", [](const Request &req, Response &res) {
  2383. auto it = req.headers.find("CustomClientHeader");
  2384. EXPECT_TRUE(it != req.headers.end());
  2385. EXPECT_EQ(it->second, "CustomClientValue");
  2386. res.set_content("Hello World!\n", "text/plain");
  2387. });
  2388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2389. auto se = detail::scope_exit([&] {
  2390. svr.stop();
  2391. thread.join();
  2392. ASSERT_FALSE(svr.is_running());
  2393. });
  2394. svr.wait_until_ready();
  2395. {
  2396. Client cli(HOST, PORT);
  2397. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2398. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2399. return detail::write_headers(strm, hdrs);
  2400. });
  2401. auto res = cli.Get("/hi");
  2402. EXPECT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. auto it = res->headers.find("CustomServerHeader");
  2405. EXPECT_TRUE(it != res->headers.end());
  2406. EXPECT_EQ(it->second, "CustomServerValue");
  2407. }
  2408. }
  2409. class ServerTest : public ::testing::Test {
  2410. protected:
  2411. ServerTest()
  2412. : cli_(HOST, PORT)
  2413. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2414. ,
  2415. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2416. #endif
  2417. {
  2418. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2419. cli_.enable_server_certificate_verification(false);
  2420. #endif
  2421. }
  2422. virtual void SetUp() {
  2423. svr_.set_mount_point("/", "./www");
  2424. svr_.set_mount_point("/mount", "./www2");
  2425. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2426. svr_.Get("/hi",
  2427. [&](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. })
  2430. .Get("/file_content",
  2431. [&](const Request & /*req*/, Response &res) {
  2432. res.set_file_content("./www/dir/test.html");
  2433. })
  2434. .Get("/file_content_with_content_type",
  2435. [&](const Request & /*req*/, Response &res) {
  2436. res.set_file_content("./www/file", "text/plain");
  2437. })
  2438. .Get("/invalid_file_content",
  2439. [&](const Request & /*req*/, Response &res) {
  2440. res.set_file_content("./www/dir/invalid_file_path");
  2441. })
  2442. .Get("/http_response_splitting",
  2443. [&](const Request & /*req*/, Response &res) {
  2444. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2445. EXPECT_EQ(0U, res.headers.size());
  2446. EXPECT_FALSE(res.has_header("a"));
  2447. res.set_header("a", "1\nSet-Cookie: a=1");
  2448. EXPECT_EQ(0U, res.headers.size());
  2449. EXPECT_FALSE(res.has_header("a"));
  2450. res.set_header("a", "1\rSet-Cookie: a=1");
  2451. EXPECT_EQ(0U, res.headers.size());
  2452. EXPECT_FALSE(res.has_header("a"));
  2453. res.set_header("a\r\nb", "0");
  2454. EXPECT_EQ(0U, res.headers.size());
  2455. EXPECT_FALSE(res.has_header("a"));
  2456. res.set_header("a\rb", "0");
  2457. EXPECT_EQ(0U, res.headers.size());
  2458. EXPECT_FALSE(res.has_header("a"));
  2459. res.set_header("a\nb", "0");
  2460. EXPECT_EQ(0U, res.headers.size());
  2461. EXPECT_FALSE(res.has_header("a"));
  2462. res.set_redirect("1\r\nSet-Cookie: a=1");
  2463. EXPECT_EQ(0U, res.headers.size());
  2464. EXPECT_FALSE(res.has_header("Location"));
  2465. })
  2466. .Get("/slow",
  2467. [&](const Request & /*req*/, Response &res) {
  2468. std::this_thread::sleep_for(std::chrono::seconds(2));
  2469. res.set_content("slow", "text/plain");
  2470. })
  2471. #if 0
  2472. .Post("/slowpost",
  2473. [&](const Request & /*req*/, Response &res) {
  2474. std::this_thread::sleep_for(std::chrono::seconds(2));
  2475. res.set_content("slow", "text/plain");
  2476. })
  2477. #endif
  2478. .Get("/remote_addr",
  2479. [&](const Request &req, Response &res) {
  2480. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  2481. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  2482. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  2483. EXPECT_EQ(req.remote_port,
  2484. std::stoi(req.get_header_value("REMOTE_PORT")));
  2485. res.set_content(remote_addr.c_str(), "text/plain");
  2486. })
  2487. .Get("/local_addr",
  2488. [&](const Request &req, Response &res) {
  2489. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  2490. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  2491. auto local_addr = req.get_header_value("LOCAL_ADDR");
  2492. auto local_port = req.get_header_value("LOCAL_PORT");
  2493. EXPECT_EQ(req.local_addr, local_addr);
  2494. EXPECT_EQ(req.local_port, std::stoi(local_port));
  2495. res.set_content(local_addr.append(":").append(local_port),
  2496. "text/plain");
  2497. })
  2498. .Get("/endwith%",
  2499. [&](const Request & /*req*/, Response &res) {
  2500. res.set_content("Hello World!", "text/plain");
  2501. })
  2502. .Get("/a\\+\\+b",
  2503. [&](const Request &req, Response &res) {
  2504. ASSERT_TRUE(req.has_param("a +b"));
  2505. auto val = req.get_param_value("a +b");
  2506. res.set_content(val, "text/plain");
  2507. })
  2508. .Get("/", [&](const Request & /*req*/,
  2509. Response &res) { res.set_redirect("/hi"); })
  2510. .Post("/1",
  2511. [](const Request & /*req*/, Response &res) {
  2512. res.set_redirect("/2", StatusCode::SeeOther_303);
  2513. })
  2514. .Get("/2",
  2515. [](const Request & /*req*/, Response &res) {
  2516. res.set_content("redirected.", "text/plain");
  2517. res.status = StatusCode::OK_200;
  2518. })
  2519. .Post("/person",
  2520. [&](const Request &req, Response &res) {
  2521. if (req.has_param("name") && req.has_param("note")) {
  2522. persons_[req.get_param_value("name")] =
  2523. req.get_param_value("note");
  2524. } else {
  2525. res.status = StatusCode::BadRequest_400;
  2526. }
  2527. })
  2528. .Put("/person",
  2529. [&](const Request &req, Response &res) {
  2530. if (req.has_param("name") && req.has_param("note")) {
  2531. persons_[req.get_param_value("name")] =
  2532. req.get_param_value("note");
  2533. } else {
  2534. res.status = StatusCode::BadRequest_400;
  2535. }
  2536. })
  2537. .Get("/person/(.*)",
  2538. [&](const Request &req, Response &res) {
  2539. string name = req.matches[1];
  2540. if (persons_.find(name) != persons_.end()) {
  2541. auto note = persons_[name];
  2542. res.set_content(note, "text/plain");
  2543. } else {
  2544. res.status = StatusCode::NotFound_404;
  2545. }
  2546. })
  2547. .Delete("/person",
  2548. [&](const Request &req, Response &res) {
  2549. if (req.has_param("name")) {
  2550. string name = req.get_param_value("name");
  2551. if (persons_.find(name) != persons_.end()) {
  2552. persons_.erase(name);
  2553. res.set_content("DELETED", "text/plain");
  2554. } else {
  2555. res.status = StatusCode::NotFound_404;
  2556. }
  2557. } else {
  2558. res.status = StatusCode::BadRequest_400;
  2559. }
  2560. })
  2561. .Post("/x-www-form-urlencoded-json",
  2562. [&](const Request &req, Response &res) {
  2563. auto json = req.get_param_value("json");
  2564. ASSERT_EQ(JSON_DATA, json);
  2565. res.set_content(json, "appliation/json");
  2566. res.status = StatusCode::OK_200;
  2567. })
  2568. .Get("/streamed-chunked",
  2569. [&](const Request & /*req*/, Response &res) {
  2570. res.set_chunked_content_provider(
  2571. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2572. sink.os << "123";
  2573. sink.os << "456";
  2574. sink.os << "789";
  2575. sink.done();
  2576. return true;
  2577. });
  2578. })
  2579. .Get("/streamed-chunked2",
  2580. [&](const Request & /*req*/, Response &res) {
  2581. auto i = new int(0);
  2582. res.set_chunked_content_provider(
  2583. "text/plain",
  2584. [i](size_t /*offset*/, DataSink &sink) {
  2585. switch (*i) {
  2586. case 0: sink.os << "123"; break;
  2587. case 1: sink.os << "456"; break;
  2588. case 2: sink.os << "789"; break;
  2589. case 3: sink.done(); break;
  2590. }
  2591. (*i)++;
  2592. return true;
  2593. },
  2594. [i](bool success) {
  2595. EXPECT_TRUE(success);
  2596. delete i;
  2597. });
  2598. })
  2599. .Get("/streamed-chunked-with-trailer",
  2600. [&](const Request & /*req*/, Response &res) {
  2601. auto i = new int(0);
  2602. res.set_header("Trailer", "Dummy1, Dummy2");
  2603. res.set_chunked_content_provider(
  2604. "text/plain",
  2605. [i](size_t /*offset*/, DataSink &sink) {
  2606. switch (*i) {
  2607. case 0: sink.os << "123"; break;
  2608. case 1: sink.os << "456"; break;
  2609. case 2: sink.os << "789"; break;
  2610. case 3: {
  2611. sink.done_with_trailer(
  2612. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2613. } break;
  2614. }
  2615. (*i)++;
  2616. return true;
  2617. },
  2618. [i](bool success) {
  2619. EXPECT_TRUE(success);
  2620. delete i;
  2621. });
  2622. })
  2623. .Get("/streamed",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. res.set_content_provider(
  2626. 6, "text/plain",
  2627. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2628. sink.os << (offset < 3 ? "a" : "b");
  2629. return true;
  2630. });
  2631. })
  2632. .Get("/streamed-with-range",
  2633. [&](const Request &req, Response &res) {
  2634. auto data = new std::string("abcdefg");
  2635. res.set_content_provider(
  2636. data->size(), "text/plain",
  2637. [data](size_t offset, size_t length, DataSink &sink) {
  2638. size_t DATA_CHUNK_SIZE = 4;
  2639. const auto &d = *data;
  2640. auto out_len =
  2641. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2642. auto ret =
  2643. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2644. EXPECT_TRUE(ret);
  2645. return true;
  2646. },
  2647. [data, &req](bool success) {
  2648. EXPECT_EQ(success, !req.has_param("error"));
  2649. delete data;
  2650. });
  2651. })
  2652. .Get("/streamed-cancel",
  2653. [&](const Request & /*req*/, Response &res) {
  2654. res.set_content_provider(
  2655. size_t(-1), "text/plain",
  2656. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2657. sink.os << "data_chunk";
  2658. return true;
  2659. });
  2660. })
  2661. .Get("/regex-with-delimiter",
  2662. [&](const Request &req, Response & /*res*/) {
  2663. ASSERT_TRUE(req.has_param("key"));
  2664. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2665. })
  2666. .Get("/with-range",
  2667. [&](const Request & /*req*/, Response &res) {
  2668. res.set_content("abcdefg", "text/plain");
  2669. })
  2670. .Get("/test-start-time",
  2671. [&](const Request &req, Response & /*res*/) {
  2672. EXPECT_NE(req.start_time_,
  2673. std::chrono::steady_clock::time_point::min());
  2674. })
  2675. .Get("/with-range-customized-response",
  2676. [&](const Request & /*req*/, Response &res) {
  2677. res.status = StatusCode::BadRequest_400;
  2678. res.set_content(JSON_DATA, "application/json");
  2679. })
  2680. .Post("/chunked",
  2681. [&](const Request &req, Response & /*res*/) {
  2682. EXPECT_EQ(req.body, "dechunked post body");
  2683. })
  2684. .Post("/large-chunked",
  2685. [&](const Request &req, Response & /*res*/) {
  2686. std::string expected(6 * 30 * 1024u, 'a');
  2687. EXPECT_EQ(req.body, expected);
  2688. })
  2689. .Post("/multipart",
  2690. [&](const Request &req, Response & /*res*/) {
  2691. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2692. req.form.get_field_count("text2") +
  2693. req.form.get_field_count("file3") +
  2694. req.form.get_field_count("file4"));
  2695. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2696. req.form.get_file_count("file2"));
  2697. ASSERT_TRUE(!req.form.has_file("???"));
  2698. ASSERT_TRUE(!req.form.has_field("???"));
  2699. ASSERT_TRUE(req.body.empty());
  2700. {
  2701. const auto &text = req.form.get_field("text1");
  2702. EXPECT_EQ("text default", text);
  2703. }
  2704. {
  2705. const auto &text = req.form.get_field("text2");
  2706. EXPECT_EQ("aωb", text);
  2707. }
  2708. {
  2709. const auto &file = req.form.get_file("file1");
  2710. EXPECT_EQ("hello.txt", file.filename);
  2711. EXPECT_EQ("text/plain", file.content_type);
  2712. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2713. }
  2714. {
  2715. const auto &file = req.form.get_file("file2");
  2716. EXPECT_EQ("world.json", file.filename);
  2717. EXPECT_EQ("application/json", file.content_type);
  2718. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2719. }
  2720. {
  2721. const auto &text = req.form.get_field("file3");
  2722. EXPECT_EQ(0u, text.size());
  2723. }
  2724. {
  2725. const auto &text = req.form.get_field("file4");
  2726. EXPECT_EQ(0u, text.size());
  2727. }
  2728. })
  2729. .Post("/multipart/multi_file_values",
  2730. [&](const Request &req, Response & /*res*/) {
  2731. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2732. req.form.get_field_count("multi_text1"));
  2733. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2734. ASSERT_TRUE(!req.form.has_file("???"));
  2735. ASSERT_TRUE(!req.form.has_field("???"));
  2736. ASSERT_TRUE(req.body.empty());
  2737. {
  2738. const auto &text = req.form.get_field("text");
  2739. EXPECT_EQ("default text", text);
  2740. }
  2741. {
  2742. const auto &text1_values = req.form.get_fields("multi_text1");
  2743. EXPECT_EQ(2u, text1_values.size());
  2744. EXPECT_EQ("aaaaa", text1_values[0]);
  2745. EXPECT_EQ("bbbbb", text1_values[1]);
  2746. }
  2747. {
  2748. const auto &file1_values = req.form.get_files("multi_file1");
  2749. EXPECT_EQ(2u, file1_values.size());
  2750. auto file1 = file1_values[0];
  2751. EXPECT_EQ(file1.filename, "hello.txt");
  2752. EXPECT_EQ(file1.content_type, "text/plain");
  2753. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2754. auto file2 = file1_values[1];
  2755. EXPECT_EQ(file2.filename, "world.json");
  2756. EXPECT_EQ(file2.content_type, "application/json");
  2757. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2758. }
  2759. })
  2760. .Post("/empty",
  2761. [&](const Request &req, Response &res) {
  2762. EXPECT_EQ(req.body, "");
  2763. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2764. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2765. res.set_content("empty", "text/plain");
  2766. })
  2767. .Post("/empty-no-content-type",
  2768. [&](const Request &req, Response &res) {
  2769. EXPECT_EQ(req.body, "");
  2770. EXPECT_FALSE(req.has_header("Content-Type"));
  2771. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2772. res.set_content("empty-no-content-type", "text/plain");
  2773. })
  2774. .Post("/path-only",
  2775. [&](const Request &req, Response &res) {
  2776. EXPECT_EQ(req.body, "");
  2777. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2778. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2779. res.set_content("path-only", "text/plain");
  2780. })
  2781. .Post("/path-headers-only",
  2782. [&](const Request &req, Response &res) {
  2783. EXPECT_EQ(req.body, "");
  2784. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2785. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2786. EXPECT_EQ("world", req.get_header_value("hello"));
  2787. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2788. res.set_content("path-headers-only", "text/plain");
  2789. })
  2790. .Post("/post-large",
  2791. [&](const Request &req, Response &res) {
  2792. EXPECT_EQ(req.body, LARGE_DATA);
  2793. res.set_content(req.body, "text/plain");
  2794. })
  2795. .Put("/empty-no-content-type",
  2796. [&](const Request &req, Response &res) {
  2797. EXPECT_EQ(req.body, "");
  2798. EXPECT_FALSE(req.has_header("Content-Type"));
  2799. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2800. res.set_content("empty-no-content-type", "text/plain");
  2801. })
  2802. .Put("/put",
  2803. [&](const Request &req, Response &res) {
  2804. EXPECT_EQ(req.body, "PUT");
  2805. res.set_content(req.body, "text/plain");
  2806. })
  2807. .Put("/put-large",
  2808. [&](const Request &req, Response &res) {
  2809. EXPECT_EQ(req.body, LARGE_DATA);
  2810. res.set_content(req.body, "text/plain");
  2811. })
  2812. .Patch("/patch",
  2813. [&](const Request &req, Response &res) {
  2814. EXPECT_EQ(req.body, "PATCH");
  2815. res.set_content(req.body, "text/plain");
  2816. })
  2817. .Delete("/delete",
  2818. [&](const Request & /*req*/, Response &res) {
  2819. res.set_content("DELETE", "text/plain");
  2820. })
  2821. .Delete("/delete-body",
  2822. [&](const Request &req, Response &res) {
  2823. EXPECT_EQ(req.body, "content");
  2824. res.set_content(req.body, "text/plain");
  2825. })
  2826. .Options(R"(\*)",
  2827. [&](const Request & /*req*/, Response &res) {
  2828. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2829. })
  2830. .Get("/request-target",
  2831. [&](const Request &req, Response & /*res*/) {
  2832. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2833. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2834. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2835. })
  2836. .Get("/long-query-value",
  2837. [&](const Request &req, Response & /*res*/) {
  2838. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2839. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2840. })
  2841. .Get("/too-long-query-value",
  2842. [&](const Request &req, Response & /*res*/) {
  2843. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2844. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2845. })
  2846. .Get("/array-param",
  2847. [&](const Request &req, Response & /*res*/) {
  2848. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2849. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2850. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2851. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2852. })
  2853. .Post("/validate-no-multiple-headers",
  2854. [&](const Request &req, Response & /*res*/) {
  2855. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2856. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2857. })
  2858. .Post("/content_receiver",
  2859. [&](const Request &req, Response &res,
  2860. const ContentReader &content_reader) {
  2861. if (req.is_multipart_form_data()) {
  2862. std::vector<FormData> items;
  2863. content_reader(
  2864. [&](const FormData &file) {
  2865. items.push_back(file);
  2866. return true;
  2867. },
  2868. [&](const char *data, size_t data_length) {
  2869. items.back().content.append(data, data_length);
  2870. return true;
  2871. });
  2872. EXPECT_EQ(5u, items.size());
  2873. {
  2874. const auto &file = get_file_value(items, "text1");
  2875. EXPECT_TRUE(file.filename.empty());
  2876. EXPECT_EQ("text default", file.content);
  2877. }
  2878. {
  2879. const auto &file = get_file_value(items, "text2");
  2880. EXPECT_TRUE(file.filename.empty());
  2881. EXPECT_EQ("aωb", file.content);
  2882. }
  2883. {
  2884. const auto &file = get_file_value(items, "file1");
  2885. EXPECT_EQ("hello.txt", file.filename);
  2886. EXPECT_EQ("text/plain", file.content_type);
  2887. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2888. }
  2889. {
  2890. const auto &file = get_file_value(items, "file2");
  2891. EXPECT_EQ("world.json", file.filename);
  2892. EXPECT_EQ("application/json", file.content_type);
  2893. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2894. }
  2895. {
  2896. const auto &file = get_file_value(items, "file3");
  2897. EXPECT_TRUE(file.filename.empty());
  2898. EXPECT_EQ("application/octet-stream", file.content_type);
  2899. EXPECT_EQ(0u, file.content.size());
  2900. }
  2901. } else {
  2902. std::string body;
  2903. content_reader([&](const char *data, size_t data_length) {
  2904. EXPECT_EQ(7U, data_length);
  2905. body.append(data, data_length);
  2906. return true;
  2907. });
  2908. EXPECT_EQ(body, "content");
  2909. res.set_content(body, "text/plain");
  2910. }
  2911. })
  2912. .Put("/content_receiver",
  2913. [&](const Request & /*req*/, Response &res,
  2914. const ContentReader &content_reader) {
  2915. std::string body;
  2916. content_reader([&](const char *data, size_t data_length) {
  2917. body.append(data, data_length);
  2918. return true;
  2919. });
  2920. EXPECT_EQ(body, "content");
  2921. res.set_content(body, "text/plain");
  2922. })
  2923. .Patch("/content_receiver",
  2924. [&](const Request & /*req*/, Response &res,
  2925. const ContentReader &content_reader) {
  2926. std::string body;
  2927. content_reader([&](const char *data, size_t data_length) {
  2928. body.append(data, data_length);
  2929. return true;
  2930. });
  2931. EXPECT_EQ(body, "content");
  2932. res.set_content(body, "text/plain");
  2933. })
  2934. .Post("/query-string-and-body",
  2935. [&](const Request &req, Response & /*res*/) {
  2936. ASSERT_TRUE(req.has_param("key"));
  2937. EXPECT_EQ(req.get_param_value("key"), "value");
  2938. EXPECT_EQ(req.body, "content");
  2939. })
  2940. .Get("/last-request",
  2941. [&](const Request &req, Response & /*res*/) {
  2942. EXPECT_EQ("close", req.get_header_value("Connection"));
  2943. })
  2944. .Get(R"(/redirect/(\d+))",
  2945. [&](const Request &req, Response &res) {
  2946. auto num = std::stoi(req.matches[1]) + 1;
  2947. std::string url = "/redirect/" + std::to_string(num);
  2948. res.set_redirect(url);
  2949. })
  2950. .Post("/binary",
  2951. [&](const Request &req, Response &res) {
  2952. EXPECT_EQ(4U, req.body.size());
  2953. EXPECT_EQ("application/octet-stream",
  2954. req.get_header_value("Content-Type"));
  2955. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2956. res.set_content(req.body, "application/octet-stream");
  2957. })
  2958. .Put("/binary",
  2959. [&](const Request &req, Response &res) {
  2960. EXPECT_EQ(4U, req.body.size());
  2961. EXPECT_EQ("application/octet-stream",
  2962. req.get_header_value("Content-Type"));
  2963. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2964. res.set_content(req.body, "application/octet-stream");
  2965. })
  2966. .Patch("/binary",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(4U, req.body.size());
  2969. EXPECT_EQ("application/octet-stream",
  2970. req.get_header_value("Content-Type"));
  2971. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2972. res.set_content(req.body, "application/octet-stream");
  2973. })
  2974. .Delete("/binary",
  2975. [&](const Request &req, Response &res) {
  2976. EXPECT_EQ(4U, req.body.size());
  2977. EXPECT_EQ("application/octet-stream",
  2978. req.get_header_value("Content-Type"));
  2979. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2980. res.set_content(req.body, "application/octet-stream");
  2981. })
  2982. .Get("/issue1772",
  2983. [&](const Request & /*req*/, Response &res) {
  2984. res.status = 401;
  2985. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2986. })
  2987. .Delete("/issue609",
  2988. [](const httplib::Request &, httplib::Response &res,
  2989. const httplib::ContentReader &) {
  2990. res.set_content("ok", "text/plain");
  2991. })
  2992. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  2993. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  2994. .Get("/compress",
  2995. [&](const Request & /*req*/, Response &res) {
  2996. res.set_content(
  2997. "12345678901234567890123456789012345678901234567890123456789"
  2998. "01234567890123456789012345678901234567890",
  2999. "text/plain");
  3000. })
  3001. .Get("/nocompress",
  3002. [&](const Request & /*req*/, Response &res) {
  3003. res.set_content(
  3004. "12345678901234567890123456789012345678901234567890123456789"
  3005. "01234567890123456789012345678901234567890",
  3006. "application/octet-stream");
  3007. })
  3008. .Post("/compress-multipart",
  3009. [&](const Request &req, Response & /*res*/) {
  3010. EXPECT_EQ(2u, req.form.fields.size());
  3011. ASSERT_TRUE(!req.form.has_field("???"));
  3012. {
  3013. const auto &text = req.form.get_field("key1");
  3014. EXPECT_EQ("test", text);
  3015. }
  3016. {
  3017. const auto &text = req.form.get_field("key2");
  3018. EXPECT_EQ("--abcdefg123", text);
  3019. }
  3020. })
  3021. #endif
  3022. ;
  3023. persons_["john"] = "programmer";
  3024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3025. svr_.wait_until_ready();
  3026. }
  3027. virtual void TearDown() {
  3028. svr_.stop();
  3029. if (!request_threads_.empty()) {
  3030. std::this_thread::sleep_for(std::chrono::seconds(1));
  3031. for (auto &t : request_threads_) {
  3032. t.join();
  3033. }
  3034. }
  3035. t_.join();
  3036. }
  3037. map<string, string> persons_;
  3038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3039. SSLClient cli_;
  3040. SSLServer svr_;
  3041. #else
  3042. Client cli_;
  3043. Server svr_;
  3044. #endif
  3045. thread t_;
  3046. std::vector<thread> request_threads_;
  3047. };
  3048. TEST_F(ServerTest, GetMethod200) {
  3049. auto res = cli_.Get("/hi");
  3050. ASSERT_TRUE(res);
  3051. EXPECT_EQ("HTTP/1.1", res->version);
  3052. EXPECT_EQ(StatusCode::OK_200, res->status);
  3053. EXPECT_EQ("OK", res->reason);
  3054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3055. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3056. EXPECT_EQ("Hello World!", res->body);
  3057. }
  3058. void performance_test(const char *host) {
  3059. auto port = 1234;
  3060. Server svr;
  3061. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  3062. res.set_content("Benchmark Response", "text/plain");
  3063. });
  3064. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  3065. auto se = detail::scope_exit([&] {
  3066. svr.stop();
  3067. listen_thread.join();
  3068. ASSERT_FALSE(svr.is_running());
  3069. });
  3070. svr.wait_until_ready();
  3071. Client cli(host, port);
  3072. auto start = std::chrono::high_resolution_clock::now();
  3073. auto res = cli.Get("/benchmark");
  3074. ASSERT_TRUE(res);
  3075. EXPECT_EQ(StatusCode::OK_200, res->status);
  3076. auto end = std::chrono::high_resolution_clock::now();
  3077. auto elapsed =
  3078. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3079. .count();
  3080. EXPECT_LE(elapsed, 5) << "Performance is too slow: " << elapsed
  3081. << "ms (Issue #1777)";
  3082. }
  3083. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  3084. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  3085. TEST_F(ServerTest, GetEmptyFile) {
  3086. auto res = cli_.Get("/empty_file");
  3087. ASSERT_TRUE(res);
  3088. EXPECT_EQ(StatusCode::OK_200, res->status);
  3089. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3090. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3091. EXPECT_EQ("", res->body);
  3092. }
  3093. TEST_F(ServerTest, GetFileContent) {
  3094. auto res = cli_.Get("/file_content");
  3095. ASSERT_TRUE(res);
  3096. EXPECT_EQ(StatusCode::OK_200, res->status);
  3097. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3098. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3099. EXPECT_EQ("test.html", res->body);
  3100. }
  3101. TEST_F(ServerTest, GetFileContentWithRange) {
  3102. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3103. ASSERT_TRUE(res);
  3104. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3105. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3106. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3107. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3108. EXPECT_EQ("est", res->body);
  3109. }
  3110. TEST_F(ServerTest, GetFileContentWithContentType) {
  3111. auto res = cli_.Get("/file_content_with_content_type");
  3112. ASSERT_TRUE(res);
  3113. EXPECT_EQ(StatusCode::OK_200, res->status);
  3114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3115. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3116. EXPECT_EQ("file\n", res->body);
  3117. }
  3118. TEST_F(ServerTest, GetInvalidFileContent) {
  3119. auto res = cli_.Get("/invalid_file_content");
  3120. ASSERT_TRUE(res);
  3121. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3122. }
  3123. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3124. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3125. ASSERT_TRUE(res);
  3126. EXPECT_EQ("HTTP/1.1", res->version);
  3127. EXPECT_EQ(StatusCode::OK_200, res->status);
  3128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3129. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3130. EXPECT_EQ("Hello World!", res->body);
  3131. }
  3132. TEST_F(ServerTest, GetMethod302) {
  3133. auto res = cli_.Get("/");
  3134. ASSERT_TRUE(res);
  3135. EXPECT_EQ(StatusCode::Found_302, res->status);
  3136. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3137. }
  3138. TEST_F(ServerTest, GetMethod302Redirect) {
  3139. cli_.set_follow_location(true);
  3140. auto res = cli_.Get("/");
  3141. ASSERT_TRUE(res);
  3142. EXPECT_EQ(StatusCode::OK_200, res->status);
  3143. EXPECT_EQ("Hello World!", res->body);
  3144. EXPECT_EQ("/hi", res->location);
  3145. }
  3146. TEST_F(ServerTest, GetMethod404) {
  3147. auto res = cli_.Get("/invalid");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3150. }
  3151. TEST_F(ServerTest, HeadMethod200) {
  3152. auto res = cli_.Head("/hi");
  3153. ASSERT_TRUE(res);
  3154. EXPECT_EQ(StatusCode::OK_200, res->status);
  3155. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3156. EXPECT_TRUE(res->body.empty());
  3157. }
  3158. TEST_F(ServerTest, HeadMethod200Static) {
  3159. auto res = cli_.Head("/mount/dir/index.html");
  3160. ASSERT_TRUE(res);
  3161. EXPECT_EQ(StatusCode::OK_200, res->status);
  3162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3163. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3164. EXPECT_TRUE(res->body.empty());
  3165. }
  3166. TEST_F(ServerTest, HeadMethod404) {
  3167. auto res = cli_.Head("/invalid");
  3168. ASSERT_TRUE(res);
  3169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3170. EXPECT_TRUE(res->body.empty());
  3171. }
  3172. TEST_F(ServerTest, GetMethodPersonJohn) {
  3173. auto res = cli_.Get("/person/john");
  3174. ASSERT_TRUE(res);
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3177. EXPECT_EQ("programmer", res->body);
  3178. }
  3179. TEST_F(ServerTest, PostMethod1) {
  3180. auto res = cli_.Get("/person/john1");
  3181. ASSERT_TRUE(res);
  3182. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3183. res = cli_.Post("/person", "name=john1&note=coder",
  3184. "application/x-www-form-urlencoded");
  3185. ASSERT_TRUE(res);
  3186. ASSERT_EQ(StatusCode::OK_200, res->status);
  3187. res = cli_.Get("/person/john1");
  3188. ASSERT_TRUE(res);
  3189. ASSERT_EQ(StatusCode::OK_200, res->status);
  3190. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3191. ASSERT_EQ("coder", res->body);
  3192. }
  3193. TEST_F(ServerTest, PostMethod2) {
  3194. auto res = cli_.Get("/person/john2");
  3195. ASSERT_TRUE(res);
  3196. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3197. Params params;
  3198. params.emplace("name", "john2");
  3199. params.emplace("note", "coder");
  3200. res = cli_.Post("/person", params);
  3201. ASSERT_TRUE(res);
  3202. ASSERT_EQ(StatusCode::OK_200, res->status);
  3203. res = cli_.Get("/person/john2");
  3204. ASSERT_TRUE(res);
  3205. ASSERT_EQ(StatusCode::OK_200, res->status);
  3206. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3207. ASSERT_EQ("coder", res->body);
  3208. }
  3209. TEST_F(ServerTest, PutMethod3) {
  3210. auto res = cli_.Get("/person/john3");
  3211. ASSERT_TRUE(res);
  3212. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3213. Params params;
  3214. params.emplace("name", "john3");
  3215. params.emplace("note", "coder");
  3216. res = cli_.Put("/person", params);
  3217. ASSERT_TRUE(res);
  3218. ASSERT_EQ(StatusCode::OK_200, res->status);
  3219. res = cli_.Get("/person/john3");
  3220. ASSERT_TRUE(res);
  3221. ASSERT_EQ(StatusCode::OK_200, res->status);
  3222. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3223. ASSERT_EQ("coder", res->body);
  3224. }
  3225. TEST_F(ServerTest, DeleteMethod1) {
  3226. auto res = cli_.Get("/person/john4");
  3227. ASSERT_TRUE(res);
  3228. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3229. Params params;
  3230. params.emplace("name", "john4");
  3231. params.emplace("note", "coder");
  3232. res = cli_.Post("/person", params);
  3233. ASSERT_TRUE(res);
  3234. ASSERT_EQ(StatusCode::OK_200, res->status);
  3235. res = cli_.Get("/person/john4");
  3236. ASSERT_TRUE(res);
  3237. ASSERT_EQ(StatusCode::OK_200, res->status);
  3238. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3239. ASSERT_EQ("coder", res->body);
  3240. Params delete_params;
  3241. delete_params.emplace("name", "john4");
  3242. res = cli_.Delete("/person", delete_params);
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ("DELETED", res->body);
  3246. res = cli_.Get("/person/john4");
  3247. ASSERT_TRUE(res);
  3248. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3249. }
  3250. TEST_F(ServerTest, DeleteMethod2) {
  3251. auto res = cli_.Get("/person/john5");
  3252. ASSERT_TRUE(res);
  3253. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3254. Params params;
  3255. params.emplace("name", "john5");
  3256. params.emplace("note", "developer");
  3257. res = cli_.Post("/person", params);
  3258. ASSERT_TRUE(res);
  3259. ASSERT_EQ(StatusCode::OK_200, res->status);
  3260. res = cli_.Get("/person/john5");
  3261. ASSERT_TRUE(res);
  3262. ASSERT_EQ(StatusCode::OK_200, res->status);
  3263. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3264. ASSERT_EQ("developer", res->body);
  3265. Params delete_params;
  3266. delete_params.emplace("name", "john5");
  3267. Headers headers;
  3268. headers.emplace("Custom-Header", "test-value");
  3269. res = cli_.Delete("/person", headers, delete_params);
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. ASSERT_EQ("DELETED", res->body);
  3273. res = cli_.Get("/person/john5");
  3274. ASSERT_TRUE(res);
  3275. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3276. }
  3277. TEST_F(ServerTest, DeleteMethod3) {
  3278. auto res = cli_.Get("/person/john6");
  3279. ASSERT_TRUE(res);
  3280. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3281. Params params;
  3282. params.emplace("name", "john6");
  3283. params.emplace("note", "tester");
  3284. res = cli_.Post("/person", params);
  3285. ASSERT_TRUE(res);
  3286. ASSERT_EQ(StatusCode::OK_200, res->status);
  3287. res = cli_.Get("/person/john6");
  3288. ASSERT_TRUE(res);
  3289. ASSERT_EQ(StatusCode::OK_200, res->status);
  3290. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3291. ASSERT_EQ("tester", res->body);
  3292. Params delete_params;
  3293. delete_params.emplace("name", "john6");
  3294. Headers headers;
  3295. headers.emplace("Custom-Header", "test-value");
  3296. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3297. ASSERT_TRUE(res);
  3298. ASSERT_EQ(StatusCode::OK_200, res->status);
  3299. ASSERT_EQ("DELETED", res->body);
  3300. res = cli_.Get("/person/john6");
  3301. ASSERT_TRUE(res);
  3302. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3303. }
  3304. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3305. Params params;
  3306. params.emplace("json", JSON_DATA);
  3307. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. ASSERT_EQ(JSON_DATA, res->body);
  3311. }
  3312. TEST_F(ServerTest, PostEmptyContent) {
  3313. auto res = cli_.Post("/empty", "", "text/plain");
  3314. ASSERT_TRUE(res);
  3315. ASSERT_EQ(StatusCode::OK_200, res->status);
  3316. ASSERT_EQ("empty", res->body);
  3317. }
  3318. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3319. auto res = cli_.Post("/empty-no-content-type");
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::OK_200, res->status);
  3322. ASSERT_EQ("empty-no-content-type", res->body);
  3323. }
  3324. TEST_F(ServerTest, PostPathOnly) {
  3325. auto res = cli_.Post("/path-only");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::OK_200, res->status);
  3328. ASSERT_EQ("path-only", res->body);
  3329. }
  3330. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3331. auto res = cli_.Post("/path-headers-only",
  3332. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3333. ASSERT_TRUE(res);
  3334. ASSERT_EQ(StatusCode::OK_200, res->status);
  3335. ASSERT_EQ("path-headers-only", res->body);
  3336. }
  3337. TEST_F(ServerTest, PostLarge) {
  3338. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3339. ASSERT_TRUE(res);
  3340. ASSERT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ(LARGE_DATA, res->body);
  3342. }
  3343. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3344. auto res = cli_.Put("/empty-no-content-type");
  3345. ASSERT_TRUE(res);
  3346. ASSERT_EQ(StatusCode::OK_200, res->status);
  3347. ASSERT_EQ("empty-no-content-type", res->body);
  3348. }
  3349. TEST_F(ServerTest, GetMethodDir) {
  3350. auto res = cli_.Get("/dir/");
  3351. ASSERT_TRUE(res);
  3352. EXPECT_EQ(StatusCode::OK_200, res->status);
  3353. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3354. auto body = R"(<html>
  3355. <head>
  3356. </head>
  3357. <body>
  3358. <a href="/dir/test.html">Test</a>
  3359. <a href="/hi">hi</a>
  3360. </body>
  3361. </html>
  3362. )";
  3363. EXPECT_EQ(body, res->body);
  3364. }
  3365. TEST_F(ServerTest, GetMethodDirTest) {
  3366. auto res = cli_.Get("/dir/test.html");
  3367. ASSERT_TRUE(res);
  3368. EXPECT_EQ(StatusCode::OK_200, res->status);
  3369. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3370. EXPECT_EQ("test.html", res->body);
  3371. }
  3372. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3373. auto res = cli_.Get("/dir/../dir/test.html");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3377. EXPECT_EQ("test.html", res->body);
  3378. }
  3379. TEST_F(ServerTest, GetMethodInvalidPath) {
  3380. auto res = cli_.Get("/dir/../test.html");
  3381. ASSERT_TRUE(res);
  3382. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3383. }
  3384. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3385. auto res = cli_.Get("/../www/dir/test.html");
  3386. ASSERT_TRUE(res);
  3387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3388. }
  3389. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3390. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3391. ASSERT_TRUE(res);
  3392. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3393. }
  3394. TEST_F(ServerTest, GetMethodDirMountTest) {
  3395. auto res = cli_.Get("/mount/dir/test.html");
  3396. ASSERT_TRUE(res);
  3397. EXPECT_EQ(StatusCode::OK_200, res->status);
  3398. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3399. EXPECT_EQ("test.html", res->body);
  3400. }
  3401. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3402. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3406. EXPECT_EQ("test.html", res->body);
  3407. }
  3408. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3409. auto res = cli_.Get("/mount/dir/../test.html");
  3410. ASSERT_TRUE(res);
  3411. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3412. }
  3413. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3414. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3415. ASSERT_TRUE(res);
  3416. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3417. }
  3418. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3419. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3422. }
  3423. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3424. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3425. ASSERT_TRUE(res);
  3426. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3427. }
  3428. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3429. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3430. ASSERT_TRUE(res);
  3431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3432. }
  3433. TEST_F(ServerTest, PostMethod303) {
  3434. auto res = cli_.Post("/1", "body", "text/plain");
  3435. ASSERT_TRUE(res);
  3436. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3437. EXPECT_EQ("/2", res->get_header_value("Location"));
  3438. }
  3439. TEST_F(ServerTest, PostMethod303Redirect) {
  3440. cli_.set_follow_location(true);
  3441. auto res = cli_.Post("/1", "body", "text/plain");
  3442. ASSERT_TRUE(res);
  3443. EXPECT_EQ(StatusCode::OK_200, res->status);
  3444. EXPECT_EQ("redirected.", res->body);
  3445. EXPECT_EQ("/2", res->location);
  3446. }
  3447. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3448. auto res = cli_.Get("/dir/test.abcde");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ("abcde", res->body);
  3453. }
  3454. TEST_F(ServerTest, StaticFileRange) {
  3455. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3458. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3460. EXPECT_EQ(true, res->has_header("Content-Range"));
  3461. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3462. EXPECT_EQ(std::string("cd"), res->body);
  3463. }
  3464. TEST_F(ServerTest, StaticFileRanges) {
  3465. auto res =
  3466. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3467. ASSERT_TRUE(res);
  3468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3469. EXPECT_TRUE(
  3470. res->get_header_value("Content-Type")
  3471. .find(
  3472. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3473. 0);
  3474. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3475. }
  3476. TEST_F(ServerTest, StaticFileRangeHead) {
  3477. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3480. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3481. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3482. EXPECT_EQ(true, res->has_header("Content-Range"));
  3483. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3484. }
  3485. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3486. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3487. ASSERT_TRUE(res);
  3488. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3490. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3491. EXPECT_EQ(true, res->has_header("Content-Range"));
  3492. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3493. res->get_header_value("Content-Range"));
  3494. EXPECT_EQ("LAST\n", res->body);
  3495. }
  3496. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3497. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3500. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3501. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3502. EXPECT_EQ(true, res->has_header("Content-Range"));
  3503. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3504. }
  3505. TEST_F(ServerTest, StaticFileBigFile) {
  3506. auto res = cli_.Get("/dir/1MB.txt");
  3507. ASSERT_TRUE(res);
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3510. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3511. }
  3512. TEST_F(ServerTest, InvalidBaseDirMount) {
  3513. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3514. }
  3515. TEST_F(ServerTest, Binary) {
  3516. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3517. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3518. "application/octet-stream");
  3519. ASSERT_TRUE(res);
  3520. ASSERT_EQ(StatusCode::OK_200, res->status);
  3521. ASSERT_EQ(4U, res->body.size());
  3522. res = cli_.Put("/binary", binary.data(), binary.size(),
  3523. "application/octet-stream");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ(4U, res->body.size());
  3527. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3528. "application/octet-stream");
  3529. ASSERT_TRUE(res);
  3530. ASSERT_EQ(StatusCode::OK_200, res->status);
  3531. ASSERT_EQ(4U, res->body.size());
  3532. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3533. "application/octet-stream");
  3534. ASSERT_TRUE(res);
  3535. ASSERT_EQ(StatusCode::OK_200, res->status);
  3536. ASSERT_EQ(4U, res->body.size());
  3537. }
  3538. TEST_F(ServerTest, BinaryString) {
  3539. auto binary = std::string("\x00\x01\x02\x03", 4);
  3540. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3541. ASSERT_TRUE(res);
  3542. ASSERT_EQ(StatusCode::OK_200, res->status);
  3543. ASSERT_EQ(4U, res->body.size());
  3544. res = cli_.Put("/binary", binary, "application/octet-stream");
  3545. ASSERT_TRUE(res);
  3546. ASSERT_EQ(StatusCode::OK_200, res->status);
  3547. ASSERT_EQ(4U, res->body.size());
  3548. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3549. ASSERT_TRUE(res);
  3550. ASSERT_EQ(StatusCode::OK_200, res->status);
  3551. ASSERT_EQ(4U, res->body.size());
  3552. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3553. ASSERT_TRUE(res);
  3554. ASSERT_EQ(StatusCode::OK_200, res->status);
  3555. ASSERT_EQ(4U, res->body.size());
  3556. }
  3557. TEST_F(ServerTest, EmptyRequest) {
  3558. auto res = cli_.Get("");
  3559. ASSERT_TRUE(!res);
  3560. EXPECT_EQ(Error::Connection, res.error());
  3561. }
  3562. TEST_F(ServerTest, LongRequest) {
  3563. std::string request;
  3564. for (size_t i = 0; i < 545; i++) {
  3565. request += "/TooLongRequest";
  3566. }
  3567. request += "OK";
  3568. auto res = cli_.Get(request.c_str());
  3569. ASSERT_TRUE(res);
  3570. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3571. }
  3572. TEST_F(ServerTest, TooLongRequest) {
  3573. std::string request;
  3574. for (size_t i = 0; i < 546; i++) {
  3575. request += "/TooLongRequest";
  3576. }
  3577. request += "_NG";
  3578. auto res = cli_.Get(request.c_str());
  3579. ASSERT_TRUE(res);
  3580. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3581. }
  3582. TEST_F(ServerTest, AlmostTooLongRequest) {
  3583. // test for #2046 - URI length check shouldn't include other content on req
  3584. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3585. // leading /, space, HTTP/1.1)
  3586. std::string request =
  3587. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3588. auto res = cli_.Get(request.c_str());
  3589. ASSERT_TRUE(res);
  3590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3591. }
  3592. TEST_F(ServerTest, LongHeader) {
  3593. Request req;
  3594. req.method = "GET";
  3595. req.path = "/hi";
  3596. std::string host_and_port;
  3597. host_and_port += HOST;
  3598. host_and_port += ":";
  3599. host_and_port += std::to_string(PORT);
  3600. req.headers.emplace("Host", host_and_port.c_str());
  3601. req.headers.emplace("Accept", "*/*");
  3602. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3603. req.headers.emplace(
  3604. "Header-Name",
  3605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3631. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3632. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3633. "@@@@@@@@@@@@@@@@");
  3634. auto res = std::make_shared<Response>();
  3635. auto error = Error::Success;
  3636. auto ret = cli_.send(req, *res, error);
  3637. ASSERT_TRUE(ret);
  3638. EXPECT_EQ(StatusCode::OK_200, res->status);
  3639. }
  3640. TEST_F(ServerTest, LongQueryValue) {
  3641. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3642. ASSERT_TRUE(res);
  3643. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3644. }
  3645. TEST_F(ServerTest, TooLongQueryValue) {
  3646. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3647. ASSERT_FALSE(res);
  3648. EXPECT_EQ(Error::Read, res.error());
  3649. }
  3650. TEST_F(ServerTest, TooLongHeader) {
  3651. Request req;
  3652. req.method = "GET";
  3653. req.path = "/hi";
  3654. std::string host_and_port;
  3655. host_and_port += HOST;
  3656. host_and_port += ":";
  3657. host_and_port += std::to_string(PORT);
  3658. req.headers.emplace("Host", host_and_port.c_str());
  3659. req.headers.emplace("Accept", "*/*");
  3660. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3661. req.headers.emplace(
  3662. "Header-Name",
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@");
  3692. auto res = std::make_shared<Response>();
  3693. auto error = Error::Success;
  3694. auto ret = cli_.send(req, *res, error);
  3695. ASSERT_TRUE(ret);
  3696. EXPECT_EQ(StatusCode::OK_200, res->status);
  3697. }
  3698. TEST_F(ServerTest, HeaderCountAtLimit) {
  3699. // Test with headers just under the 100 limit
  3700. httplib::Headers headers;
  3701. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3702. // This should keep us just under the 100 header limit
  3703. for (int i = 0; i < 95; i++) {
  3704. std::string name = "X-Test-Header-" + std::to_string(i);
  3705. std::string value = "value" + std::to_string(i);
  3706. headers.emplace(name, value);
  3707. }
  3708. // This should work fine as we're under the limit
  3709. auto res = cli_.Get("/hi", headers);
  3710. EXPECT_TRUE(res);
  3711. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3712. }
  3713. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3714. // Test with many headers to exceed the 100 limit
  3715. httplib::Headers headers;
  3716. // Add 150 headers to definitely exceed the 100 limit
  3717. for (int i = 0; i < 150; i++) {
  3718. std::string name = "X-Test-Header-" + std::to_string(i);
  3719. std::string value = "value" + std::to_string(i);
  3720. headers.emplace(name, value);
  3721. }
  3722. // This should fail due to exceeding header count limit
  3723. auto res = cli_.Get("/hi", headers);
  3724. // The request should either fail or return 400 Bad Request
  3725. if (res) {
  3726. // If we get a response, it should be 400 Bad Request
  3727. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3728. } else {
  3729. // Or the request should fail entirely
  3730. EXPECT_FALSE(res);
  3731. }
  3732. }
  3733. TEST_F(ServerTest, PercentEncoding) {
  3734. auto res = cli_.Get("/e%6edwith%");
  3735. ASSERT_TRUE(res);
  3736. EXPECT_EQ(StatusCode::OK_200, res->status);
  3737. }
  3738. TEST_F(ServerTest, PercentEncodingUnicode) {
  3739. auto res = cli_.Get("/e%u006edwith%");
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. }
  3743. TEST_F(ServerTest, InvalidPercentEncoding) {
  3744. auto res = cli_.Get("/%endwith%");
  3745. ASSERT_TRUE(res);
  3746. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3747. }
  3748. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3749. auto res = cli_.Get("/%uendwith%");
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3752. }
  3753. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3754. auto res = cli_.Get("/hello?aaa=bbb%");
  3755. ASSERT_TRUE(res);
  3756. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3757. }
  3758. TEST_F(ServerTest, PlusSignEncoding) {
  3759. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3760. ASSERT_TRUE(res);
  3761. EXPECT_EQ(StatusCode::OK_200, res->status);
  3762. EXPECT_EQ("a +b", res->body);
  3763. }
  3764. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3765. // This test simulates a potential DoS attack using many headers
  3766. // to verify our security fix prevents memory exhaustion
  3767. httplib::Headers attack_headers;
  3768. // Attempt to add many headers like an attacker would (200 headers to far
  3769. // exceed limit)
  3770. for (int i = 0; i < 200; i++) {
  3771. std::string name = "X-Attack-Header-" + std::to_string(i);
  3772. std::string value = "attack_payload_" + std::to_string(i);
  3773. attack_headers.emplace(name, value);
  3774. }
  3775. // Try to POST with excessive headers
  3776. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3777. // Should either fail or return 400 Bad Request due to security limit
  3778. if (res) {
  3779. // If we get a response, it should be 400 Bad Request
  3780. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3781. } else {
  3782. // Request failed, which is the expected behavior for DoS protection
  3783. EXPECT_FALSE(res);
  3784. }
  3785. }
  3786. TEST_F(ServerTest, MultipartFormData) {
  3787. UploadFormDataItems items = {
  3788. {"text1", "text default", "", ""},
  3789. {"text2", "aωb", "", ""},
  3790. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3791. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3792. {"file3", "", "", "application/octet-stream"},
  3793. {"file4", "", "", " application/json tmp-string "}};
  3794. auto res = cli_.Post("/multipart", items);
  3795. ASSERT_TRUE(res);
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. }
  3798. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3799. UploadFormDataItems items = {
  3800. {"text", "default text", "", ""},
  3801. {"multi_text1", "aaaaa", "", ""},
  3802. {"multi_text1", "bbbbb", "", ""},
  3803. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3804. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3805. "application/json"},
  3806. };
  3807. auto res = cli_.Post("/multipart/multi_file_values", items);
  3808. ASSERT_TRUE(res);
  3809. EXPECT_EQ(StatusCode::OK_200, res->status);
  3810. }
  3811. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3812. auto res = cli_.Get("/hi");
  3813. ASSERT_TRUE(res);
  3814. EXPECT_EQ(StatusCode::OK_200, res->status);
  3815. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3816. EXPECT_EQ("Hello World!", res->body);
  3817. }
  3818. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3819. Request req;
  3820. req.method = "POST";
  3821. req.path = "/chunked";
  3822. std::string host_and_port;
  3823. host_and_port += HOST;
  3824. host_and_port += ":";
  3825. host_and_port += std::to_string(PORT);
  3826. req.headers.emplace("Host", host_and_port.c_str());
  3827. req.headers.emplace("Accept", "*/*");
  3828. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3829. req.headers.emplace("Content-Type", "text/plain");
  3830. req.headers.emplace("Content-Length", "0");
  3831. req.headers.emplace(
  3832. "Transfer-Encoding",
  3833. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3834. // Client does not chunk, so make a chunked body manually.
  3835. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3836. auto res = std::make_shared<Response>();
  3837. auto error = Error::Success;
  3838. auto ret = cli_.send(req, *res, error);
  3839. ASSERT_TRUE(ret);
  3840. EXPECT_EQ(StatusCode::OK_200, res->status);
  3841. }
  3842. TEST_F(ServerTest, GetStreamed2) {
  3843. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3844. ASSERT_TRUE(res);
  3845. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3846. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3847. EXPECT_EQ(true, res->has_header("Content-Range"));
  3848. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3849. EXPECT_EQ(std::string("ab"), res->body);
  3850. }
  3851. TEST_F(ServerTest, GetStreamed) {
  3852. auto res = cli_.Get("/streamed");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::OK_200, res->status);
  3855. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3856. EXPECT_EQ(std::string("aaabbb"), res->body);
  3857. }
  3858. TEST_F(ServerTest, GetStreamedWithRange1) {
  3859. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3862. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3863. EXPECT_EQ(true, res->has_header("Content-Range"));
  3864. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3865. EXPECT_EQ(std::string("def"), res->body);
  3866. }
  3867. TEST_F(ServerTest, GetStreamedWithRange2) {
  3868. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3871. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3872. EXPECT_EQ(true, res->has_header("Content-Range"));
  3873. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3874. EXPECT_EQ(std::string("bcdefg"), res->body);
  3875. }
  3876. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3877. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3880. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3881. EXPECT_EQ(true, res->has_header("Content-Range"));
  3882. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3883. EXPECT_EQ(std::string("efg"), res->body);
  3884. }
  3885. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3886. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3889. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3890. EXPECT_EQ(false, res->has_header("Content-Range"));
  3891. EXPECT_EQ(0U, res->body.size());
  3892. }
  3893. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3894. auto res = cli_.Get("/streamed-with-range",
  3895. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3896. "92233720368547758079223372036854775807"}});
  3897. ASSERT_TRUE(res);
  3898. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3899. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3900. EXPECT_EQ(false, res->has_header("Content-Range"));
  3901. EXPECT_EQ(0U, res->body.size());
  3902. }
  3903. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3904. auto res = cli_.Get(
  3905. "/with-range",
  3906. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3907. {"Accept-Encoding", ""}});
  3908. ASSERT_TRUE(res);
  3909. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3910. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3911. EXPECT_EQ(true, res->has_header("Content-Range"));
  3912. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3913. EXPECT_EQ(std::string("abcdefg"), res->body);
  3914. }
  3915. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3916. auto res = cli_.Get("/with-range", {
  3917. {"Range", "bytes=0-"},
  3918. {"Accept-Encoding", ""},
  3919. });
  3920. ASSERT_TRUE(res);
  3921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3922. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3923. EXPECT_EQ(true, res->has_header("Content-Range"));
  3924. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3925. EXPECT_EQ(std::string("abcdefg"), res->body);
  3926. }
  3927. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3928. auto res =
  3929. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3930. ASSERT_TRUE(res);
  3931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3932. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3933. EXPECT_EQ(false, res->has_header("Content-Range"));
  3934. EXPECT_EQ(267U, res->body.size());
  3935. // Check that both range contents are present
  3936. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3937. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3938. // Check that Content-Range headers are present for both ranges
  3939. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3940. std::string::npos);
  3941. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3942. std::string::npos);
  3943. }
  3944. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3945. Ranges ranges;
  3946. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3947. ranges.emplace_back(0, -1);
  3948. }
  3949. auto res =
  3950. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3951. ASSERT_TRUE(res);
  3952. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3953. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3954. EXPECT_EQ(false, res->has_header("Content-Range"));
  3955. EXPECT_EQ(0U, res->body.size());
  3956. }
  3957. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  3958. auto res =
  3959. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3962. EXPECT_EQ(5U, res->body.size());
  3963. // Check that overlapping ranges are coalesced into a single range
  3964. EXPECT_EQ("bcdef", res->body);
  3965. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  3966. // Should be single range, not multipart
  3967. EXPECT_TRUE(res->has_header("Content-Range"));
  3968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3971. auto res =
  3972. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  3973. ASSERT_TRUE(res);
  3974. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3975. EXPECT_EQ(268U, res->body.size());
  3976. // Check that both range contents are present
  3977. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3978. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  3979. // Check that Content-Range headers are present for both ranges
  3980. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3981. std::string::npos);
  3982. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  3983. std::string::npos);
  3984. }
  3985. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  3986. auto res =
  3987. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  3988. ASSERT_TRUE(res);
  3989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3990. EXPECT_EQ(269U, res->body.size());
  3991. // Check that both duplicate range contents are present
  3992. size_t first_abc = res->body.find("abc\r\n");
  3993. EXPECT_TRUE(first_abc != std::string::npos);
  3994. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  3995. EXPECT_TRUE(second_abc != std::string::npos);
  3996. // Check that Content-Range headers are present for both ranges
  3997. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  3998. EXPECT_TRUE(first_range != std::string::npos);
  3999. size_t second_range =
  4000. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4001. EXPECT_TRUE(second_range != std::string::npos);
  4002. }
  4003. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4004. auto res = cli_.Get("/streamed-with-range?error",
  4005. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4006. ASSERT_TRUE(res);
  4007. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4008. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4009. EXPECT_EQ(false, res->has_header("Content-Range"));
  4010. EXPECT_EQ(0U, res->body.size());
  4011. }
  4012. TEST_F(ServerTest, GetStreamedEndless) {
  4013. uint64_t offset = 0;
  4014. auto res = cli_.Get("/streamed-cancel",
  4015. [&](const char * /*data*/, uint64_t data_length) {
  4016. if (offset < 100) {
  4017. offset += data_length;
  4018. return true;
  4019. }
  4020. return false;
  4021. });
  4022. ASSERT_TRUE(!res);
  4023. EXPECT_EQ(Error::Canceled, res.error());
  4024. }
  4025. TEST_F(ServerTest, ClientStop) {
  4026. std::atomic_size_t count{4};
  4027. std::vector<std::thread> threads;
  4028. for (auto i = count.load(); i != 0; --i) {
  4029. threads.emplace_back([&]() {
  4030. auto res = cli_.Get("/streamed-cancel",
  4031. [&](const char *, uint64_t) { return true; });
  4032. --count;
  4033. ASSERT_TRUE(!res);
  4034. EXPECT_TRUE(res.error() == Error::Canceled ||
  4035. res.error() == Error::Read || res.error() == Error::Write);
  4036. });
  4037. }
  4038. std::this_thread::sleep_for(std::chrono::seconds(2));
  4039. while (count != 0) {
  4040. cli_.stop();
  4041. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4042. }
  4043. for (auto &t : threads) {
  4044. t.join();
  4045. }
  4046. }
  4047. TEST_F(ServerTest, GetWithRange1) {
  4048. auto res = cli_.Get("/with-range", {
  4049. make_range_header({{3, 5}}),
  4050. {"Accept-Encoding", ""},
  4051. });
  4052. ASSERT_TRUE(res);
  4053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4054. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4055. EXPECT_EQ(true, res->has_header("Content-Range"));
  4056. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4057. EXPECT_EQ(std::string("def"), res->body);
  4058. }
  4059. TEST_F(ServerTest, GetWithRange2) {
  4060. auto res = cli_.Get("/with-range", {
  4061. make_range_header({{1, -1}}),
  4062. {"Accept-Encoding", ""},
  4063. });
  4064. ASSERT_TRUE(res);
  4065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4066. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4067. EXPECT_EQ(true, res->has_header("Content-Range"));
  4068. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4069. EXPECT_EQ(std::string("bcdefg"), res->body);
  4070. }
  4071. TEST_F(ServerTest, GetWithRange3) {
  4072. auto res = cli_.Get("/with-range", {
  4073. make_range_header({{0, 0}}),
  4074. {"Accept-Encoding", ""},
  4075. });
  4076. ASSERT_TRUE(res);
  4077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4078. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4079. EXPECT_EQ(true, res->has_header("Content-Range"));
  4080. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4081. EXPECT_EQ(std::string("a"), res->body);
  4082. }
  4083. TEST_F(ServerTest, GetWithRange4) {
  4084. auto res = cli_.Get("/with-range", {
  4085. make_range_header({{-1, 2}}),
  4086. {"Accept-Encoding", ""},
  4087. });
  4088. ASSERT_TRUE(res);
  4089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4090. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4091. EXPECT_EQ(true, res->has_header("Content-Range"));
  4092. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4093. EXPECT_EQ(std::string("fg"), res->body);
  4094. }
  4095. TEST_F(ServerTest, GetWithRange5) {
  4096. auto res = cli_.Get("/with-range", {
  4097. make_range_header({{0, 5}}),
  4098. {"Accept-Encoding", ""},
  4099. });
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4102. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(true, res->has_header("Content-Range"));
  4104. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4105. EXPECT_EQ(std::string("abcdef"), res->body);
  4106. }
  4107. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4108. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4109. ASSERT_TRUE(res);
  4110. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4111. }
  4112. TEST_F(ServerTest, GetWithRangeMultipart) {
  4113. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4114. ASSERT_TRUE(res);
  4115. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4116. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4117. EXPECT_EQ(false, res->has_header("Content-Range"));
  4118. EXPECT_EQ(267U, res->body.size());
  4119. }
  4120. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4121. auto res =
  4122. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4125. }
  4126. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4127. auto res = cli_.Get("/with-range-customized-response",
  4128. {{make_range_header({{1, 2}})}});
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4131. EXPECT_EQ(true, res->has_header("Content-Length"));
  4132. EXPECT_EQ(false, res->has_header("Content-Range"));
  4133. EXPECT_EQ(JSON_DATA, res->body);
  4134. }
  4135. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4136. auto res = cli_.Get("/with-range-customized-response",
  4137. {{make_range_header({{1, 2}, {4, 5}})}});
  4138. ASSERT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4140. EXPECT_EQ(true, res->has_header("Content-Length"));
  4141. EXPECT_EQ(false, res->has_header("Content-Range"));
  4142. EXPECT_EQ(JSON_DATA, res->body);
  4143. }
  4144. TEST_F(ServerTest, Issue1772) {
  4145. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4146. ASSERT_TRUE(res);
  4147. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4148. }
  4149. TEST_F(ServerTest, Issue609) {
  4150. auto res = cli_.Delete("/issue609");
  4151. ASSERT_TRUE(res);
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ(std::string("ok"), res->body);
  4154. }
  4155. TEST_F(ServerTest, GetStreamedChunked) {
  4156. auto res = cli_.Get("/streamed-chunked");
  4157. ASSERT_TRUE(res);
  4158. EXPECT_EQ(StatusCode::OK_200, res->status);
  4159. EXPECT_EQ(std::string("123456789"), res->body);
  4160. }
  4161. TEST_F(ServerTest, GetStreamedChunked2) {
  4162. auto res = cli_.Get("/streamed-chunked2");
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::OK_200, res->status);
  4165. EXPECT_EQ(std::string("123456789"), res->body);
  4166. }
  4167. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4168. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4169. ASSERT_TRUE(res);
  4170. EXPECT_EQ(StatusCode::OK_200, res->status);
  4171. EXPECT_EQ(std::string("123456789"), res->body);
  4172. EXPECT_TRUE(res->has_header("Trailer"));
  4173. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4174. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4175. // Trailers are now stored separately from headers (security fix)
  4176. EXPECT_EQ(2U, res->trailers.size());
  4177. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4178. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4179. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4180. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4181. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4182. // Verify trailers are NOT in headers (security verification)
  4183. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4184. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4185. }
  4186. TEST_F(ServerTest, LargeChunkedPost) {
  4187. Request req;
  4188. req.method = "POST";
  4189. req.path = "/large-chunked";
  4190. std::string host_and_port;
  4191. host_and_port += HOST;
  4192. host_and_port += ":";
  4193. host_and_port += std::to_string(PORT);
  4194. req.headers.emplace("Host", host_and_port.c_str());
  4195. req.headers.emplace("Accept", "*/*");
  4196. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4197. req.headers.emplace("Content-Type", "text/plain");
  4198. req.headers.emplace("Content-Length", "0");
  4199. req.headers.emplace("Transfer-Encoding", "chunked");
  4200. std::string long_string(30 * 1024u, 'a');
  4201. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4202. // Attempt to make a large enough post to exceed OS buffers, to test that
  4203. // the server handles short reads if the full chunk data isn't available.
  4204. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4205. auto res = std::make_shared<Response>();
  4206. auto error = Error::Success;
  4207. auto ret = cli_.send(req, *res, error);
  4208. ASSERT_TRUE(ret);
  4209. EXPECT_EQ(StatusCode::OK_200, res->status);
  4210. }
  4211. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4212. auto res = cli_.Get("/remote_addr");
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4216. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4217. }
  4218. TEST_F(ServerTest, GetMethodLocalAddr) {
  4219. auto res = cli_.Get("/local_addr");
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::OK_200, res->status);
  4222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4223. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4224. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4225. }
  4226. TEST_F(ServerTest, HTTPResponseSplitting) {
  4227. auto res = cli_.Get("/http_response_splitting");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. }
  4231. TEST_F(ServerTest, SlowRequest) {
  4232. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4233. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4234. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4235. }
  4236. #if 0
  4237. TEST_F(ServerTest, SlowPost) {
  4238. char buffer[64 * 1024];
  4239. memset(buffer, 0x42, sizeof(buffer));
  4240. auto res = cli_.Post(
  4241. "/slowpost", 64 * 1024 * 1024,
  4242. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4243. auto ret = sink.write(buffer, sizeof(buffer));
  4244. EXPECT_TRUE(ret);
  4245. return true;
  4246. },
  4247. "text/plain");
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::OK_200, res->status);
  4250. }
  4251. TEST_F(ServerTest, SlowPostFail) {
  4252. char buffer[64 * 1024];
  4253. memset(buffer, 0x42, sizeof(buffer));
  4254. cli_.set_write_timeout(std::chrono::seconds(0));
  4255. auto res = cli_.Post(
  4256. "/slowpost", 64 * 1024 * 1024,
  4257. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4258. sink.write(buffer, sizeof(buffer));
  4259. return true;
  4260. },
  4261. "text/plain");
  4262. ASSERT_TRUE(!res);
  4263. EXPECT_EQ(Error::Write, res.error());
  4264. }
  4265. #endif
  4266. TEST_F(ServerTest, Put) {
  4267. auto res = cli_.Put("/put", "PUT", "text/plain");
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::OK_200, res->status);
  4270. EXPECT_EQ("PUT", res->body);
  4271. }
  4272. TEST_F(ServerTest, PutWithContentProvider) {
  4273. auto res = cli_.Put(
  4274. "/put", 3,
  4275. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4276. sink.os << "PUT";
  4277. return true;
  4278. },
  4279. "text/plain");
  4280. ASSERT_TRUE(res);
  4281. EXPECT_EQ(StatusCode::OK_200, res->status);
  4282. EXPECT_EQ("PUT", res->body);
  4283. }
  4284. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4285. auto res = cli_.Post(
  4286. "/post", 42,
  4287. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4288. return false;
  4289. },
  4290. "text/plain");
  4291. ASSERT_TRUE(!res);
  4292. EXPECT_EQ(Error::Canceled, res.error());
  4293. }
  4294. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4295. auto res = cli_.Put(
  4296. "/put",
  4297. [](size_t /*offset*/, DataSink &sink) {
  4298. sink.os << "PUT";
  4299. sink.done();
  4300. return true;
  4301. },
  4302. "text/plain");
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::OK_200, res->status);
  4305. EXPECT_EQ("PUT", res->body);
  4306. }
  4307. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4308. auto res = cli_.Post(
  4309. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4310. "text/plain");
  4311. ASSERT_TRUE(!res);
  4312. EXPECT_EQ(Error::Canceled, res.error());
  4313. }
  4314. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4315. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4316. cli_.set_compress(true);
  4317. auto res = cli_.Put(
  4318. "/put", 3,
  4319. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4320. sink.os << "PUT";
  4321. return true;
  4322. },
  4323. "text/plain");
  4324. ASSERT_TRUE(res);
  4325. EXPECT_EQ(StatusCode::OK_200, res->status);
  4326. EXPECT_EQ("PUT", res->body);
  4327. }
  4328. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4329. cli_.set_compress(true);
  4330. auto res = cli_.Post(
  4331. "/post", 42,
  4332. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4333. return false;
  4334. },
  4335. "text/plain");
  4336. ASSERT_TRUE(!res);
  4337. EXPECT_EQ(Error::Canceled, res.error());
  4338. }
  4339. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4340. cli_.set_compress(true);
  4341. auto res = cli_.Put(
  4342. "/put",
  4343. [](size_t /*offset*/, DataSink &sink) {
  4344. sink.os << "PUT";
  4345. sink.done();
  4346. return true;
  4347. },
  4348. "text/plain");
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::OK_200, res->status);
  4351. EXPECT_EQ("PUT", res->body);
  4352. }
  4353. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4354. cli_.set_compress(true);
  4355. auto res = cli_.Post(
  4356. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4357. "text/plain");
  4358. ASSERT_TRUE(!res);
  4359. EXPECT_EQ(Error::Canceled, res.error());
  4360. }
  4361. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4362. cli_.set_compress(true);
  4363. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4364. ASSERT_TRUE(res);
  4365. EXPECT_EQ(StatusCode::OK_200, res->status);
  4366. EXPECT_EQ(LARGE_DATA, res->body);
  4367. }
  4368. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4369. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4370. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4371. Client cli(s.c_str());
  4372. cli.enable_server_certificate_verification(false);
  4373. #else
  4374. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4375. Client cli(s.c_str());
  4376. #endif
  4377. cli.set_compress(true);
  4378. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. EXPECT_EQ(LARGE_DATA, res->body);
  4382. // The compressed size should be less than a 10th of the original. May vary
  4383. // depending on the zlib library.
  4384. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4385. static_cast<uint64_t>(10 * 1024 * 1024));
  4386. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4387. }
  4388. TEST_F(ServerTest, PutContentWithDeflate) {
  4389. cli_.set_compress(false);
  4390. Headers headers;
  4391. headers.emplace("Content-Encoding", "deflate");
  4392. // PUT in deflate format:
  4393. auto res = cli_.Put("/put", headers,
  4394. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4395. ASSERT_TRUE(res);
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("PUT", res->body);
  4398. }
  4399. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4400. Headers headers;
  4401. headers.emplace("Accept-Encoding", "gzip, deflate");
  4402. auto res = cli_.Get("/streamed-chunked", headers);
  4403. ASSERT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ(std::string("123456789"), res->body);
  4406. }
  4407. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4408. Headers headers;
  4409. headers.emplace("Accept-Encoding", "gzip, deflate");
  4410. auto res = cli_.Get("/streamed-chunked2", headers);
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ(std::string("123456789"), res->body);
  4414. }
  4415. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4416. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4417. ASSERT_TRUE(res);
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. }
  4420. TEST(GzipDecompressor, ChunkedDecompression) {
  4421. std::string data;
  4422. for (size_t i = 0; i < 32 * 1024; ++i) {
  4423. data.push_back(static_cast<char>('a' + i % 26));
  4424. }
  4425. std::string compressed_data;
  4426. {
  4427. httplib::detail::gzip_compressor compressor;
  4428. bool result = compressor.compress(
  4429. data.data(), data.size(),
  4430. /*last=*/true,
  4431. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4432. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4433. compressed_data_size);
  4434. return true;
  4435. });
  4436. ASSERT_TRUE(result);
  4437. }
  4438. std::string decompressed_data;
  4439. {
  4440. httplib::detail::gzip_decompressor decompressor;
  4441. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4442. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4443. size_t chunk_size = 130;
  4444. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4445. chunk_begin += chunk_size) {
  4446. size_t current_chunk_size =
  4447. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4448. bool result = decompressor.decompress(
  4449. compressed_data.data() + chunk_begin, current_chunk_size,
  4450. [&](const char *decompressed_data_chunk,
  4451. size_t decompressed_data_chunk_size) {
  4452. decompressed_data.insert(decompressed_data.size(),
  4453. decompressed_data_chunk,
  4454. decompressed_data_chunk_size);
  4455. return true;
  4456. });
  4457. ASSERT_TRUE(result);
  4458. }
  4459. }
  4460. ASSERT_EQ(data, decompressed_data);
  4461. }
  4462. TEST(GzipDecompressor, DeflateDecompression) {
  4463. std::string original_text = "Raw deflate without gzip";
  4464. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4465. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4466. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4467. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4468. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4469. std::string decompressed_data;
  4470. {
  4471. httplib::detail::gzip_decompressor decompressor;
  4472. bool result = decompressor.decompress(
  4473. compressed_data.data(), compressed_data.size(),
  4474. [&](const char *decompressed_data_chunk,
  4475. size_t decompressed_data_chunk_size) {
  4476. decompressed_data.insert(decompressed_data.size(),
  4477. decompressed_data_chunk,
  4478. decompressed_data_chunk_size);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(result);
  4482. }
  4483. ASSERT_EQ(original_text, decompressed_data);
  4484. }
  4485. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4486. std::string original_text = "Raw deflate without gzip";
  4487. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4488. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4489. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4490. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4491. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4492. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4493. std::string decompressed_data;
  4494. {
  4495. httplib::detail::gzip_decompressor decompressor;
  4496. bool result = decompressor.decompress(
  4497. compressed_data.data(), compressed_data.size(),
  4498. [&](const char *decompressed_data_chunk,
  4499. size_t decompressed_data_chunk_size) {
  4500. decompressed_data.insert(decompressed_data.size(),
  4501. decompressed_data_chunk,
  4502. decompressed_data_chunk_size);
  4503. return true;
  4504. });
  4505. ASSERT_TRUE(result);
  4506. }
  4507. ASSERT_EQ(original_text, decompressed_data);
  4508. }
  4509. #ifdef _WIN32
  4510. TEST(GzipDecompressor, LargeRandomData) {
  4511. // prepare large random data that is difficult to be compressed and is
  4512. // expected to have large size even when compressed
  4513. std::random_device seed_gen;
  4514. std::mt19937 random(seed_gen());
  4515. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4516. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4517. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4518. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4519. // compress data over 4GiB
  4520. std::string compressed_data;
  4521. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4522. httplib::detail::gzip_compressor compressor;
  4523. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4524. data.size() * sizeof(std::uint32_t), true,
  4525. [&](const char *data, size_t size) {
  4526. compressed_data.insert(
  4527. compressed_data.size(), data, size);
  4528. return true;
  4529. });
  4530. ASSERT_TRUE(result);
  4531. // FIXME: compressed data size is expected to be greater than 4GiB,
  4532. // but there is no guarantee
  4533. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4534. // decompress data over 4GiB
  4535. std::string decompressed_data;
  4536. decompressed_data.reserve(data_size);
  4537. httplib::detail::gzip_decompressor decompressor;
  4538. result = decompressor.decompress(
  4539. compressed_data.data(), compressed_data.size(),
  4540. [&](const char *data, size_t size) {
  4541. decompressed_data.insert(decompressed_data.size(), data, size);
  4542. return true;
  4543. });
  4544. ASSERT_TRUE(result);
  4545. // compare
  4546. ASSERT_EQ(data_size, decompressed_data.size());
  4547. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4548. 0);
  4549. }
  4550. #endif
  4551. #endif
  4552. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4553. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4554. Headers headers;
  4555. headers.emplace("Accept-Encoding", "br");
  4556. auto res = cli_.Get("/streamed-chunked", headers);
  4557. ASSERT_TRUE(res);
  4558. EXPECT_EQ(StatusCode::OK_200, res->status);
  4559. EXPECT_EQ(std::string("123456789"), res->body);
  4560. }
  4561. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4562. Headers headers;
  4563. headers.emplace("Accept-Encoding", "br");
  4564. auto res = cli_.Get("/streamed-chunked2", headers);
  4565. ASSERT_TRUE(res);
  4566. EXPECT_EQ(StatusCode::OK_200, res->status);
  4567. EXPECT_EQ(std::string("123456789"), res->body);
  4568. }
  4569. #endif
  4570. TEST_F(ServerTest, Patch) {
  4571. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4572. ASSERT_TRUE(res);
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("PATCH", res->body);
  4575. }
  4576. TEST_F(ServerTest, Delete) {
  4577. auto res = cli_.Delete("/delete");
  4578. ASSERT_TRUE(res);
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. EXPECT_EQ("DELETE", res->body);
  4581. }
  4582. TEST_F(ServerTest, DeleteContentReceiver) {
  4583. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4584. ASSERT_TRUE(res);
  4585. EXPECT_EQ(StatusCode::OK_200, res->status);
  4586. EXPECT_EQ("content", res->body);
  4587. }
  4588. TEST_F(ServerTest, Options) {
  4589. auto res = cli_.Options("*");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4593. EXPECT_TRUE(res->body.empty());
  4594. }
  4595. TEST_F(ServerTest, URL) {
  4596. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4597. ASSERT_TRUE(res);
  4598. EXPECT_EQ(StatusCode::OK_200, res->status);
  4599. }
  4600. TEST_F(ServerTest, ArrayParam) {
  4601. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4602. ASSERT_TRUE(res);
  4603. EXPECT_EQ(StatusCode::OK_200, res->status);
  4604. }
  4605. TEST_F(ServerTest, NoMultipleHeaders) {
  4606. Headers headers = {{"Content-Length", "5"}};
  4607. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4608. "text/plain");
  4609. ASSERT_TRUE(res);
  4610. EXPECT_EQ(StatusCode::OK_200, res->status);
  4611. }
  4612. TEST_F(ServerTest, PostContentReceiver) {
  4613. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4614. ASSERT_TRUE(res);
  4615. ASSERT_EQ(StatusCode::OK_200, res->status);
  4616. ASSERT_EQ("content", res->body);
  4617. }
  4618. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4619. UploadFormDataItems items = {
  4620. {"text1", "text default", "", ""},
  4621. {"text2", "aωb", "", ""},
  4622. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4623. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4624. {"file3", "", "", "application/octet-stream"},
  4625. };
  4626. auto res = cli_.Post("/content_receiver", items);
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::OK_200, res->status);
  4629. }
  4630. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4631. UploadFormDataItems items = {
  4632. {"text1", "text default", "", ""},
  4633. {"text2", "aωb", "", ""},
  4634. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4635. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4636. {"file3", "", "", "application/octet-stream"},
  4637. };
  4638. auto boundary = std::string("+++++");
  4639. std::string body;
  4640. for (const auto &item : items) {
  4641. body += "--" + boundary + "\r\n";
  4642. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4643. if (!item.filename.empty()) {
  4644. body += "; filename=\"" + item.filename + "\"";
  4645. }
  4646. body += "\r\n";
  4647. if (!item.content_type.empty()) {
  4648. body += "Content-Type: " + item.content_type + "\r\n";
  4649. }
  4650. body += "\r\n";
  4651. body += item.content + "\r\n";
  4652. }
  4653. body += "--" + boundary + "--\r\n";
  4654. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4655. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. }
  4659. TEST_F(ServerTest, PostContentReceiverGzip) {
  4660. cli_.set_compress(true);
  4661. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4662. ASSERT_TRUE(res);
  4663. ASSERT_EQ(StatusCode::OK_200, res->status);
  4664. ASSERT_EQ("content", res->body);
  4665. }
  4666. TEST_F(ServerTest, PutContentReceiver) {
  4667. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4668. ASSERT_TRUE(res);
  4669. ASSERT_EQ(StatusCode::OK_200, res->status);
  4670. ASSERT_EQ("content", res->body);
  4671. }
  4672. TEST_F(ServerTest, PatchContentReceiver) {
  4673. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4674. ASSERT_TRUE(res);
  4675. ASSERT_EQ(StatusCode::OK_200, res->status);
  4676. ASSERT_EQ("content", res->body);
  4677. }
  4678. template <typename ClientType>
  4679. void TestWithHeadersAndContentReceiver(
  4680. ClientType &cli,
  4681. std::function<Result(ClientType &, const std::string &, const Headers &,
  4682. const std::string &, const std::string &,
  4683. ContentReceiver, DownloadProgress)>
  4684. request_func) {
  4685. Headers headers;
  4686. headers.emplace("X-Custom-Header", "test-value");
  4687. std::string received_body;
  4688. auto res = request_func(
  4689. cli, "/content_receiver", headers, "content", "application/json",
  4690. [&](const char *data, size_t data_length) {
  4691. received_body.append(data, data_length);
  4692. return true;
  4693. },
  4694. nullptr);
  4695. ASSERT_TRUE(res);
  4696. EXPECT_EQ(StatusCode::OK_200, res->status);
  4697. EXPECT_EQ("content", received_body);
  4698. }
  4699. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4700. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4701. using ClientT = SSLClient;
  4702. #else
  4703. using ClientT = Client;
  4704. #endif
  4705. TestWithHeadersAndContentReceiver<ClientT>(
  4706. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4707. const std::string &body, const std::string &content_type,
  4708. ContentReceiver receiver, DownloadProgress progress) {
  4709. return cli.Post(path, headers, body, content_type, receiver, progress);
  4710. });
  4711. }
  4712. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4713. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4714. using ClientT = SSLClient;
  4715. #else
  4716. using ClientT = Client;
  4717. #endif
  4718. TestWithHeadersAndContentReceiver<ClientT>(
  4719. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4720. const std::string &body, const std::string &content_type,
  4721. ContentReceiver receiver, DownloadProgress progress) {
  4722. return cli.Put(path, headers, body, content_type, receiver, progress);
  4723. });
  4724. }
  4725. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4727. using ClientT = SSLClient;
  4728. #else
  4729. using ClientT = Client;
  4730. #endif
  4731. TestWithHeadersAndContentReceiver<ClientT>(
  4732. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4733. const std::string &body, const std::string &content_type,
  4734. ContentReceiver receiver, DownloadProgress progress) {
  4735. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4736. });
  4737. }
  4738. template <typename ClientType>
  4739. void TestWithHeadersAndContentReceiverWithProgress(
  4740. ClientType &cli,
  4741. std::function<Result(ClientType &, const std::string &, const Headers &,
  4742. const std::string &, const std::string &,
  4743. ContentReceiver, DownloadProgress)>
  4744. request_func) {
  4745. Headers headers;
  4746. headers.emplace("X-Test-Header", "progress-test");
  4747. std::string received_body;
  4748. auto progress_called = false;
  4749. auto res = request_func(
  4750. cli, "/content_receiver", headers, "content", "text/plain",
  4751. [&](const char *data, size_t data_length) {
  4752. received_body.append(data, data_length);
  4753. return true;
  4754. },
  4755. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4756. progress_called = true;
  4757. return true;
  4758. });
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. EXPECT_EQ("content", received_body);
  4762. EXPECT_TRUE(progress_called);
  4763. }
  4764. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4765. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4766. using ClientT = SSLClient;
  4767. #else
  4768. using ClientT = Client;
  4769. #endif
  4770. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4771. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4772. const std::string &body, const std::string &content_type,
  4773. ContentReceiver receiver, DownloadProgress progress) {
  4774. return cli.Post(path, headers, body, content_type, receiver, progress);
  4775. });
  4776. }
  4777. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4778. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4779. using ClientT = SSLClient;
  4780. #else
  4781. using ClientT = Client;
  4782. #endif
  4783. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4784. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4785. const std::string &body, const std::string &content_type,
  4786. ContentReceiver receiver, DownloadProgress progress) {
  4787. return cli.Put(path, headers, body, content_type, receiver, progress);
  4788. });
  4789. }
  4790. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4791. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4792. using ClientT = SSLClient;
  4793. #else
  4794. using ClientT = Client;
  4795. #endif
  4796. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4797. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4798. const std::string &body, const std::string &content_type,
  4799. ContentReceiver receiver, DownloadProgress progress) {
  4800. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4801. });
  4802. }
  4803. template <typename ClientType>
  4804. void TestWithHeadersAndContentReceiverError(
  4805. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4806. const Headers &, const std::string &,
  4807. const std::string &, ContentReceiver)>
  4808. request_func) {
  4809. Headers headers;
  4810. headers.emplace("X-Error-Test", "true");
  4811. std::string received_body;
  4812. auto receiver_failed = false;
  4813. auto res =
  4814. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4815. [&](const char *data, size_t data_length) {
  4816. received_body.append(data, data_length);
  4817. receiver_failed = true;
  4818. return false;
  4819. });
  4820. ASSERT_FALSE(res);
  4821. EXPECT_TRUE(receiver_failed);
  4822. }
  4823. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4824. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4825. using ClientT = SSLClient;
  4826. #else
  4827. using ClientT = Client;
  4828. #endif
  4829. TestWithHeadersAndContentReceiverError<ClientT>(
  4830. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4831. const std::string &body, const std::string &content_type,
  4832. ContentReceiver receiver) {
  4833. return cli.Post(path, headers, body, content_type, receiver);
  4834. });
  4835. }
  4836. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4838. using ClientT = SSLClient;
  4839. #else
  4840. using ClientT = Client;
  4841. #endif
  4842. TestWithHeadersAndContentReceiverError<ClientT>(
  4843. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4844. const std::string &body, const std::string &content_type,
  4845. ContentReceiver receiver) {
  4846. return cli.Put(path, headers, body, content_type, receiver);
  4847. });
  4848. }
  4849. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4850. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4851. using ClientT = SSLClient;
  4852. #else
  4853. using ClientT = Client;
  4854. #endif
  4855. TestWithHeadersAndContentReceiverError<ClientT>(
  4856. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4857. const std::string &body, const std::string &content_type,
  4858. ContentReceiver receiver) {
  4859. return cli.Patch(path, headers, body, content_type, receiver);
  4860. });
  4861. }
  4862. TEST_F(ServerTest, PostQueryStringAndBody) {
  4863. auto res =
  4864. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4865. ASSERT_TRUE(res);
  4866. ASSERT_EQ(StatusCode::OK_200, res->status);
  4867. }
  4868. TEST_F(ServerTest, HTTP2Magic) {
  4869. Request req;
  4870. req.method = "PRI";
  4871. req.path = "*";
  4872. req.body = "SM";
  4873. auto res = std::make_shared<Response>();
  4874. auto error = Error::Success;
  4875. auto ret = cli_.send(req, *res, error);
  4876. ASSERT_TRUE(ret);
  4877. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4878. }
  4879. TEST_F(ServerTest, KeepAlive) {
  4880. auto res = cli_.Get("/hi");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::OK_200, res->status);
  4883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4884. EXPECT_EQ("Hello World!", res->body);
  4885. res = cli_.Get("/hi");
  4886. ASSERT_TRUE(res);
  4887. EXPECT_EQ(StatusCode::OK_200, res->status);
  4888. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4889. EXPECT_EQ("Hello World!", res->body);
  4890. res = cli_.Get("/hi");
  4891. ASSERT_TRUE(res);
  4892. EXPECT_EQ(StatusCode::OK_200, res->status);
  4893. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4894. EXPECT_EQ("Hello World!", res->body);
  4895. res = cli_.Get("/not-exist");
  4896. ASSERT_TRUE(res);
  4897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4898. res = cli_.Post("/empty", "", "text/plain");
  4899. ASSERT_TRUE(res);
  4900. EXPECT_EQ(StatusCode::OK_200, res->status);
  4901. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4902. EXPECT_EQ("empty", res->body);
  4903. EXPECT_EQ("close", res->get_header_value("Connection"));
  4904. res = cli_.Post(
  4905. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4906. "text/plain");
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4910. EXPECT_EQ("empty", res->body);
  4911. cli_.set_keep_alive(false);
  4912. res = cli_.Get("/last-request");
  4913. ASSERT_TRUE(res);
  4914. EXPECT_EQ(StatusCode::OK_200, res->status);
  4915. EXPECT_EQ("close", res->get_header_value("Connection"));
  4916. }
  4917. TEST_F(ServerTest, TooManyRedirect) {
  4918. cli_.set_follow_location(true);
  4919. auto res = cli_.Get("/redirect/0");
  4920. ASSERT_TRUE(!res);
  4921. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4922. }
  4923. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4924. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4925. TEST_F(ServerTest, Gzip) {
  4926. Headers headers;
  4927. headers.emplace("Accept-Encoding", "gzip, deflate");
  4928. auto res = cli_.Get("/compress", headers);
  4929. ASSERT_TRUE(res);
  4930. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4932. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4934. "7890123456789012345678901234567890",
  4935. res->body);
  4936. EXPECT_EQ(StatusCode::OK_200, res->status);
  4937. }
  4938. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4939. Headers headers;
  4940. headers.emplace("Accept-Encoding", "");
  4941. auto res = cli_.Get("/compress", headers);
  4942. ASSERT_TRUE(res);
  4943. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4945. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4946. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4947. "7890123456789012345678901234567890",
  4948. res->body);
  4949. EXPECT_EQ(StatusCode::OK_200, res->status);
  4950. }
  4951. TEST_F(ServerTest, GzipWithContentReceiver) {
  4952. Headers headers;
  4953. headers.emplace("Accept-Encoding", "gzip, deflate");
  4954. std::string body;
  4955. auto res = cli_.Get("/compress", headers,
  4956. [&](const char *data, uint64_t data_length) {
  4957. EXPECT_EQ(100U, data_length);
  4958. body.append(data, data_length);
  4959. return true;
  4960. });
  4961. ASSERT_TRUE(res);
  4962. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4964. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4965. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4966. "7890123456789012345678901234567890",
  4967. body);
  4968. EXPECT_EQ(StatusCode::OK_200, res->status);
  4969. }
  4970. TEST_F(ServerTest, GzipWithoutDecompressing) {
  4971. Headers headers;
  4972. headers.emplace("Accept-Encoding", "gzip, deflate");
  4973. cli_.set_decompress(false);
  4974. auto res = cli_.Get("/compress", headers);
  4975. ASSERT_TRUE(res);
  4976. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4977. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4978. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4979. EXPECT_EQ(33U, res->body.size());
  4980. EXPECT_EQ(StatusCode::OK_200, res->status);
  4981. }
  4982. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  4983. Headers headers;
  4984. headers.emplace("Accept-Encoding", "");
  4985. std::string body;
  4986. auto res = cli_.Get("/compress", headers,
  4987. [&](const char *data, uint64_t data_length) {
  4988. EXPECT_EQ(100U, data_length);
  4989. body.append(data, data_length);
  4990. return true;
  4991. });
  4992. ASSERT_TRUE(res);
  4993. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  4994. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4995. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  4996. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4997. "7890123456789012345678901234567890",
  4998. body);
  4999. EXPECT_EQ(StatusCode::OK_200, res->status);
  5000. }
  5001. TEST_F(ServerTest, NoGzip) {
  5002. Headers headers;
  5003. headers.emplace("Accept-Encoding", "gzip, deflate");
  5004. auto res = cli_.Get("/nocompress", headers);
  5005. ASSERT_TRUE(res);
  5006. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5007. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5008. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5009. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5010. "7890123456789012345678901234567890",
  5011. res->body);
  5012. EXPECT_EQ(StatusCode::OK_200, res->status);
  5013. }
  5014. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5015. Headers headers;
  5016. headers.emplace("Accept-Encoding", "gzip, deflate");
  5017. std::string body;
  5018. auto res = cli_.Get("/nocompress", headers,
  5019. [&](const char *data, uint64_t data_length) {
  5020. EXPECT_EQ(100U, data_length);
  5021. body.append(data, data_length);
  5022. return true;
  5023. });
  5024. ASSERT_TRUE(res);
  5025. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5026. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5027. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5028. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5029. "7890123456789012345678901234567890",
  5030. body);
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. }
  5033. TEST_F(ServerTest, MultipartFormDataGzip) {
  5034. UploadFormDataItems items = {
  5035. {"key1", "test", "", ""},
  5036. {"key2", "--abcdefg123", "", ""},
  5037. };
  5038. cli_.set_compress(true);
  5039. auto res = cli_.Post("/compress-multipart", items);
  5040. ASSERT_TRUE(res);
  5041. EXPECT_EQ(StatusCode::OK_200, res->status);
  5042. }
  5043. #endif
  5044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5045. TEST_F(ServerTest, Brotli) {
  5046. Headers headers;
  5047. headers.emplace("Accept-Encoding", "br");
  5048. auto res = cli_.Get("/compress", headers);
  5049. ASSERT_TRUE(res);
  5050. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5052. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5054. "7890123456789012345678901234567890",
  5055. res->body);
  5056. EXPECT_EQ(StatusCode::OK_200, res->status);
  5057. }
  5058. #endif
  5059. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5060. TEST_F(ServerTest, Zstd) {
  5061. Headers headers;
  5062. headers.emplace("Accept-Encoding", "zstd");
  5063. auto res = cli_.Get("/compress", headers);
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5067. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5068. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5069. "7890123456789012345678901234567890",
  5070. res->body);
  5071. EXPECT_EQ(StatusCode::OK_200, res->status);
  5072. }
  5073. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5074. Headers headers;
  5075. headers.emplace("Accept-Encoding", "");
  5076. auto res = cli_.Get("/compress", headers);
  5077. ASSERT_TRUE(res);
  5078. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5079. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5080. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5081. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5082. "7890123456789012345678901234567890",
  5083. res->body);
  5084. EXPECT_EQ(StatusCode::OK_200, res->status);
  5085. }
  5086. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5087. Headers headers;
  5088. headers.emplace("Accept-Encoding", "zstd");
  5089. std::string body;
  5090. auto res = cli_.Get("/compress", headers,
  5091. [&](const char *data, uint64_t data_length) {
  5092. EXPECT_EQ(100U, data_length);
  5093. body.append(data, data_length);
  5094. return true;
  5095. });
  5096. ASSERT_TRUE(res);
  5097. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5098. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5099. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5100. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5101. "7890123456789012345678901234567890",
  5102. body);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. }
  5105. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5106. Headers headers;
  5107. headers.emplace("Accept-Encoding", "zstd");
  5108. cli_.set_decompress(false);
  5109. auto res = cli_.Get("/compress", headers);
  5110. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5111. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5112. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5113. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5114. ASSERT_TRUE(res);
  5115. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5116. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5118. EXPECT_EQ(StatusCode::OK_200, res->status);
  5119. ASSERT_EQ(26U, res->body.size());
  5120. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5121. 0);
  5122. }
  5123. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5124. Headers headers;
  5125. headers.emplace("Accept-Encoding", "");
  5126. std::string body;
  5127. auto res = cli_.Get("/compress", headers,
  5128. [&](const char *data, uint64_t data_length) {
  5129. EXPECT_EQ(100U, data_length);
  5130. body.append(data, data_length);
  5131. return true;
  5132. });
  5133. ASSERT_TRUE(res);
  5134. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5135. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5136. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5137. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5138. "7890123456789012345678901234567890",
  5139. body);
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. }
  5142. TEST_F(ServerTest, NoZstd) {
  5143. Headers headers;
  5144. headers.emplace("Accept-Encoding", "zstd");
  5145. auto res = cli_.Get("/nocompress", headers);
  5146. ASSERT_TRUE(res);
  5147. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5148. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5149. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5150. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5151. "7890123456789012345678901234567890",
  5152. res->body);
  5153. EXPECT_EQ(StatusCode::OK_200, res->status);
  5154. }
  5155. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5156. Headers headers;
  5157. headers.emplace("Accept-Encoding", "zstd");
  5158. std::string body;
  5159. auto res = cli_.Get("/nocompress", headers,
  5160. [&](const char *data, uint64_t data_length) {
  5161. EXPECT_EQ(100U, data_length);
  5162. body.append(data, data_length);
  5163. return true;
  5164. });
  5165. ASSERT_TRUE(res);
  5166. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5167. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5168. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5169. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5170. "7890123456789012345678901234567890",
  5171. body);
  5172. EXPECT_EQ(StatusCode::OK_200, res->status);
  5173. }
  5174. // TODO: How to enable zstd ??
  5175. TEST_F(ServerTest, MultipartFormDataZstd) {
  5176. UploadFormDataItems items = {
  5177. {"key1", "test", "", ""},
  5178. {"key2", "--abcdefg123", "", ""},
  5179. };
  5180. Headers headers;
  5181. headers.emplace("Accept-Encoding", "zstd");
  5182. cli_.set_compress(true);
  5183. auto res = cli_.Post("/compress-multipart", headers, items);
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ(StatusCode::OK_200, res->status);
  5186. }
  5187. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5188. Headers headers;
  5189. headers.emplace("Accept-Encoding", "zstd");
  5190. cli_.set_compress(true);
  5191. auto res = cli_.Put(
  5192. "/put", headers, 3,
  5193. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5194. sink.os << "PUT";
  5195. return true;
  5196. },
  5197. "text/plain");
  5198. ASSERT_TRUE(res);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. EXPECT_EQ("PUT", res->body);
  5201. }
  5202. // Pre-compression logging tests
  5203. TEST_F(ServerTest, PreCompressionLogging) {
  5204. // Test data for compression (matches the actual /compress endpoint content)
  5205. const std::string test_content =
  5206. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5207. "3456789012345678901234567890";
  5208. // Variables to capture logging data
  5209. std::string pre_compression_body;
  5210. std::string pre_compression_content_type;
  5211. std::string pre_compression_content_encoding;
  5212. std::string post_compression_body;
  5213. std::string post_compression_content_type;
  5214. std::string post_compression_content_encoding;
  5215. // Set up pre-compression logger
  5216. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5217. const Response &res) {
  5218. pre_compression_body = res.body;
  5219. pre_compression_content_type = res.get_header_value("Content-Type");
  5220. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5221. });
  5222. // Set up post-compression logger
  5223. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5224. post_compression_body = res.body;
  5225. post_compression_content_type = res.get_header_value("Content-Type");
  5226. post_compression_content_encoding =
  5227. res.get_header_value("Content-Encoding");
  5228. });
  5229. // Test with gzip compression
  5230. Headers headers;
  5231. headers.emplace("Accept-Encoding", "gzip");
  5232. auto res = cli_.Get("/compress", headers);
  5233. // Verify response was compressed
  5234. ASSERT_TRUE(res);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5237. // Verify pre-compression logger captured uncompressed content
  5238. EXPECT_EQ(test_content, pre_compression_body);
  5239. EXPECT_EQ("text/plain", pre_compression_content_type);
  5240. EXPECT_TRUE(pre_compression_content_encoding
  5241. .empty()); // No encoding header before compression
  5242. // Verify post-compression logger captured compressed content
  5243. EXPECT_NE(test_content,
  5244. post_compression_body); // Should be different after compression
  5245. EXPECT_EQ("text/plain", post_compression_content_type);
  5246. EXPECT_EQ("gzip", post_compression_content_encoding);
  5247. // Verify compressed content is smaller
  5248. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5249. }
  5250. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5251. const std::string test_content =
  5252. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5253. "3456789012345678901234567890";
  5254. std::string pre_compression_body;
  5255. std::string post_compression_body;
  5256. svr_.set_pre_compression_logger(
  5257. [&](const Request & /*req*/, const Response &res) {
  5258. pre_compression_body = res.body;
  5259. });
  5260. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5261. post_compression_body = res.body;
  5262. });
  5263. Headers headers;
  5264. headers.emplace("Accept-Encoding", "br");
  5265. auto res = cli_.Get("/compress", headers);
  5266. ASSERT_TRUE(res);
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5269. // Verify pre-compression content is uncompressed
  5270. EXPECT_EQ(test_content, pre_compression_body);
  5271. // Verify post-compression content is compressed
  5272. EXPECT_NE(test_content, post_compression_body);
  5273. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5274. }
  5275. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5276. const std::string test_content =
  5277. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5278. "3456789012345678901234567890";
  5279. std::string pre_compression_body;
  5280. std::string post_compression_body;
  5281. svr_.set_pre_compression_logger(
  5282. [&](const Request & /*req*/, const Response &res) {
  5283. pre_compression_body = res.body;
  5284. });
  5285. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5286. post_compression_body = res.body;
  5287. });
  5288. // Request without compression (use /nocompress endpoint)
  5289. Headers headers;
  5290. auto res = cli_.Get("/nocompress", headers);
  5291. ASSERT_TRUE(res);
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5294. // Pre-compression logger should not be called when no compression is applied
  5295. EXPECT_TRUE(
  5296. pre_compression_body.empty()); // Pre-compression logger not called
  5297. EXPECT_EQ(
  5298. test_content,
  5299. post_compression_body); // Post-compression logger captures final content
  5300. }
  5301. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5302. const std::string test_content =
  5303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5304. "3456789012345678901234567890";
  5305. std::string pre_compression_body;
  5306. bool pre_logger_called = false;
  5307. // Set only pre-compression logger
  5308. svr_.set_pre_compression_logger(
  5309. [&](const Request & /*req*/, const Response &res) {
  5310. pre_compression_body = res.body;
  5311. pre_logger_called = true;
  5312. });
  5313. Headers headers;
  5314. headers.emplace("Accept-Encoding", "gzip");
  5315. auto res = cli_.Get("/compress", headers);
  5316. ASSERT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5319. // Verify pre-compression logger was called
  5320. EXPECT_TRUE(pre_logger_called);
  5321. EXPECT_EQ(test_content, pre_compression_body);
  5322. }
  5323. TEST(ZstdDecompressor, ChunkedDecompression) {
  5324. std::string data;
  5325. for (size_t i = 0; i < 32 * 1024; ++i) {
  5326. data.push_back(static_cast<char>('a' + i % 26));
  5327. }
  5328. std::string compressed_data;
  5329. {
  5330. httplib::detail::zstd_compressor compressor;
  5331. bool result = compressor.compress(
  5332. data.data(), data.size(),
  5333. /*last=*/true,
  5334. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5335. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5336. compressed_data_size);
  5337. return true;
  5338. });
  5339. ASSERT_TRUE(result);
  5340. }
  5341. std::string decompressed_data;
  5342. {
  5343. httplib::detail::zstd_decompressor decompressor;
  5344. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5345. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5346. size_t chunk_size = 130;
  5347. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5348. chunk_begin += chunk_size) {
  5349. size_t current_chunk_size =
  5350. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5351. bool result = decompressor.decompress(
  5352. compressed_data.data() + chunk_begin, current_chunk_size,
  5353. [&](const char *decompressed_data_chunk,
  5354. size_t decompressed_data_chunk_size) {
  5355. decompressed_data.insert(decompressed_data.size(),
  5356. decompressed_data_chunk,
  5357. decompressed_data_chunk_size);
  5358. return true;
  5359. });
  5360. ASSERT_TRUE(result);
  5361. }
  5362. }
  5363. ASSERT_EQ(data, decompressed_data);
  5364. }
  5365. TEST(ZstdDecompressor, Decompress) {
  5366. std::string original_text = "Compressed with ZSTD";
  5367. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5368. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5369. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5370. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5371. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5372. std::string decompressed_data;
  5373. {
  5374. httplib::detail::zstd_decompressor decompressor;
  5375. bool result = decompressor.decompress(
  5376. compressed_data.data(), compressed_data.size(),
  5377. [&](const char *decompressed_data_chunk,
  5378. size_t decompressed_data_chunk_size) {
  5379. decompressed_data.insert(decompressed_data.size(),
  5380. decompressed_data_chunk,
  5381. decompressed_data_chunk_size);
  5382. return true;
  5383. });
  5384. ASSERT_TRUE(result);
  5385. }
  5386. ASSERT_EQ(original_text, decompressed_data);
  5387. }
  5388. #endif
  5389. // Sends a raw request to a server listening at HOST:PORT.
  5390. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5391. std::string *resp = nullptr) {
  5392. auto error = Error::Success;
  5393. auto client_sock = detail::create_client_socket(
  5394. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5395. /*connection_timeout_sec=*/5, 0,
  5396. /*read_timeout_sec=*/5, 0,
  5397. /*write_timeout_sec=*/5, 0, std::string(), error);
  5398. if (client_sock == INVALID_SOCKET) { return false; }
  5399. auto ret = detail::process_client_socket(
  5400. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5401. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5402. if (req.size() !=
  5403. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5404. return false;
  5405. }
  5406. char buf[512];
  5407. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5408. while (line_reader.getline()) {
  5409. if (resp) { *resp += line_reader.ptr(); }
  5410. }
  5411. return true;
  5412. });
  5413. detail::close_socket(client_sock);
  5414. return ret;
  5415. }
  5416. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5417. Server svr;
  5418. std::string header_value;
  5419. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5420. header_value = req.get_header_value("foo");
  5421. res.set_content("ok", "text/plain");
  5422. });
  5423. thread t = thread([&] { svr.listen(HOST, PORT); });
  5424. auto se = detail::scope_exit([&] {
  5425. svr.stop();
  5426. t.join();
  5427. ASSERT_FALSE(svr.is_running());
  5428. });
  5429. svr.wait_until_ready();
  5430. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5431. // like characters are not treated the same - use vertical tab and escape.
  5432. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5433. "foo: \t \v bar \x1B\t \r\n"
  5434. "Connection: close\r\n"
  5435. "\r\n";
  5436. std::string res;
  5437. ASSERT_TRUE(send_request(5, req, &res));
  5438. EXPECT_EQ(header_value, "");
  5439. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5440. }
  5441. // Sends a raw request and verifies that there isn't a crash or exception.
  5442. static void test_raw_request(const std::string &req,
  5443. std::string *out = nullptr) {
  5444. Server svr;
  5445. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5446. res.set_content("ok", "text/plain");
  5447. });
  5448. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5449. res.set_content("ok", "text/plain");
  5450. });
  5451. svr.Get("/header_field_value_check",
  5452. [&](const Request & /*req*/, Response &res) {
  5453. res.set_content("ok", "text/plain");
  5454. });
  5455. // Server read timeout must be longer than the client read timeout for the
  5456. // bug to reproduce, probably to force the server to process a request
  5457. // without a trailing blank line.
  5458. const time_t client_read_timeout_sec = 1;
  5459. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5460. bool listen_thread_ok = false;
  5461. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5462. auto se = detail::scope_exit([&] {
  5463. svr.stop();
  5464. t.join();
  5465. ASSERT_FALSE(svr.is_running());
  5466. EXPECT_TRUE(listen_thread_ok);
  5467. });
  5468. svr.wait_until_ready();
  5469. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5470. }
  5471. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5472. // A certain header line causes an exception if the header property is parsed
  5473. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5474. test_raw_request(
  5475. "GET /hi HTTP/1.1\r\n"
  5476. " : "
  5477. " "
  5478. " ");
  5479. }
  5480. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5481. // A certain header line causes an exception if the header property *name* is
  5482. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5483. // greedy matcher and requires backtracking when there are a lot of ":"
  5484. // characters.
  5485. // This occurs with libc++ but not libstdc++.
  5486. test_raw_request(
  5487. "GET /hi HTTP/1.1\r\n"
  5488. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5489. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5490. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5491. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5492. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5493. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5494. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5495. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5496. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5497. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5498. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5499. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5500. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5501. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5502. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5503. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5504. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5505. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5506. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5507. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5508. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5509. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5510. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5511. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5512. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5513. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5514. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5515. "&&&%%%");
  5516. }
  5517. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5518. // Make sure this doesn't crash the server.
  5519. // In a previous version of the header line regex, the "\r" rendered the line
  5520. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5521. // a new position where the leading white space ended and the field value
  5522. // began.
  5523. // The crash occurs with libc++ but not libstdc++.
  5524. test_raw_request("GET /hi HTTP/1.1\r\n"
  5525. "a:" +
  5526. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5527. "\r\n"
  5528. "\r\n");
  5529. }
  5530. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5531. std::string out;
  5532. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5533. "Content-Type: text/plain\r\n"
  5534. "Transfer-Encoding: chunked\r\n"
  5535. "\r\n"
  5536. "nothex\r\n",
  5537. &out);
  5538. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5539. }
  5540. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5541. std::string out;
  5542. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5543. "Content-Type: text/plain\r\n"
  5544. "Transfer-Encoding: chunked\r\n"
  5545. "\r\n"
  5546. "3\r\n"
  5547. "xyz\r\n"
  5548. "NaN\r\n",
  5549. &out);
  5550. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5551. }
  5552. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5553. std::string out;
  5554. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5555. "Content-Type: text/plain\r\n"
  5556. "Transfer-Encoding: chunked\r\n"
  5557. "\r\n"
  5558. // Length is too large for 64 bits.
  5559. "1ffffffffffffffff\r\n"
  5560. "xyz\r\n",
  5561. &out);
  5562. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5563. }
  5564. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5565. test_raw_request("GET /hi HTTP/1.1\r\n"
  5566. "Content-Type: text/plain\r\n\r");
  5567. }
  5568. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5569. std::string out;
  5570. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5571. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5572. }
  5573. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5574. std::string out;
  5575. std::string request(
  5576. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5577. test_raw_request(request, &out);
  5578. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5579. }
  5580. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5581. std::string out;
  5582. std::string request(
  5583. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5584. test_raw_request(request, &out);
  5585. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5586. }
  5587. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5588. std::string out;
  5589. std::string request(
  5590. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5591. test_raw_request(request, &out);
  5592. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5593. }
  5594. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5595. std::string out;
  5596. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5597. "Test: \r\n\r\n",
  5598. &out);
  5599. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5600. }
  5601. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5602. Server svr;
  5603. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5604. res.set_header("Cache-Control", "no-cache");
  5605. res.set_chunked_content_provider(
  5606. "text/event-stream", [](size_t offset, DataSink &sink) {
  5607. std::string s = "data:";
  5608. s += std::to_string(offset);
  5609. s += "\n\n";
  5610. auto ret = sink.write(s.data(), s.size());
  5611. EXPECT_TRUE(ret);
  5612. std::this_thread::sleep_for(std::chrono::seconds(1));
  5613. return true;
  5614. });
  5615. });
  5616. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5617. svr.wait_until_ready();
  5618. Client client(HOST, PORT);
  5619. const Headers headers = {{"Accept", "text/event-stream"}};
  5620. auto get_thread = std::thread([&client, &headers]() {
  5621. auto res = client.Get(
  5622. "/events", headers,
  5623. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5624. });
  5625. auto se = detail::scope_exit([&] {
  5626. svr.stop();
  5627. get_thread.join();
  5628. listen_thread.join();
  5629. ASSERT_FALSE(svr.is_running());
  5630. });
  5631. // Give GET time to get a few messages.
  5632. std::this_thread::sleep_for(std::chrono::seconds(2));
  5633. }
  5634. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5635. httplib::Server svr;
  5636. svr.Post("/hi",
  5637. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5638. res.status = StatusCode::OK_200;
  5639. });
  5640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5641. svr.wait_until_ready();
  5642. Client cli(HOST, PORT);
  5643. auto res = cli.Post("/hi", "data", "text/plain");
  5644. ASSERT_TRUE(res);
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. svr.stop();
  5647. thread.join();
  5648. ASSERT_FALSE(svr.is_running());
  5649. res = cli.Post("/hi", "data", "text/plain");
  5650. ASSERT_FALSE(res);
  5651. }
  5652. TEST(ServerStopTest, ListenFailure) {
  5653. Server svr;
  5654. auto t = thread([&]() {
  5655. auto ret = svr.listen("????", PORT);
  5656. EXPECT_FALSE(ret);
  5657. });
  5658. svr.wait_until_ready();
  5659. svr.stop();
  5660. t.join();
  5661. }
  5662. TEST(ServerStopTest, Decommision) {
  5663. Server svr;
  5664. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5665. for (int i = 0; i < 4; i++) {
  5666. auto is_even = !(i % 2);
  5667. std::thread t{[&] {
  5668. try {
  5669. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5670. if (is_even) {
  5671. throw std::runtime_error("Some thing that happens to go wrong.");
  5672. }
  5673. svr.listen(HOST, PORT);
  5674. } catch (...) { svr.decommission(); }
  5675. }};
  5676. svr.wait_until_ready();
  5677. // Server is up
  5678. {
  5679. Client cli(HOST, PORT);
  5680. auto res = cli.Get("/hi");
  5681. if (is_even) {
  5682. EXPECT_FALSE(res);
  5683. } else {
  5684. EXPECT_TRUE(res);
  5685. EXPECT_EQ("hi...", res->body);
  5686. }
  5687. }
  5688. svr.stop();
  5689. t.join();
  5690. // Server is down...
  5691. {
  5692. Client cli(HOST, PORT);
  5693. auto res = cli.Get("/hi");
  5694. EXPECT_FALSE(res);
  5695. }
  5696. }
  5697. }
  5698. // Helper function for string body upload progress tests
  5699. template <typename SetupHandler, typename ClientCall>
  5700. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5701. ClientCall &&client_call,
  5702. const string &body) {
  5703. Server svr;
  5704. setup_handler(svr);
  5705. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5706. auto se = detail::scope_exit([&] {
  5707. svr.stop();
  5708. t.join();
  5709. });
  5710. svr.wait_until_ready();
  5711. Client cli(HOST, PORT);
  5712. vector<uint64_t> progress_values;
  5713. bool progress_called = false;
  5714. auto res =
  5715. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5716. progress_values.push_back(current);
  5717. progress_called = true;
  5718. return true;
  5719. });
  5720. ASSERT_TRUE(res);
  5721. EXPECT_EQ(200, res->status);
  5722. EXPECT_TRUE(progress_called);
  5723. }
  5724. TEST(UploadProgressTest, PostStringBodyBasic) {
  5725. TestStringBodyUploadProgress(
  5726. [](Server &svr) {
  5727. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5728. res.set_content("received", "text/plain");
  5729. });
  5730. },
  5731. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5732. return cli.Post("/test", body, "text/plain", progress_callback);
  5733. },
  5734. "test data for upload progress");
  5735. }
  5736. TEST(UploadProgressTest, PutStringBodyBasic) {
  5737. TestStringBodyUploadProgress(
  5738. [](Server &svr) {
  5739. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5740. res.set_content("put received", "text/plain");
  5741. });
  5742. },
  5743. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5744. return cli.Put("/test", body, "text/plain", progress_callback);
  5745. },
  5746. "put test data for upload progress");
  5747. }
  5748. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5749. TestStringBodyUploadProgress(
  5750. [](Server &svr) {
  5751. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5752. res.set_content("patch received", "text/plain");
  5753. });
  5754. },
  5755. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5756. return cli.Patch("/test", body, "text/plain", progress_callback);
  5757. },
  5758. "patch test data for upload progress");
  5759. }
  5760. // Helper function for content provider upload progress tests
  5761. template <typename SetupHandler, typename ClientCall>
  5762. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5763. ClientCall &&client_call) {
  5764. Server svr;
  5765. setup_handler(svr);
  5766. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5767. auto se = detail::scope_exit([&] {
  5768. svr.stop();
  5769. t.join();
  5770. });
  5771. svr.wait_until_ready();
  5772. Client cli(HOST, PORT);
  5773. vector<uint64_t> progress_values;
  5774. auto res =
  5775. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5776. progress_values.push_back(current);
  5777. return true;
  5778. });
  5779. ASSERT_TRUE(res);
  5780. EXPECT_EQ(200, res->status);
  5781. EXPECT_FALSE(progress_values.empty());
  5782. }
  5783. TEST(UploadProgressTest, PostContentProviderProgress) {
  5784. TestContentProviderUploadProgress(
  5785. [](Server &svr) {
  5786. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5787. res.set_content("provider received", "text/plain");
  5788. });
  5789. },
  5790. [](Client &cli, UploadProgress progress_callback) {
  5791. return cli.Post(
  5792. "/test", 10,
  5793. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5794. sink.os << "test data";
  5795. return true;
  5796. },
  5797. "text/plain", progress_callback);
  5798. });
  5799. }
  5800. // Helper function for multipart upload progress tests
  5801. template <typename SetupHandler, typename ClientCall>
  5802. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5803. ClientCall &&client_call,
  5804. const string &endpoint) {
  5805. Server svr;
  5806. setup_handler(svr);
  5807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5808. auto se = detail::scope_exit([&] {
  5809. svr.stop();
  5810. t.join();
  5811. });
  5812. svr.wait_until_ready();
  5813. Client cli(HOST, PORT);
  5814. vector<uint64_t> progress_values;
  5815. UploadFormDataItems items = {
  5816. {"field1", "value1", "", ""},
  5817. {"field2", "longer value for progress tracking test", "", ""},
  5818. {"file1", "file content data for upload progress", "test.txt",
  5819. "text/plain"}};
  5820. auto res = client_call(cli, endpoint, items,
  5821. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5822. progress_values.push_back(current);
  5823. return true;
  5824. });
  5825. ASSERT_TRUE(res);
  5826. EXPECT_EQ(200, res->status);
  5827. EXPECT_FALSE(progress_values.empty());
  5828. }
  5829. TEST(UploadProgressTest, PostMultipartProgress) {
  5830. TestMultipartUploadProgress(
  5831. [](Server &svr) {
  5832. svr.Post("/multipart", [](const Request &req, Response &res) {
  5833. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5834. res.set_content("multipart received", "text/plain");
  5835. });
  5836. },
  5837. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5838. UploadProgress progress_callback) {
  5839. return cli.Post(endpoint, items, progress_callback);
  5840. },
  5841. "/multipart");
  5842. }
  5843. // Helper function for basic download progress tests
  5844. template <typename SetupHandler, typename ClientCall>
  5845. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5846. ClientCall &&client_call, const string &endpoint,
  5847. size_t expected_content_size) {
  5848. Server svr;
  5849. setup_handler(svr);
  5850. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5851. auto se = detail::scope_exit([&] {
  5852. svr.stop();
  5853. t.join();
  5854. });
  5855. svr.wait_until_ready();
  5856. Client cli(HOST, PORT);
  5857. vector<uint64_t> progress_values;
  5858. auto res = client_call(cli, endpoint,
  5859. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5860. progress_values.push_back(current);
  5861. return true;
  5862. });
  5863. ASSERT_TRUE(res);
  5864. EXPECT_EQ(200, res->status);
  5865. EXPECT_FALSE(progress_values.empty());
  5866. EXPECT_EQ(expected_content_size, res->body.size());
  5867. }
  5868. TEST(DownloadProgressTest, GetBasic) {
  5869. TestBasicDownloadProgress(
  5870. [](Server &svr) {
  5871. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5872. string content(1000, 'D');
  5873. res.set_content(content, "text/plain");
  5874. });
  5875. },
  5876. [](Client &cli, const string &endpoint,
  5877. DownloadProgress progress_callback) {
  5878. return cli.Get(endpoint, progress_callback);
  5879. },
  5880. "/download", 1000u);
  5881. }
  5882. // Helper function for content receiver download progress tests
  5883. template <typename SetupHandler, typename ClientCall>
  5884. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5885. ClientCall &&client_call,
  5886. const string &endpoint,
  5887. size_t expected_content_size) {
  5888. Server svr;
  5889. setup_handler(svr);
  5890. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5891. auto se = detail::scope_exit([&] {
  5892. svr.stop();
  5893. t.join();
  5894. });
  5895. svr.wait_until_ready();
  5896. Client cli(HOST, PORT);
  5897. vector<uint64_t> progress_values;
  5898. string received_body;
  5899. auto res = client_call(
  5900. cli, endpoint,
  5901. [&](const char *data, size_t data_length) -> bool {
  5902. received_body.append(data, data_length);
  5903. return true;
  5904. },
  5905. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5906. progress_values.push_back(current);
  5907. return true;
  5908. });
  5909. ASSERT_TRUE(res);
  5910. EXPECT_EQ(200, res->status);
  5911. EXPECT_FALSE(progress_values.empty());
  5912. EXPECT_EQ(expected_content_size, received_body.size());
  5913. EXPECT_TRUE(res->body.empty());
  5914. }
  5915. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5916. TestContentReceiverDownloadProgress(
  5917. [](Server &svr) {
  5918. svr.Get("/download-receiver",
  5919. [](const Request & /*req*/, Response &res) {
  5920. string content(2000, 'R');
  5921. res.set_content(content, "text/plain");
  5922. });
  5923. },
  5924. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5925. DownloadProgress progress_callback) {
  5926. return cli.Get(endpoint, content_receiver, progress_callback);
  5927. },
  5928. "/download-receiver", 2000u);
  5929. }
  5930. TEST(StreamingTest, NoContentLengthStreaming) {
  5931. Server svr;
  5932. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5933. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5934. if (offset < 6) {
  5935. sink.os << (offset < 3 ? "a" : "b");
  5936. } else {
  5937. sink.done();
  5938. }
  5939. return true;
  5940. });
  5941. });
  5942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5943. auto listen_se = detail::scope_exit([&] {
  5944. svr.stop();
  5945. listen_thread.join();
  5946. ASSERT_FALSE(svr.is_running());
  5947. });
  5948. svr.wait_until_ready();
  5949. Client client(HOST, PORT);
  5950. auto get_thread = std::thread([&client]() {
  5951. std::string s;
  5952. auto res =
  5953. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  5954. s += std::string(data, len);
  5955. return true;
  5956. });
  5957. ASSERT_TRUE(res);
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("aaabbb", s);
  5960. });
  5961. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  5962. // Give GET time to get a few messages.
  5963. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5964. }
  5965. TEST(MountTest, Unmount) {
  5966. Server svr;
  5967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5968. auto se = detail::scope_exit([&] {
  5969. svr.stop();
  5970. listen_thread.join();
  5971. ASSERT_FALSE(svr.is_running());
  5972. });
  5973. svr.wait_until_ready();
  5974. Client cli("localhost", PORT);
  5975. svr.set_mount_point("/mount2", "./www2");
  5976. auto res = cli.Get("/");
  5977. ASSERT_TRUE(res);
  5978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5979. res = cli.Get("/mount2/dir/test.html");
  5980. ASSERT_TRUE(res);
  5981. EXPECT_EQ(StatusCode::OK_200, res->status);
  5982. svr.set_mount_point("/", "./www");
  5983. res = cli.Get("/dir/");
  5984. ASSERT_TRUE(res);
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. svr.remove_mount_point("/");
  5987. res = cli.Get("/dir/");
  5988. ASSERT_TRUE(res);
  5989. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5990. svr.remove_mount_point("/mount2");
  5991. res = cli.Get("/mount2/dir/test.html");
  5992. ASSERT_TRUE(res);
  5993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5994. }
  5995. TEST(MountTest, Redicect) {
  5996. Server svr;
  5997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5998. auto se = detail::scope_exit([&] {
  5999. svr.stop();
  6000. listen_thread.join();
  6001. ASSERT_FALSE(svr.is_running());
  6002. });
  6003. svr.set_mount_point("/", "./www");
  6004. svr.wait_until_ready();
  6005. Client cli("localhost", PORT);
  6006. auto res = cli.Get("/dir/");
  6007. ASSERT_TRUE(res);
  6008. EXPECT_EQ(StatusCode::OK_200, res->status);
  6009. res = cli.Get("/dir");
  6010. ASSERT_TRUE(res);
  6011. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6012. res = cli.Get("/file");
  6013. ASSERT_TRUE(res);
  6014. EXPECT_EQ(StatusCode::OK_200, res->status);
  6015. res = cli.Get("/file/");
  6016. ASSERT_TRUE(res);
  6017. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6018. cli.set_follow_location(true);
  6019. res = cli.Get("/dir");
  6020. ASSERT_TRUE(res);
  6021. EXPECT_EQ(StatusCode::OK_200, res->status);
  6022. }
  6023. TEST(MountTest, MultibytesPathName) {
  6024. Server svr;
  6025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6026. auto se = detail::scope_exit([&] {
  6027. svr.stop();
  6028. listen_thread.join();
  6029. ASSERT_FALSE(svr.is_running());
  6030. });
  6031. svr.set_mount_point("/", "./www");
  6032. svr.wait_until_ready();
  6033. Client cli("localhost", PORT);
  6034. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6035. ASSERT_TRUE(res);
  6036. EXPECT_EQ(StatusCode::OK_200, res->status);
  6037. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6038. }
  6039. TEST(KeepAliveTest, ReadTimeout) {
  6040. Server svr;
  6041. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6042. std::this_thread::sleep_for(std::chrono::seconds(2));
  6043. res.set_content("a", "text/plain");
  6044. });
  6045. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6046. res.set_content("b", "text/plain");
  6047. });
  6048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6049. auto se = detail::scope_exit([&] {
  6050. svr.stop();
  6051. listen_thread.join();
  6052. ASSERT_FALSE(svr.is_running());
  6053. });
  6054. svr.wait_until_ready();
  6055. Client cli("localhost", PORT);
  6056. cli.set_keep_alive(true);
  6057. cli.set_read_timeout(std::chrono::seconds(1));
  6058. auto resa = cli.Get("/a");
  6059. ASSERT_FALSE(resa);
  6060. EXPECT_EQ(Error::Read, resa.error());
  6061. auto resb = cli.Get("/b");
  6062. ASSERT_TRUE(resb);
  6063. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6064. EXPECT_EQ("b", resb->body);
  6065. }
  6066. TEST(KeepAliveTest, MaxCount) {
  6067. size_t keep_alive_max_count = 3;
  6068. Server svr;
  6069. svr.set_keep_alive_max_count(keep_alive_max_count);
  6070. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6071. res.set_content("Hello World!", "text/plain");
  6072. });
  6073. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6074. auto se = detail::scope_exit([&] {
  6075. svr.stop();
  6076. listen_thread.join();
  6077. ASSERT_FALSE(svr.is_running());
  6078. });
  6079. svr.wait_until_ready();
  6080. Client cli(HOST, PORT);
  6081. cli.set_keep_alive(true);
  6082. for (size_t i = 0; i < 5; i++) {
  6083. auto result = cli.Get("/hi");
  6084. ASSERT_TRUE(result);
  6085. EXPECT_EQ(StatusCode::OK_200, result->status);
  6086. if (i == keep_alive_max_count - 1) {
  6087. EXPECT_EQ("close", result->get_header_value("Connection"));
  6088. } else {
  6089. EXPECT_FALSE(result->has_header("Connection"));
  6090. }
  6091. }
  6092. }
  6093. TEST(KeepAliveTest, Issue1041) {
  6094. Server svr;
  6095. svr.set_keep_alive_timeout(3);
  6096. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6097. res.set_content("Hello World!", "text/plain");
  6098. });
  6099. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6100. auto se = detail::scope_exit([&] {
  6101. svr.stop();
  6102. listen_thread.join();
  6103. ASSERT_FALSE(svr.is_running());
  6104. });
  6105. svr.wait_until_ready();
  6106. Client cli(HOST, PORT);
  6107. cli.set_keep_alive(true);
  6108. auto result = cli.Get("/hi");
  6109. ASSERT_TRUE(result);
  6110. EXPECT_EQ(StatusCode::OK_200, result->status);
  6111. std::this_thread::sleep_for(std::chrono::seconds(5));
  6112. result = cli.Get("/hi");
  6113. ASSERT_TRUE(result);
  6114. EXPECT_EQ(StatusCode::OK_200, result->status);
  6115. }
  6116. TEST(KeepAliveTest, Issue1959) {
  6117. Server svr;
  6118. svr.set_keep_alive_timeout(5);
  6119. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6120. res.set_content("a", "text/plain");
  6121. });
  6122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6123. auto se = detail::scope_exit([&] {
  6124. if (!svr.is_running()) return;
  6125. svr.stop();
  6126. listen_thread.join();
  6127. ASSERT_FALSE(svr.is_running());
  6128. });
  6129. svr.wait_until_ready();
  6130. Client cli("localhost", PORT);
  6131. cli.set_keep_alive(true);
  6132. using namespace std::chrono;
  6133. auto start = steady_clock::now();
  6134. cli.Get("/a");
  6135. svr.stop();
  6136. listen_thread.join();
  6137. auto end = steady_clock::now();
  6138. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6139. EXPECT_LT(elapsed, 5000);
  6140. }
  6141. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6142. TEST(KeepAliveTest, SSLClientReconnection) {
  6143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6144. ASSERT_TRUE(svr.is_valid());
  6145. svr.set_keep_alive_timeout(1);
  6146. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6147. res.set_content("Hello World!", "text/plain");
  6148. });
  6149. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6150. auto se = detail::scope_exit([&] {
  6151. svr.stop();
  6152. listen_thread.join();
  6153. ASSERT_FALSE(svr.is_running());
  6154. });
  6155. svr.wait_until_ready();
  6156. SSLClient cli(HOST, PORT);
  6157. cli.enable_server_certificate_verification(false);
  6158. cli.set_keep_alive(true);
  6159. auto result = cli.Get("/hi");
  6160. ASSERT_TRUE(result);
  6161. EXPECT_EQ(StatusCode::OK_200, result->status);
  6162. result = cli.Get("/hi");
  6163. ASSERT_TRUE(result);
  6164. EXPECT_EQ(StatusCode::OK_200, result->status);
  6165. std::this_thread::sleep_for(std::chrono::seconds(2));
  6166. // Recoonect
  6167. result = cli.Get("/hi");
  6168. ASSERT_TRUE(result);
  6169. EXPECT_EQ(StatusCode::OK_200, result->status);
  6170. result = cli.Get("/hi");
  6171. ASSERT_TRUE(result);
  6172. EXPECT_EQ(StatusCode::OK_200, result->status);
  6173. }
  6174. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6176. ASSERT_TRUE(svr.is_valid());
  6177. svr.set_keep_alive_timeout(1);
  6178. std::string content = "reconnect";
  6179. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6180. res.set_content("Hello World!", "text/plain");
  6181. });
  6182. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6183. auto se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. listen_thread.join();
  6186. ASSERT_FALSE(svr.is_running());
  6187. });
  6188. svr.wait_until_ready();
  6189. SSLClient cli(HOST, PORT);
  6190. cli.enable_server_certificate_verification(false);
  6191. cli.set_keep_alive(true);
  6192. auto result = cli.Post(
  6193. "/hi", content.size(),
  6194. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6195. sink.write(content.c_str(), content.size());
  6196. return true;
  6197. },
  6198. "text/plain");
  6199. ASSERT_TRUE(result);
  6200. EXPECT_EQ(200, result->status);
  6201. std::this_thread::sleep_for(std::chrono::seconds(2));
  6202. // Recoonect
  6203. result = cli.Post(
  6204. "/hi", content.size(),
  6205. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6206. sink.write(content.c_str(), content.size());
  6207. return true;
  6208. },
  6209. "text/plain");
  6210. ASSERT_TRUE(result);
  6211. EXPECT_EQ(200, result->status);
  6212. result = cli.Post(
  6213. "/hi", content.size(),
  6214. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6215. sink.write(content.c_str(), content.size());
  6216. return true;
  6217. },
  6218. "text/plain");
  6219. ASSERT_TRUE(result);
  6220. EXPECT_EQ(200, result->status);
  6221. }
  6222. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6223. {
  6224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6225. ASSERT_TRUE(svr.is_valid());
  6226. svr.Get("/sni", [&](const Request &req, Response &res) {
  6227. std::string expected;
  6228. if (req.ssl) {
  6229. if (const char *sni =
  6230. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6231. expected = sni;
  6232. }
  6233. }
  6234. EXPECT_EQ(expected, req.get_param_value("expected"));
  6235. res.set_content("ok", "text/plain");
  6236. });
  6237. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. listen_thread.join();
  6241. ASSERT_FALSE(svr.is_running());
  6242. });
  6243. svr.wait_until_ready();
  6244. {
  6245. SSLClient cli("localhost", PORT);
  6246. cli.enable_server_certificate_verification(false);
  6247. auto res = cli.Get("/sni?expected=localhost");
  6248. ASSERT_TRUE(res);
  6249. }
  6250. {
  6251. SSLClient cli("::1", PORT);
  6252. cli.enable_server_certificate_verification(false);
  6253. auto res = cli.Get("/sni?expected=");
  6254. ASSERT_TRUE(res);
  6255. }
  6256. }
  6257. }
  6258. #endif
  6259. TEST(ClientProblemDetectionTest, ContentProvider) {
  6260. Server svr;
  6261. size_t content_length = 1024 * 1024;
  6262. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6263. res.set_content_provider(
  6264. content_length, "text/plain",
  6265. [&](size_t offset, size_t length, DataSink &sink) {
  6266. auto out_len = std::min(length, static_cast<size_t>(1024));
  6267. std::string out(out_len, '@');
  6268. sink.write(out.data(), out_len);
  6269. return offset < 4096;
  6270. },
  6271. [](bool success) { ASSERT_FALSE(success); });
  6272. });
  6273. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6274. res.set_content_provider(
  6275. 0, "text/plain",
  6276. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6277. EXPECT_TRUE(false);
  6278. return true;
  6279. },
  6280. [](bool success) { ASSERT_FALSE(success); });
  6281. });
  6282. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6283. auto se = detail::scope_exit([&] {
  6284. svr.stop();
  6285. listen_thread.join();
  6286. ASSERT_FALSE(svr.is_running());
  6287. });
  6288. svr.wait_until_ready();
  6289. Client cli("localhost", PORT);
  6290. {
  6291. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6292. size_t /*data_length*/) { return false; });
  6293. ASSERT_FALSE(res);
  6294. }
  6295. {
  6296. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6297. size_t /*data_length*/) { return false; });
  6298. ASSERT_TRUE(res);
  6299. }
  6300. }
  6301. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6302. Server svr;
  6303. svr.set_error_handler([](Request const &, Response &res) -> void {
  6304. res.set_chunked_content_provider(
  6305. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6306. sink.os << "hello";
  6307. sink.os << "world";
  6308. sink.done();
  6309. return true;
  6310. });
  6311. });
  6312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6313. auto se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. listen_thread.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client cli("localhost", PORT);
  6320. auto res = cli.Get("/");
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6323. EXPECT_EQ("helloworld", res->body);
  6324. }
  6325. TEST(LongPollingTest, ClientCloseDetection) {
  6326. Server svr;
  6327. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6328. res.set_chunked_content_provider(
  6329. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6330. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6331. sink.os << "hello";
  6332. auto count = 10;
  6333. while (count > 0 && sink.is_writable()) {
  6334. this_thread::sleep_for(chrono::milliseconds(10));
  6335. count--;
  6336. }
  6337. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6338. return true;
  6339. });
  6340. });
  6341. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6342. auto se = detail::scope_exit([&] {
  6343. svr.stop();
  6344. listen_thread.join();
  6345. ASSERT_FALSE(svr.is_running());
  6346. });
  6347. svr.wait_until_ready();
  6348. Client cli("localhost", PORT);
  6349. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6350. EXPECT_EQ("hello", string(data, data_length));
  6351. return false; // close the socket immediately.
  6352. });
  6353. ASSERT_FALSE(res);
  6354. }
  6355. TEST(GetWithParametersTest, GetWithParameters) {
  6356. Server svr;
  6357. svr.Get("/", [&](const Request &req, Response &) {
  6358. EXPECT_EQ("world", req.get_param_value("hello"));
  6359. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6360. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6361. });
  6362. svr.Get("/params", [&](const Request &req, Response &) {
  6363. EXPECT_EQ("world", req.get_param_value("hello"));
  6364. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6365. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6366. });
  6367. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6368. EXPECT_EQ("resource-id", req.matches[1]);
  6369. EXPECT_EQ("foo", req.get_param_value("param1"));
  6370. EXPECT_EQ("bar", req.get_param_value("param2"));
  6371. });
  6372. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6373. EXPECT_EQ("user-id", req.path_params.at("id"));
  6374. EXPECT_EQ("foo", req.get_param_value("param1"));
  6375. EXPECT_EQ("bar", req.get_param_value("param2"));
  6376. });
  6377. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6378. auto se = detail::scope_exit([&] {
  6379. svr.stop();
  6380. listen_thread.join();
  6381. ASSERT_FALSE(svr.is_running());
  6382. });
  6383. svr.wait_until_ready();
  6384. {
  6385. Client cli(HOST, PORT);
  6386. Params params;
  6387. params.emplace("hello", "world");
  6388. params.emplace("hello2", "world2");
  6389. params.emplace("hello3", "world3");
  6390. auto res = cli.Get("/", params, Headers{});
  6391. ASSERT_TRUE(res);
  6392. EXPECT_EQ(StatusCode::OK_200, res->status);
  6393. }
  6394. {
  6395. Client cli(HOST, PORT);
  6396. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6397. ASSERT_TRUE(res);
  6398. EXPECT_EQ(StatusCode::OK_200, res->status);
  6399. }
  6400. {
  6401. Client cli(HOST, PORT);
  6402. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6403. ASSERT_TRUE(res);
  6404. EXPECT_EQ(StatusCode::OK_200, res->status);
  6405. }
  6406. {
  6407. Client cli(HOST, PORT);
  6408. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6409. ASSERT_TRUE(res);
  6410. EXPECT_EQ(StatusCode::OK_200, res->status);
  6411. }
  6412. }
  6413. TEST(GetWithParametersTest, GetWithParameters2) {
  6414. Server svr;
  6415. svr.Get("/", [&](const Request &req, Response &res) {
  6416. auto text = req.get_param_value("hello");
  6417. res.set_content(text, "text/plain");
  6418. });
  6419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6420. auto se = detail::scope_exit([&] {
  6421. svr.stop();
  6422. listen_thread.join();
  6423. ASSERT_FALSE(svr.is_running());
  6424. });
  6425. svr.wait_until_ready();
  6426. Client cli("localhost", PORT);
  6427. Params params;
  6428. params.emplace("hello", "world");
  6429. std::string body;
  6430. auto res = cli.Get("/", params, Headers{},
  6431. [&](const char *data, size_t data_length) {
  6432. body.append(data, data_length);
  6433. return true;
  6434. });
  6435. ASSERT_TRUE(res);
  6436. EXPECT_EQ(StatusCode::OK_200, res->status);
  6437. EXPECT_EQ("world", body);
  6438. }
  6439. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6440. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6441. auto host = "httpbin.org";
  6442. auto path = std::string{"/range/32"};
  6443. #else
  6444. auto host = "nghttp2.org";
  6445. auto path = std::string{"/httpbin/range/32"};
  6446. #endif
  6447. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6448. SSLClient cli(host);
  6449. #else
  6450. Client cli(host);
  6451. #endif
  6452. cli.set_default_headers({make_range_header({{1, 10}})});
  6453. cli.set_connection_timeout(5);
  6454. {
  6455. auto res = cli.Get(path);
  6456. ASSERT_TRUE(res);
  6457. EXPECT_EQ("bcdefghijk", res->body);
  6458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6459. }
  6460. {
  6461. auto res = cli.Get(path);
  6462. ASSERT_TRUE(res);
  6463. EXPECT_EQ("bcdefghijk", res->body);
  6464. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6465. }
  6466. }
  6467. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6468. Server svr;
  6469. svr.set_default_headers({{"Hello", "World"}});
  6470. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6471. res.set_content("ok", "text/plain");
  6472. });
  6473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6474. auto se = detail::scope_exit([&] {
  6475. svr.stop();
  6476. listen_thread.join();
  6477. ASSERT_FALSE(svr.is_running());
  6478. });
  6479. svr.wait_until_ready();
  6480. Client cli("localhost", PORT);
  6481. auto res = cli.Get("/");
  6482. ASSERT_TRUE(res);
  6483. EXPECT_EQ(StatusCode::OK_200, res->status);
  6484. EXPECT_EQ("ok", res->body);
  6485. EXPECT_EQ("World", res->get_header_value("Hello"));
  6486. }
  6487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6488. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6489. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6490. ASSERT_TRUE(svr.is_valid());
  6491. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6492. std::this_thread::sleep_for(std::chrono::seconds(2));
  6493. res.set_content("a", "text/plain");
  6494. });
  6495. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6496. res.set_content("b", "text/plain");
  6497. });
  6498. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6499. auto se = detail::scope_exit([&] {
  6500. svr.stop();
  6501. listen_thread.join();
  6502. ASSERT_FALSE(svr.is_running());
  6503. });
  6504. svr.wait_until_ready();
  6505. SSLClient cli("localhost", PORT);
  6506. cli.enable_server_certificate_verification(false);
  6507. cli.set_keep_alive(true);
  6508. cli.set_read_timeout(std::chrono::seconds(1));
  6509. auto resa = cli.Get("/a");
  6510. ASSERT_TRUE(!resa);
  6511. EXPECT_EQ(Error::Read, resa.error());
  6512. auto resb = cli.Get("/b");
  6513. ASSERT_TRUE(resb);
  6514. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6515. EXPECT_EQ("b", resb->body);
  6516. }
  6517. #endif
  6518. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6519. protected:
  6520. ServerTestWithAI_PASSIVE()
  6521. : cli_(HOST, PORT)
  6522. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6523. ,
  6524. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6525. #endif
  6526. {
  6527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6528. cli_.enable_server_certificate_verification(false);
  6529. #endif
  6530. }
  6531. virtual void SetUp() {
  6532. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6533. res.set_content("Hello World!", "text/plain");
  6534. });
  6535. t_ = thread(
  6536. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6537. svr_.wait_until_ready();
  6538. }
  6539. virtual void TearDown() {
  6540. svr_.stop();
  6541. t_.join();
  6542. }
  6543. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6544. SSLClient cli_;
  6545. SSLServer svr_;
  6546. #else
  6547. Client cli_;
  6548. Server svr_;
  6549. #endif
  6550. thread t_;
  6551. };
  6552. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6553. auto res = cli_.Get("/hi");
  6554. ASSERT_TRUE(res);
  6555. EXPECT_EQ(StatusCode::OK_200, res->status);
  6556. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6557. EXPECT_EQ("Hello World!", res->body);
  6558. }
  6559. class ServerUpDownTest : public ::testing::Test {
  6560. protected:
  6561. ServerUpDownTest() : cli_(HOST, PORT) {}
  6562. virtual void SetUp() {
  6563. t_ = thread([&]() {
  6564. svr_.bind_to_any_port(HOST);
  6565. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6566. ASSERT_TRUE(svr_.listen_after_bind());
  6567. });
  6568. svr_.wait_until_ready();
  6569. }
  6570. virtual void TearDown() {
  6571. svr_.stop();
  6572. t_.join();
  6573. }
  6574. Client cli_;
  6575. Server svr_;
  6576. thread t_;
  6577. };
  6578. TEST_F(ServerUpDownTest, QuickStartStop) {
  6579. // Should not crash, especially when run with
  6580. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6581. }
  6582. class PayloadMaxLengthTest : public ::testing::Test {
  6583. protected:
  6584. PayloadMaxLengthTest()
  6585. : cli_(HOST, PORT)
  6586. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6587. ,
  6588. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6589. #endif
  6590. {
  6591. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6592. cli_.enable_server_certificate_verification(false);
  6593. #endif
  6594. }
  6595. virtual void SetUp() {
  6596. svr_.set_payload_max_length(8);
  6597. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6598. res.set_content("test", "text/plain");
  6599. });
  6600. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6601. svr_.wait_until_ready();
  6602. }
  6603. virtual void TearDown() {
  6604. svr_.stop();
  6605. t_.join();
  6606. }
  6607. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6608. SSLClient cli_;
  6609. SSLServer svr_;
  6610. #else
  6611. Client cli_;
  6612. Server svr_;
  6613. #endif
  6614. thread t_;
  6615. };
  6616. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6617. auto res = cli_.Post("/test", "123456789", "text/plain");
  6618. ASSERT_TRUE(res);
  6619. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6620. res = cli_.Post("/test", "12345678", "text/plain");
  6621. ASSERT_TRUE(res);
  6622. EXPECT_EQ(StatusCode::OK_200, res->status);
  6623. }
  6624. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6625. // Test chunked encoding with payload exceeding the 8-byte limit
  6626. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6627. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6628. ASSERT_TRUE(res);
  6629. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6630. }
  6631. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6632. // Test chunked encoding with payload within the 8-byte limit
  6633. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6634. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6635. ASSERT_TRUE(res);
  6636. EXPECT_EQ(StatusCode::OK_200, res->status);
  6637. }
  6638. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6639. // Test using send_request to send chunked data exceeding payload limit
  6640. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6641. "Host: " +
  6642. std::string(HOST) + ":" + std::to_string(PORT) +
  6643. "\r\n"
  6644. "Transfer-Encoding: chunked\r\n"
  6645. "Connection: close\r\n"
  6646. "\r\n"
  6647. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6648. "0123456789\r\n"
  6649. "0\r\n" // End chunk
  6650. "\r\n";
  6651. std::string response;
  6652. bool result = send_request(1, chunked_request, &response);
  6653. if (!result) {
  6654. // If send_request fails, it might be because the server closed the
  6655. // connection due to payload limit enforcement, which is acceptable
  6656. SUCCEED()
  6657. << "Server rejected oversized chunked request (connection closed)";
  6658. } else {
  6659. // If we got a response, check if it's an error response or connection was
  6660. // closed early Short response length indicates connection was closed due to
  6661. // payload limit
  6662. if (response.length() <= 10) {
  6663. SUCCEED() << "Server closed connection for oversized chunked request";
  6664. } else {
  6665. // Check for error status codes
  6666. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6667. response.find("Payload Too Large") != std::string::npos ||
  6668. response.find("400") != std::string::npos);
  6669. }
  6670. }
  6671. }
  6672. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6673. // Test request without Content-Length header exceeding payload limit
  6674. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6675. "Host: " +
  6676. std::string(HOST) + ":" +
  6677. std::to_string(PORT) +
  6678. "\r\n"
  6679. "Connection: close\r\n"
  6680. "\r\n";
  6681. // Add payload exceeding the 8-byte limit
  6682. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6683. request_without_content_length += large_payload;
  6684. std::string response;
  6685. bool result = send_request(1, request_without_content_length, &response);
  6686. if (!result) {
  6687. // If send_request fails, server likely closed connection due to payload
  6688. // limit
  6689. SUCCEED() << "Server rejected oversized request without Content-Length "
  6690. "(connection closed)";
  6691. } else {
  6692. // Check if server responded with error or closed connection early
  6693. if (response.length() <= 10) {
  6694. SUCCEED() << "Server closed connection for oversized request without "
  6695. "Content-Length";
  6696. } else {
  6697. // Check for error status codes
  6698. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6699. response.find("Payload Too Large") != std::string::npos ||
  6700. response.find("400") != std::string::npos);
  6701. }
  6702. }
  6703. }
  6704. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6705. // Test request without Content-Length header within payload limit
  6706. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6707. "Host: " +
  6708. std::string(HOST) + ":" +
  6709. std::to_string(PORT) +
  6710. "\r\n"
  6711. "Connection: close\r\n"
  6712. "\r\n";
  6713. // Add payload within the 8-byte limit
  6714. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6715. request_without_content_length += small_payload;
  6716. std::string response;
  6717. bool result = send_request(1, request_without_content_length, &response);
  6718. // For requests without Content-Length, the server may have different behavior
  6719. // The key is that it should not reject due to payload limit for small
  6720. // payloads
  6721. if (result) {
  6722. // Check for any HTTP response (success or error, but not connection closed)
  6723. if (response.length() > 10) {
  6724. SUCCEED()
  6725. << "Server processed request without Content-Length within limit";
  6726. } else {
  6727. // Short response might indicate connection closed, which is acceptable
  6728. SUCCEED() << "Server closed connection for request without "
  6729. "Content-Length (acceptable behavior)";
  6730. }
  6731. } else {
  6732. // Connection failure might be due to protocol requirements
  6733. SUCCEED() << "Connection issue with request without Content-Length "
  6734. "(environment-specific)";
  6735. }
  6736. }
  6737. class LargePayloadMaxLengthTest : public ::testing::Test {
  6738. protected:
  6739. LargePayloadMaxLengthTest()
  6740. : cli_(HOST, PORT)
  6741. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6742. ,
  6743. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6744. #endif
  6745. {
  6746. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6747. cli_.enable_server_certificate_verification(false);
  6748. #endif
  6749. }
  6750. virtual void SetUp() {
  6751. // Set 10MB payload limit
  6752. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6753. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6754. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6755. res.set_content("Large payload test", "text/plain");
  6756. });
  6757. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6758. svr_.wait_until_ready();
  6759. }
  6760. virtual void TearDown() {
  6761. svr_.stop();
  6762. t_.join();
  6763. }
  6764. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6765. SSLClient cli_;
  6766. SSLServer svr_;
  6767. #else
  6768. Client cli_;
  6769. Server svr_;
  6770. #endif
  6771. thread t_;
  6772. };
  6773. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6774. // Test chunked encoding with payload within 10MB limit
  6775. std::string medium_payload(5 * 1024 * 1024,
  6776. 'A'); // 5MB payload, within 10MB limit
  6777. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6778. ASSERT_TRUE(res);
  6779. EXPECT_EQ(StatusCode::OK_200, res->status);
  6780. }
  6781. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6782. // Test chunked encoding with payload exceeding 10MB limit
  6783. std::string large_payload(12 * 1024 * 1024,
  6784. 'B'); // 12MB payload, exceeds 10MB limit
  6785. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6786. ASSERT_TRUE(res);
  6787. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6788. }
  6789. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6790. // Test request without Content-Length header within 10MB limit
  6791. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6792. "Host: " +
  6793. std::string(HOST) + ":" +
  6794. std::to_string(PORT) +
  6795. "\r\n"
  6796. "Connection: close\r\n"
  6797. "\r\n";
  6798. // Add 1MB payload (within 10MB limit)
  6799. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6800. request_without_content_length += medium_payload;
  6801. std::string response;
  6802. bool result = send_request(5, request_without_content_length, &response);
  6803. if (result) {
  6804. // Should get a proper HTTP response for payloads within limit
  6805. if (response.length() > 10) {
  6806. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6807. "10MB limit";
  6808. } else {
  6809. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6810. "Content-Length)";
  6811. }
  6812. } else {
  6813. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6814. }
  6815. }
  6816. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6817. // Test request without Content-Length header exceeding 10MB limit
  6818. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6819. "Host: " +
  6820. std::string(HOST) + ":" +
  6821. std::to_string(PORT) +
  6822. "\r\n"
  6823. "Connection: close\r\n"
  6824. "\r\n";
  6825. // Add 12MB payload (exceeds 10MB limit)
  6826. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6827. request_without_content_length += large_payload;
  6828. std::string response;
  6829. bool result = send_request(10, request_without_content_length, &response);
  6830. if (!result) {
  6831. // Server should close connection due to payload limit
  6832. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6833. "(connection closed)";
  6834. } else {
  6835. // Check for error response
  6836. if (response.length() <= 10) {
  6837. SUCCEED()
  6838. << "Server closed connection for 12MB request exceeding 10MB limit";
  6839. } else {
  6840. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6841. response.find("Payload Too Large") != std::string::npos ||
  6842. response.find("400") != std::string::npos);
  6843. }
  6844. }
  6845. }
  6846. TEST(HostAndPortPropertiesTest, NoSSL) {
  6847. httplib::Client cli("www.google.com", 1234);
  6848. ASSERT_EQ("www.google.com", cli.host());
  6849. ASSERT_EQ(1234, cli.port());
  6850. }
  6851. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6852. httplib::Client cli("www.google.com:1234");
  6853. ASSERT_EQ("www.google.com", cli.host());
  6854. ASSERT_EQ(1234, cli.port());
  6855. }
  6856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6857. TEST(HostAndPortPropertiesTest, SSL) {
  6858. httplib::SSLClient cli("www.google.com");
  6859. ASSERT_EQ("www.google.com", cli.host());
  6860. ASSERT_EQ(443, cli.port());
  6861. }
  6862. #endif
  6863. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6864. TEST(SSLClientTest, UpdateCAStore) {
  6865. httplib::SSLClient httplib_client("www.google.com");
  6866. auto ca_store_1 = X509_STORE_new();
  6867. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6868. nullptr);
  6869. httplib_client.set_ca_cert_store(ca_store_1);
  6870. auto ca_store_2 = X509_STORE_new();
  6871. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6872. nullptr);
  6873. httplib_client.set_ca_cert_store(ca_store_2);
  6874. }
  6875. TEST(SSLClientTest, ServerNameIndication_Online) {
  6876. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6877. auto host = "httpbin.org";
  6878. auto path = std::string{"/get"};
  6879. #else
  6880. auto host = "nghttp2.org";
  6881. auto path = std::string{"/httpbin/get"};
  6882. #endif
  6883. SSLClient cli(host, 443);
  6884. auto res = cli.Get(path);
  6885. ASSERT_TRUE(res);
  6886. ASSERT_EQ(StatusCode::OK_200, res->status);
  6887. }
  6888. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6889. // Use a site that will cause SSL verification failure due to self-signed cert
  6890. SSLClient cli("self-signed.badssl.com", 443);
  6891. cli.enable_server_certificate_verification(true);
  6892. auto res = cli.Get("/");
  6893. ASSERT_TRUE(!res);
  6894. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6895. // For SSL server verification errors, ssl_error should be 0, only
  6896. // ssl_openssl_error should be set
  6897. EXPECT_EQ(0, res.ssl_error());
  6898. // Verify OpenSSL error is captured for SSLServerVerification
  6899. // This occurs when SSL_get_verify_result() returns a verification failure
  6900. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6901. res.ssl_openssl_error());
  6902. }
  6903. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6904. // Use a site where hostname doesn't match the certificate
  6905. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6906. SSLClient cli("wrong.host.badssl.com", 443);
  6907. cli.enable_server_certificate_verification(true);
  6908. cli.enable_server_hostname_verification(true);
  6909. auto res = cli.Get("/");
  6910. ASSERT_TRUE(!res);
  6911. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6912. // For SSL hostname verification errors, ssl_error should be 0, only
  6913. // ssl_openssl_error should be set
  6914. EXPECT_EQ(0, res.ssl_error());
  6915. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6916. // This occurs when verify_host() fails due to hostname mismatch
  6917. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6918. res.ssl_openssl_error());
  6919. }
  6920. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6921. Client cli("https://google.com");
  6922. auto res = cli.Get("/");
  6923. ASSERT_TRUE(res);
  6924. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6925. }
  6926. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6927. SSLClient cli("google.com");
  6928. cli.set_ca_cert_path(CA_CERT_FILE);
  6929. auto res = cli.Get("/");
  6930. ASSERT_TRUE(res);
  6931. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6932. }
  6933. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6934. SSLClient cli("google.com");
  6935. cli.enable_server_certificate_verification(true);
  6936. cli.set_ca_cert_path("hello");
  6937. auto res = cli.Get("/");
  6938. ASSERT_TRUE(!res);
  6939. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6940. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6941. // should be set
  6942. EXPECT_EQ(0, res.ssl_error());
  6943. // Verify OpenSSL error is captured for SSLLoadingCerts
  6944. // This error occurs when SSL_CTX_load_verify_locations() fails
  6945. // > openssl errstr 0x80000002
  6946. // error:80000002:system library::No such file or directory
  6947. // > openssl errstr 0xA000126
  6948. // error:0A000126:SSL routines::unexpected eof while reading
  6949. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  6950. res.ssl_openssl_error() == 0xA000126);
  6951. }
  6952. TEST(SSLClientTest, ServerCertificateVerification4) {
  6953. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  6954. ASSERT_TRUE(svr.is_valid());
  6955. svr.Get("/test", [&](const Request &, Response &res) {
  6956. res.set_content("test", "text/plain");
  6957. svr.stop();
  6958. ASSERT_TRUE(true);
  6959. });
  6960. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  6961. auto se = detail::scope_exit([&] {
  6962. t.join();
  6963. ASSERT_FALSE(svr.is_running());
  6964. });
  6965. svr.wait_until_ready();
  6966. SSLClient cli("127.0.0.1", PORT);
  6967. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  6968. cli.enable_server_certificate_verification(true);
  6969. cli.set_connection_timeout(30);
  6970. auto res = cli.Get("/test");
  6971. ASSERT_TRUE(res);
  6972. ASSERT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  6975. std::string cert;
  6976. read_file(CA_CERT_FILE, cert);
  6977. SSLClient cli("google.com");
  6978. cli.load_ca_cert_store(cert.data(), cert.size());
  6979. const auto res = cli.Get("/");
  6980. ASSERT_TRUE(res);
  6981. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6982. }
  6983. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  6984. // clang-format off
  6985. static constexpr char cert[] =
  6986. "GlobalSign Root CA\n"
  6987. "==================\n"
  6988. "-----BEGIN CERTIFICATE-----\n"
  6989. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  6990. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  6991. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  6992. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  6993. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  6994. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  6995. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  6996. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  6997. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  6998. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  6999. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7000. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7001. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7002. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7003. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7004. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7005. "-----END CERTIFICATE-----\n";
  7006. // clang-format on
  7007. SSLClient cli("google.com");
  7008. cli.load_ca_cert_store(cert, sizeof(cert));
  7009. const auto res = cli.Get("/");
  7010. ASSERT_TRUE(res);
  7011. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7012. }
  7013. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7014. SSLClient cli("www.youtube.com");
  7015. cli.set_ca_cert_path(CA_CERT_FILE);
  7016. cli.enable_server_certificate_verification(true);
  7017. cli.set_follow_location(true);
  7018. auto res = cli.Get("/");
  7019. ASSERT_TRUE(res);
  7020. ASSERT_EQ(StatusCode::OK_200, res->status);
  7021. }
  7022. TEST(SSLClientTest, Issue2004_Online) {
  7023. Client client("https://google.com");
  7024. client.set_follow_location(true);
  7025. auto res = client.Get("/");
  7026. ASSERT_TRUE(res);
  7027. ASSERT_EQ(StatusCode::OK_200, res->status);
  7028. auto body = res->body;
  7029. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7030. }
  7031. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7032. // Create SSLClient with invalid cert/key to make is_valid() return false
  7033. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7034. "nonexistent_key.pem");
  7035. // is_valid() should be false due to cert loading failure
  7036. ASSERT_FALSE(cli.is_valid());
  7037. auto res = cli.Get("/");
  7038. ASSERT_FALSE(res);
  7039. EXPECT_EQ(Error::SSLConnection, res.error());
  7040. }
  7041. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7042. // Test for Issue #2251: SSL error not properly reported when client cert
  7043. // and key paths are swapped or mismatched
  7044. // This simulates the scenario where user accidentally swaps the cert and key
  7045. // files
  7046. // Using client cert file as private key and vice versa (completely wrong)
  7047. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7048. // Should fail validation due to cert/key mismatch
  7049. ASSERT_FALSE(cli.is_valid());
  7050. // Attempt to make a request should fail with proper error
  7051. auto res = cli.Get("/");
  7052. ASSERT_FALSE(res);
  7053. EXPECT_EQ(Error::SSLConnection, res.error());
  7054. // SSL error should be recorded in the Result object (this is the key fix for
  7055. // Issue #2251)
  7056. auto openssl_error = res.ssl_openssl_error();
  7057. EXPECT_NE(0u, openssl_error);
  7058. }
  7059. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7060. // Another variant: using valid file paths but with mismatched cert/key pair
  7061. // This tests the case where files exist but contain incompatible key material
  7062. // Using client cert with wrong key (cert2 key)
  7063. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7064. // Should fail validation
  7065. ASSERT_FALSE(cli.is_valid());
  7066. auto res = cli.Get("/");
  7067. ASSERT_FALSE(res);
  7068. // Must report error properly, not appear as success
  7069. EXPECT_EQ(Error::SSLConnection, res.error());
  7070. // OpenSSL error should be captured in Result
  7071. EXPECT_NE(0u, res.ssl_openssl_error());
  7072. }
  7073. #if 0
  7074. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7075. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7076. ASSERT_TRUE(cli != nullptr);
  7077. cli->set_address_family(AF_INET6);
  7078. cli->set_interface("en0");
  7079. auto res = cli->Get("/get");
  7080. ASSERT_TRUE(res);
  7081. ASSERT_EQ(StatusCode::OK_200, res->status);
  7082. }
  7083. #endif
  7084. void ClientCertPresent(
  7085. const std::string &client_cert_file,
  7086. const std::string &client_private_key_file,
  7087. const std::string &client_encrypted_private_key_pass = std::string()) {
  7088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7089. CLIENT_CA_CERT_DIR);
  7090. ASSERT_TRUE(svr.is_valid());
  7091. svr.Get("/test", [&](const Request &req, Response &res) {
  7092. res.set_content("test", "text/plain");
  7093. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7094. ASSERT_TRUE(peer_cert != nullptr);
  7095. auto subject_name = X509_get_subject_name(peer_cert);
  7096. ASSERT_TRUE(subject_name != nullptr);
  7097. std::string common_name;
  7098. {
  7099. char name[BUFSIZ];
  7100. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7101. name, sizeof(name));
  7102. common_name.assign(name, static_cast<size_t>(name_len));
  7103. }
  7104. EXPECT_EQ("Common Name", common_name);
  7105. X509_free(peer_cert);
  7106. });
  7107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7108. auto se = detail::scope_exit([&] {
  7109. svr.stop();
  7110. t.join();
  7111. ASSERT_FALSE(svr.is_running());
  7112. });
  7113. svr.wait_until_ready();
  7114. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7115. client_encrypted_private_key_pass);
  7116. cli.enable_server_certificate_verification(false);
  7117. cli.set_connection_timeout(30);
  7118. auto res = cli.Get("/test");
  7119. ASSERT_TRUE(res);
  7120. ASSERT_EQ(StatusCode::OK_200, res->status);
  7121. }
  7122. TEST(SSLClientServerTest, ClientCertPresent) {
  7123. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7124. }
  7125. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7126. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7127. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7128. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7129. }
  7130. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7131. void MemoryClientCertPresent(
  7132. const std::string &client_cert_file,
  7133. const std::string &client_private_key_file,
  7134. const std::string &client_encrypted_private_key_pass = std::string()) {
  7135. auto f = fopen(SERVER_CERT_FILE, "r+");
  7136. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7137. fclose(f);
  7138. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7139. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7140. fclose(f);
  7141. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7142. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7143. auto client_ca_cert_store = X509_STORE_new();
  7144. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7145. X509_free(client_cert);
  7146. fclose(f);
  7147. f = fopen(client_cert_file.c_str(), "r+");
  7148. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7149. fclose(f);
  7150. f = fopen(client_private_key_file.c_str(), "r+");
  7151. auto client_private_key = PEM_read_PrivateKey(
  7152. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7153. fclose(f);
  7154. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7155. ASSERT_TRUE(svr.is_valid());
  7156. svr.Get("/test", [&](const Request &req, Response &res) {
  7157. res.set_content("test", "text/plain");
  7158. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7159. ASSERT_TRUE(peer_cert != nullptr);
  7160. auto subject_name = X509_get_subject_name(peer_cert);
  7161. ASSERT_TRUE(subject_name != nullptr);
  7162. std::string common_name;
  7163. {
  7164. char name[BUFSIZ];
  7165. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7166. name, sizeof(name));
  7167. common_name.assign(name, static_cast<size_t>(name_len));
  7168. }
  7169. EXPECT_EQ("Common Name", common_name);
  7170. X509_free(peer_cert);
  7171. });
  7172. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7173. auto se = detail::scope_exit([&] {
  7174. svr.stop();
  7175. t.join();
  7176. ASSERT_FALSE(svr.is_running());
  7177. });
  7178. svr.wait_until_ready();
  7179. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7180. client_encrypted_private_key_pass);
  7181. cli.enable_server_certificate_verification(false);
  7182. cli.set_connection_timeout(30);
  7183. auto res = cli.Get("/test");
  7184. ASSERT_TRUE(res);
  7185. ASSERT_EQ(StatusCode::OK_200, res->status);
  7186. X509_free(server_cert);
  7187. EVP_PKEY_free(server_private_key);
  7188. X509_free(client_cert);
  7189. EVP_PKEY_free(client_private_key);
  7190. }
  7191. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7192. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7193. }
  7194. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7195. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7196. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7197. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7198. }
  7199. #endif
  7200. TEST(SSLClientServerTest, ClientCertMissing) {
  7201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7202. CLIENT_CA_CERT_DIR);
  7203. ASSERT_TRUE(svr.is_valid());
  7204. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7205. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7206. auto se = detail::scope_exit([&] {
  7207. svr.stop();
  7208. t.join();
  7209. ASSERT_FALSE(svr.is_running());
  7210. });
  7211. svr.wait_until_ready();
  7212. SSLClient cli(HOST, PORT);
  7213. cli.set_connection_timeout(30);
  7214. auto res = cli.Get("/test");
  7215. ASSERT_TRUE(!res);
  7216. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7217. // For SSL server verification errors, ssl_error should be 0, only
  7218. // ssl_openssl_error should be set
  7219. EXPECT_EQ(0, res.ssl_error());
  7220. // Verify OpenSSL error is captured for SSLServerVerification
  7221. // Note: This test may have different error codes depending on the exact
  7222. // verification failure
  7223. EXPECT_NE(0UL, res.ssl_openssl_error());
  7224. }
  7225. TEST(SSLClientServerTest, TrustDirOptional) {
  7226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7227. ASSERT_TRUE(svr.is_valid());
  7228. svr.Get("/test", [&](const Request &, Response &res) {
  7229. res.set_content("test", "text/plain");
  7230. });
  7231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7232. auto se = detail::scope_exit([&] {
  7233. svr.stop();
  7234. t.join();
  7235. ASSERT_FALSE(svr.is_running());
  7236. });
  7237. svr.wait_until_ready();
  7238. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7239. cli.enable_server_certificate_verification(false);
  7240. cli.set_connection_timeout(30);
  7241. auto res = cli.Get("/test");
  7242. ASSERT_TRUE(res);
  7243. ASSERT_EQ(StatusCode::OK_200, res->status);
  7244. }
  7245. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7246. class NoListenSSLServer : public SSLServer {
  7247. public:
  7248. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7249. const char *client_ca_cert_file_path,
  7250. const char *client_ca_cert_dir_path = nullptr)
  7251. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7252. client_ca_cert_dir_path),
  7253. stop_(false) {}
  7254. std::atomic_bool stop_;
  7255. private:
  7256. bool process_and_close_socket(socket_t /*sock*/) override {
  7257. // Don't create SSL context
  7258. while (!stop_.load()) {
  7259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7260. }
  7261. return true;
  7262. }
  7263. };
  7264. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7265. CLIENT_CA_CERT_FILE);
  7266. ASSERT_TRUE(svr.is_valid());
  7267. svr.Get("/test", [&](const Request &, Response &res) {
  7268. res.set_content("test", "text/plain");
  7269. });
  7270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7271. auto se = detail::scope_exit([&] {
  7272. svr.stop_ = true;
  7273. svr.stop();
  7274. t.join();
  7275. ASSERT_FALSE(svr.is_running());
  7276. });
  7277. svr.wait_until_ready();
  7278. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7279. cli.enable_server_certificate_verification(false);
  7280. cli.set_connection_timeout(1);
  7281. auto res = cli.Get("/test");
  7282. ASSERT_TRUE(!res);
  7283. EXPECT_EQ(Error::SSLConnection, res.error());
  7284. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7285. }
  7286. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7287. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7288. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7289. SSL_CTX_set_options(&ssl_ctx,
  7290. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7291. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7292. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7293. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7294. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7295. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7296. "ECDHE-DSS-AES128-SHA256:"
  7297. "ECDHE-RSA-AES256-SHA256:"
  7298. "ECDHE-DSS-AES256-SHA256:";
  7299. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7300. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7301. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7302. SSL_FILETYPE_PEM) != 1) {
  7303. return false;
  7304. }
  7305. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7306. CLIENT_CA_CERT_DIR);
  7307. SSL_CTX_set_verify(
  7308. &ssl_ctx,
  7309. SSL_VERIFY_PEER |
  7310. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7311. nullptr);
  7312. return true;
  7313. };
  7314. SSLServer svr(setup_ssl_ctx_callback);
  7315. ASSERT_TRUE(svr.is_valid());
  7316. svr.Get("/test", [&](const Request &req, Response &res) {
  7317. res.set_content("test", "text/plain");
  7318. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7319. ASSERT_TRUE(peer_cert != nullptr);
  7320. auto subject_name = X509_get_subject_name(peer_cert);
  7321. ASSERT_TRUE(subject_name != nullptr);
  7322. std::string common_name;
  7323. {
  7324. char name[BUFSIZ];
  7325. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7326. name, sizeof(name));
  7327. common_name.assign(name, static_cast<size_t>(name_len));
  7328. }
  7329. EXPECT_EQ("Common Name", common_name);
  7330. X509_free(peer_cert);
  7331. });
  7332. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7333. auto se = detail::scope_exit([&] {
  7334. svr.stop();
  7335. t.join();
  7336. ASSERT_FALSE(svr.is_running());
  7337. });
  7338. svr.wait_until_ready();
  7339. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7340. cli.enable_server_certificate_verification(false);
  7341. cli.set_connection_timeout(30);
  7342. auto res = cli.Get("/test");
  7343. ASSERT_TRUE(res);
  7344. ASSERT_EQ(StatusCode::OK_200, res->status);
  7345. }
  7346. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7348. ASSERT_TRUE(svr.is_valid());
  7349. // Set up a handler to verify client certificate is present
  7350. bool client_cert_verified = false;
  7351. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7352. // Verify that client certificate was provided
  7353. client_cert_verified = true;
  7354. res.set_content("success", "text/plain");
  7355. });
  7356. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7357. auto se = detail::scope_exit([&] {
  7358. svr.stop();
  7359. t.join();
  7360. ASSERT_FALSE(svr.is_running());
  7361. });
  7362. svr.wait_until_ready();
  7363. // Client with certificate
  7364. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7365. cli.enable_server_certificate_verification(false);
  7366. cli.set_connection_timeout(30);
  7367. auto res = cli.Get("/test");
  7368. ASSERT_TRUE(res);
  7369. ASSERT_EQ(StatusCode::OK_200, res->status);
  7370. ASSERT_TRUE(client_cert_verified);
  7371. EXPECT_EQ("success", res->body);
  7372. }
  7373. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7374. // Test that when client CA cert file is provided,
  7375. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7376. // Create a server with client authentication
  7377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7378. ASSERT_TRUE(svr.is_valid());
  7379. // We can't directly access the SSL_CTX from SSLServer to verify,
  7380. // but we can test that the server properly requests client certificates
  7381. // and accepts valid ones from the specified CA
  7382. bool handler_called = false;
  7383. svr.Get("/test", [&](const Request &req, Response &res) {
  7384. handler_called = true;
  7385. // Verify that a client certificate was provided
  7386. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7387. ASSERT_TRUE(peer_cert != nullptr);
  7388. // Get the issuer name
  7389. auto issuer_name = X509_get_issuer_name(peer_cert);
  7390. ASSERT_TRUE(issuer_name != nullptr);
  7391. char issuer_buf[256];
  7392. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7393. // The client certificate should be issued by our test CA
  7394. std::string issuer_str(issuer_buf);
  7395. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7396. X509_free(peer_cert);
  7397. res.set_content("authenticated", "text/plain");
  7398. });
  7399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7400. auto se = detail::scope_exit([&] {
  7401. svr.stop();
  7402. t.join();
  7403. ASSERT_FALSE(svr.is_running());
  7404. });
  7405. svr.wait_until_ready();
  7406. // Connect with a client certificate issued by the CA
  7407. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7408. cli.enable_server_certificate_verification(false);
  7409. cli.set_connection_timeout(30);
  7410. auto res = cli.Get("/test");
  7411. ASSERT_TRUE(res);
  7412. ASSERT_EQ(StatusCode::OK_200, res->status);
  7413. ASSERT_TRUE(handler_called);
  7414. EXPECT_EQ("authenticated", res->body);
  7415. }
  7416. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7417. // Test 1: Valid CA file - no error should be recorded
  7418. {
  7419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7420. CLIENT_CA_CERT_FILE);
  7421. ASSERT_TRUE(svr.is_valid());
  7422. // With valid setup, last_ssl_error should be 0
  7423. EXPECT_EQ(0, svr.ssl_last_error());
  7424. }
  7425. // Test 2: Invalid CA file content
  7426. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7427. {
  7428. // Create a temporary file with completely invalid content
  7429. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7430. {
  7431. std::ofstream ofs(temp_invalid_ca);
  7432. ofs << "This is not a certificate file at all\n";
  7433. ofs << "Just plain text content\n";
  7434. }
  7435. // Create server with invalid CA file
  7436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7437. // Clean up temporary file
  7438. std::remove(temp_invalid_ca);
  7439. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7440. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7441. // Note: SSL_CTX_load_verify_locations typically fails first,
  7442. // but our error handling code path is still exercised
  7443. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7444. }
  7445. }
  7446. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7447. // Test SSL server using X509_STORE constructor with client CA certificates
  7448. // This test verifies that Phase 2 implementation correctly extracts CA names
  7449. // from an X509_STORE and sets them in the SSL context
  7450. // Load the CA certificate into memory
  7451. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7452. ASSERT_NE(nullptr, bio);
  7453. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7454. BIO_free(bio);
  7455. ASSERT_NE(nullptr, ca_cert);
  7456. // Create an X509_STORE and add the CA certificate
  7457. auto store = X509_STORE_new();
  7458. ASSERT_NE(nullptr, store);
  7459. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7460. // Load server certificate and private key
  7461. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7462. ASSERT_NE(nullptr, cert_bio);
  7463. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7464. BIO_free(cert_bio);
  7465. ASSERT_NE(nullptr, server_cert);
  7466. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7467. ASSERT_NE(nullptr, key_bio);
  7468. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7469. BIO_free(key_bio);
  7470. ASSERT_NE(nullptr, server_key);
  7471. // Create SSLServer with X509_STORE constructor
  7472. // Note: X509_STORE ownership is transferred to SSL_CTX
  7473. SSLServer svr(server_cert, server_key, store);
  7474. ASSERT_TRUE(svr.is_valid());
  7475. // No SSL error should be recorded for valid setup
  7476. EXPECT_EQ(0, svr.ssl_last_error());
  7477. // Set up server endpoints
  7478. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7479. res.set_content("ok", "text/plain");
  7480. });
  7481. // Start server in a thread
  7482. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7483. svr.wait_until_ready();
  7484. // Connect with client certificate (using constructor with paths)
  7485. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7486. cli.enable_server_certificate_verification(false);
  7487. auto res = cli.Get("/test-x509store");
  7488. ASSERT_TRUE(res);
  7489. EXPECT_EQ(200, res->status);
  7490. EXPECT_EQ("ok", res->body);
  7491. // Clean up
  7492. X509_free(server_cert);
  7493. EVP_PKEY_free(server_key);
  7494. X509_free(ca_cert);
  7495. svr.stop();
  7496. server_thread.join();
  7497. }
  7498. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7499. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7500. // prepare large data
  7501. std::random_device seed_gen;
  7502. std::mt19937 random(seed_gen());
  7503. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7504. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7505. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7506. // server
  7507. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7508. ASSERT_TRUE(svr.is_valid());
  7509. svr.Post("/binary", [&](const Request &req, Response &res) {
  7510. EXPECT_EQ(large_size_byte, req.body.size());
  7511. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7512. res.set_content(req.body, "application/octet-stream");
  7513. });
  7514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7515. auto se = detail::scope_exit([&] {
  7516. svr.stop();
  7517. listen_thread.join();
  7518. ASSERT_FALSE(svr.is_running());
  7519. });
  7520. svr.wait_until_ready();
  7521. // client POST
  7522. SSLClient cli("localhost", PORT);
  7523. cli.enable_server_certificate_verification(false);
  7524. cli.set_read_timeout(std::chrono::seconds(100));
  7525. cli.set_write_timeout(std::chrono::seconds(100));
  7526. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7527. large_size_byte, "application/octet-stream");
  7528. // compare
  7529. EXPECT_EQ(StatusCode::OK_200, res->status);
  7530. EXPECT_EQ(large_size_byte, res->body.size());
  7531. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7532. }
  7533. #endif
  7534. #ifdef _WIN32
  7535. TEST(CleanupTest, WSACleanup) {
  7536. int ret = WSACleanup();
  7537. ASSERT_EQ(0, ret);
  7538. }
  7539. #endif
  7540. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7541. TEST(NoSSLSupport, SimpleInterface) {
  7542. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7543. }
  7544. #endif
  7545. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7546. TEST(InvalidScheme, SimpleInterface) {
  7547. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7548. }
  7549. #endif
  7550. TEST(NoScheme, SimpleInterface) {
  7551. Client cli("yahoo.com:80");
  7552. ASSERT_TRUE(cli.is_valid());
  7553. }
  7554. TEST(SendAPI, SimpleInterface_Online) {
  7555. Client cli("http://yahoo.com");
  7556. Request req;
  7557. req.method = "GET";
  7558. req.path = "/";
  7559. auto res = cli.send(req);
  7560. ASSERT_TRUE(res);
  7561. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7562. }
  7563. TEST(SendAPI, WithParamsInRequest) {
  7564. Server svr;
  7565. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7566. EXPECT_TRUE(req.has_param("test"));
  7567. EXPECT_EQ("test_value", req.get_param_value("test"));
  7568. });
  7569. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7570. auto se = detail::scope_exit([&] {
  7571. svr.stop();
  7572. t.join();
  7573. ASSERT_FALSE(svr.is_running());
  7574. });
  7575. svr.wait_until_ready();
  7576. Client cli(HOST, PORT);
  7577. {
  7578. Request req;
  7579. req.method = "GET";
  7580. req.path = "/";
  7581. req.params.emplace("test", "test_value");
  7582. auto res = cli.send(req);
  7583. ASSERT_TRUE(res);
  7584. }
  7585. {
  7586. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7587. ASSERT_TRUE(res);
  7588. }
  7589. }
  7590. TEST(ClientImplMethods, GetSocketTest) {
  7591. httplib::Server svr;
  7592. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7593. res.status = StatusCode::OK_200;
  7594. });
  7595. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7596. auto se = detail::scope_exit([&] {
  7597. svr.stop();
  7598. thread.join();
  7599. ASSERT_FALSE(svr.is_running());
  7600. });
  7601. svr.wait_until_ready();
  7602. {
  7603. httplib::Client cli("http://127.0.0.1:3333");
  7604. cli.set_keep_alive(true);
  7605. // Use the behavior of cpp-httplib of opening the connection
  7606. // only when the first request happens. If that changes,
  7607. // this test would be obsolete.
  7608. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7609. // This also implicitly tests the server. But other tests would fail much
  7610. // earlier than this one to be considered.
  7611. auto res = cli.Get("/");
  7612. ASSERT_TRUE(res);
  7613. EXPECT_EQ(StatusCode::OK_200, res->status);
  7614. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7615. }
  7616. }
  7617. // Disabled due to out-of-memory problem on GitHub Actions
  7618. #ifdef _WIN64
  7619. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7620. // allocate content size larger than 2GB in memory
  7621. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7622. char *content = (char *)malloc(content_size);
  7623. ASSERT_TRUE(content);
  7624. Server svr;
  7625. svr.Get("/foo",
  7626. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7627. res.set_content(content, content_size, "application/octet-stream");
  7628. });
  7629. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7630. auto se = detail::scope_exit([&] {
  7631. svr.stop();
  7632. listen_thread.join();
  7633. if (content) free(content);
  7634. ASSERT_FALSE(svr.is_running());
  7635. });
  7636. svr.wait_until_ready();
  7637. Client cli(HOST, PORT);
  7638. auto res = cli.Get("/foo");
  7639. ASSERT_TRUE(res);
  7640. EXPECT_EQ(StatusCode::OK_200, res->status);
  7641. EXPECT_EQ(content_size, res->body.length());
  7642. }
  7643. #endif
  7644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7645. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7646. Client cli("http://yahoo.com");
  7647. auto res = cli.Get("/");
  7648. ASSERT_TRUE(res);
  7649. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7650. cli.set_follow_location(true);
  7651. res = cli.Get("/");
  7652. ASSERT_TRUE(res);
  7653. EXPECT_EQ(StatusCode::OK_200, res->status);
  7654. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7655. }
  7656. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7657. Client cli("https://yahoo.com");
  7658. auto res = cli.Get("/");
  7659. ASSERT_TRUE(res);
  7660. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7661. cli.set_follow_location(true);
  7662. res = cli.Get("/");
  7663. ASSERT_TRUE(res);
  7664. EXPECT_EQ(StatusCode::OK_200, res->status);
  7665. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7666. }
  7667. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7668. Client cli("https://yahoo.com");
  7669. auto res = cli.Get("/");
  7670. ASSERT_TRUE(res);
  7671. ASSERT_FALSE(!res);
  7672. ASSERT_TRUE(res);
  7673. ASSERT_FALSE(res == nullptr);
  7674. ASSERT_TRUE(res != nullptr);
  7675. EXPECT_EQ(Error::Success, res.error());
  7676. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7677. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7678. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7679. cli.set_follow_location(true);
  7680. res = cli.Get("/");
  7681. ASSERT_TRUE(res);
  7682. EXPECT_EQ(Error::Success, res.error());
  7683. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7684. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7685. EXPECT_EQ(StatusCode::OK_200, res->status);
  7686. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7687. }
  7688. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7689. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7690. Client cli("https://cdnjs.cloudflare.com");
  7691. auto res =
  7692. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7693. ASSERT_TRUE(res);
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ(287630U, res->body.size());
  7696. EXPECT_EQ("application/javascript; charset=utf-8",
  7697. res->get_header_value("Content-Type"));
  7698. }
  7699. #endif
  7700. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7701. #undef REDIR_HOST // Silence compiler warning
  7702. #define REDIR_HOST "https://httpbingo.org"
  7703. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7704. Client cli(REDIR_HOST);
  7705. cli.set_follow_location(true);
  7706. auto res =
  7707. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7708. ASSERT_TRUE(res);
  7709. EXPECT_EQ(StatusCode::OK_200, res->status);
  7710. }
  7711. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7712. Client cli(REDIR_HOST);
  7713. cli.set_follow_location(true);
  7714. Params params;
  7715. params.emplace("url", "http://example.com");
  7716. params.emplace("status_code", "302");
  7717. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7718. ASSERT_TRUE(res);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7722. Client cli(REDIR_HOST);
  7723. cli.set_follow_location(true);
  7724. Params params;
  7725. params.emplace("url", "http://example.com");
  7726. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7727. ASSERT_TRUE(res);
  7728. EXPECT_EQ(StatusCode::OK_200, res->status);
  7729. }
  7730. TEST(HttpToHttpsRedirectTest, CertFile) {
  7731. Server svr;
  7732. ASSERT_TRUE(svr.is_valid());
  7733. svr.Get("/index", [&](const Request &, Response &res) {
  7734. res.set_redirect("https://127.0.0.1:1235/index");
  7735. svr.stop();
  7736. });
  7737. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7738. ASSERT_TRUE(ssl_svr.is_valid());
  7739. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7740. res.set_content("test", "text/plain");
  7741. ssl_svr.stop();
  7742. });
  7743. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7744. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7745. auto se = detail::scope_exit([&] {
  7746. t2.join();
  7747. t.join();
  7748. ASSERT_FALSE(svr.is_running());
  7749. });
  7750. svr.wait_until_ready();
  7751. ssl_svr.wait_until_ready();
  7752. Client cli("127.0.0.1", PORT);
  7753. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7754. cli.enable_server_certificate_verification(true);
  7755. cli.set_follow_location(true);
  7756. cli.set_connection_timeout(30);
  7757. auto res = cli.Get("/index");
  7758. ASSERT_TRUE(res);
  7759. ASSERT_EQ(StatusCode::OK_200, res->status);
  7760. }
  7761. TEST(SSLClientRedirectTest, CertFile) {
  7762. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7763. ASSERT_TRUE(ssl_svr1.is_valid());
  7764. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7765. res.set_redirect("https://127.0.0.1:1235/index");
  7766. ssl_svr1.stop();
  7767. });
  7768. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7769. ASSERT_TRUE(ssl_svr2.is_valid());
  7770. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7771. res.set_content("test", "text/plain");
  7772. ssl_svr2.stop();
  7773. });
  7774. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7775. thread t2 =
  7776. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7777. auto se = detail::scope_exit([&] {
  7778. t2.join();
  7779. t.join();
  7780. ASSERT_FALSE(ssl_svr1.is_running());
  7781. });
  7782. ssl_svr1.wait_until_ready();
  7783. ssl_svr2.wait_until_ready();
  7784. SSLClient cli("127.0.0.1", PORT);
  7785. std::string cert;
  7786. read_file(SERVER_CERT2_FILE, cert);
  7787. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7788. cli.enable_server_certificate_verification(true);
  7789. cli.set_follow_location(true);
  7790. cli.set_connection_timeout(30);
  7791. auto res = cli.Get("/index");
  7792. ASSERT_TRUE(res);
  7793. ASSERT_EQ(StatusCode::OK_200, res->status);
  7794. }
  7795. TEST(MultipartFormDataTest, LargeData) {
  7796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7797. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7798. const ContentReader &content_reader) {
  7799. if (req.is_multipart_form_data()) {
  7800. std::vector<FormData> items;
  7801. content_reader(
  7802. [&](const FormData &file) {
  7803. items.push_back(file);
  7804. return true;
  7805. },
  7806. [&](const char *data, size_t data_length) {
  7807. items.back().content.append(data, data_length);
  7808. return true;
  7809. });
  7810. EXPECT_TRUE(std::string(items[0].name) == "document");
  7811. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7812. EXPECT_TRUE(items[0].filename == "2MB_data");
  7813. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7814. EXPECT_TRUE(items[1].name == "hello");
  7815. EXPECT_TRUE(items[1].content == "world");
  7816. EXPECT_TRUE(items[1].filename == "");
  7817. EXPECT_TRUE(items[1].content_type == "");
  7818. } else {
  7819. std::string body;
  7820. content_reader([&](const char *data, size_t data_length) {
  7821. body.append(data, data_length);
  7822. return true;
  7823. });
  7824. }
  7825. });
  7826. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7827. auto se = detail::scope_exit([&] {
  7828. svr.stop();
  7829. t.join();
  7830. ASSERT_FALSE(svr.is_running());
  7831. });
  7832. svr.wait_until_ready();
  7833. {
  7834. std::string data(1024 * 1024 * 2, '.');
  7835. std::stringstream buffer;
  7836. buffer << data;
  7837. Client cli("https://localhost:8080");
  7838. cli.enable_server_certificate_verification(false);
  7839. UploadFormDataItems items{
  7840. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7841. {"hello", "world", "", ""},
  7842. };
  7843. auto res = cli.Post("/post", items);
  7844. ASSERT_TRUE(res);
  7845. ASSERT_EQ(StatusCode::OK_200, res->status);
  7846. }
  7847. }
  7848. TEST(MultipartFormDataTest, DataProviderItems) {
  7849. std::random_device seed_gen;
  7850. std::mt19937 random(seed_gen());
  7851. std::string rand1;
  7852. rand1.resize(1000);
  7853. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7854. std::string rand2;
  7855. rand2.resize(3000);
  7856. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7858. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7859. const ContentReader &content_reader) {
  7860. ASSERT_FALSE(req.is_multipart_form_data());
  7861. std::string body;
  7862. content_reader([&](const char *data, size_t data_length) {
  7863. body.append(data, data_length);
  7864. return true;
  7865. });
  7866. EXPECT_EQ(body, "");
  7867. });
  7868. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7869. const ContentReader &content_reader) {
  7870. ASSERT_TRUE(req.is_multipart_form_data());
  7871. std::vector<FormData> items;
  7872. content_reader(
  7873. [&](const FormData &file) {
  7874. items.push_back(file);
  7875. return true;
  7876. },
  7877. [&](const char *data, size_t data_length) {
  7878. items.back().content.append(data, data_length);
  7879. return true;
  7880. });
  7881. ASSERT_TRUE(items.size() == 2);
  7882. EXPECT_EQ(std::string(items[0].name), "name1");
  7883. EXPECT_EQ(items[0].content, "Testing123");
  7884. EXPECT_EQ(items[0].filename, "filename1");
  7885. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7886. EXPECT_EQ(items[1].name, "name2");
  7887. EXPECT_EQ(items[1].content, "Testing456");
  7888. EXPECT_EQ(items[1].filename, "");
  7889. EXPECT_EQ(items[1].content_type, "");
  7890. });
  7891. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7892. const ContentReader &content_reader) {
  7893. ASSERT_TRUE(req.is_multipart_form_data());
  7894. std::vector<FormData> items;
  7895. content_reader(
  7896. [&](const FormData &file) {
  7897. items.push_back(file);
  7898. return true;
  7899. },
  7900. [&](const char *data, size_t data_length) {
  7901. items.back().content.append(data, data_length);
  7902. return true;
  7903. });
  7904. ASSERT_TRUE(items.size() == 2);
  7905. EXPECT_EQ(items[0].name, "name3");
  7906. EXPECT_EQ(items[0].content, rand1);
  7907. EXPECT_EQ(items[0].filename, "filename3");
  7908. EXPECT_EQ(items[0].content_type, "");
  7909. EXPECT_EQ(items[1].name, "name4");
  7910. EXPECT_EQ(items[1].content, rand2);
  7911. EXPECT_EQ(items[1].filename, "filename4");
  7912. EXPECT_EQ(items[1].content_type, "");
  7913. });
  7914. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7915. const ContentReader &content_reader) {
  7916. ASSERT_TRUE(req.is_multipart_form_data());
  7917. std::vector<FormData> items;
  7918. content_reader(
  7919. [&](const FormData &file) {
  7920. items.push_back(file);
  7921. return true;
  7922. },
  7923. [&](const char *data, size_t data_length) {
  7924. items.back().content.append(data, data_length);
  7925. return true;
  7926. });
  7927. ASSERT_TRUE(items.size() == 4);
  7928. EXPECT_EQ(std::string(items[0].name), "name1");
  7929. EXPECT_EQ(items[0].content, "Testing123");
  7930. EXPECT_EQ(items[0].filename, "filename1");
  7931. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7932. EXPECT_EQ(items[1].name, "name2");
  7933. EXPECT_EQ(items[1].content, "Testing456");
  7934. EXPECT_EQ(items[1].filename, "");
  7935. EXPECT_EQ(items[1].content_type, "");
  7936. EXPECT_EQ(items[2].name, "name3");
  7937. EXPECT_EQ(items[2].content, rand1);
  7938. EXPECT_EQ(items[2].filename, "filename3");
  7939. EXPECT_EQ(items[2].content_type, "");
  7940. EXPECT_EQ(items[3].name, "name4");
  7941. EXPECT_EQ(items[3].content, rand2);
  7942. EXPECT_EQ(items[3].filename, "filename4");
  7943. EXPECT_EQ(items[3].content_type, "");
  7944. });
  7945. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7946. auto se = detail::scope_exit([&] {
  7947. svr.stop();
  7948. t.join();
  7949. ASSERT_FALSE(svr.is_running());
  7950. });
  7951. svr.wait_until_ready();
  7952. {
  7953. Client cli("https://localhost:8080");
  7954. cli.enable_server_certificate_verification(false);
  7955. UploadFormDataItems items{
  7956. {"name1", "Testing123", "filename1", "application/octet-stream"},
  7957. {"name2", "Testing456", "", ""}, // not a file
  7958. };
  7959. {
  7960. auto res = cli.Post("/post-none", {}, {}, {});
  7961. ASSERT_TRUE(res);
  7962. ASSERT_EQ(StatusCode::OK_200, res->status);
  7963. }
  7964. FormDataProviderItems providers;
  7965. {
  7966. auto res =
  7967. cli.Post("/post-items", {}, items, providers); // empty providers
  7968. ASSERT_TRUE(res);
  7969. ASSERT_EQ(StatusCode::OK_200, res->status);
  7970. }
  7971. providers.push_back({"name3",
  7972. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7973. // test the offset is given correctly at each step
  7974. if (!offset)
  7975. sink.os.write(rand1.data(), 30);
  7976. else if (offset == 30)
  7977. sink.os.write(rand1.data() + 30, 300);
  7978. else if (offset == 330)
  7979. sink.os.write(rand1.data() + 330, 670);
  7980. else if (offset == rand1.size())
  7981. sink.done();
  7982. return true;
  7983. },
  7984. "filename3",
  7985. {}});
  7986. providers.push_back({"name4",
  7987. [&](size_t offset, httplib::DataSink &sink) -> bool {
  7988. // test the offset is given correctly at each step
  7989. if (!offset)
  7990. sink.os.write(rand2.data(), 2000);
  7991. else if (offset == 2000)
  7992. sink.os.write(rand2.data() + 2000, 1);
  7993. else if (offset == 2001)
  7994. sink.os.write(rand2.data() + 2001, 999);
  7995. else if (offset == rand2.size())
  7996. sink.done();
  7997. return true;
  7998. },
  7999. "filename4",
  8000. {}});
  8001. {
  8002. auto res = cli.Post("/post-providers", {}, {}, providers);
  8003. ASSERT_TRUE(res);
  8004. ASSERT_EQ(StatusCode::OK_200, res->status);
  8005. }
  8006. {
  8007. auto res = cli.Post("/post-both", {}, items, providers);
  8008. ASSERT_TRUE(res);
  8009. ASSERT_EQ(StatusCode::OK_200, res->status);
  8010. }
  8011. }
  8012. }
  8013. TEST(MultipartFormDataTest, BadHeader) {
  8014. Server svr;
  8015. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8016. res.set_content("ok", "text/plain");
  8017. });
  8018. thread t = thread([&] { svr.listen(HOST, PORT); });
  8019. auto se = detail::scope_exit([&] {
  8020. svr.stop();
  8021. t.join();
  8022. ASSERT_FALSE(svr.is_running());
  8023. });
  8024. svr.wait_until_ready();
  8025. const std::string body =
  8026. "This is the preamble. It is to be ignored, though it\r\n"
  8027. "is a handy place for composition agents to include an\r\n"
  8028. "explanatory note to non-MIME conformant readers.\r\n"
  8029. "\r\n"
  8030. "\r\n"
  8031. "--simple boundary\r\n"
  8032. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8033. ": BAD...\r\n"
  8034. "\r\n"
  8035. "value1\r\n"
  8036. "--simple boundary\r\n"
  8037. "Content-Disposition: form-data; name=\"field2\"; "
  8038. "filename=\"example.txt\"\r\n"
  8039. "\r\n"
  8040. "value2\r\n"
  8041. "--simple boundary--\r\n"
  8042. "This is the epilogue. It is also to be ignored.\r\n";
  8043. std::string content_type =
  8044. R"(multipart/form-data; boundary="simple boundary")";
  8045. Client cli(HOST, PORT);
  8046. auto res = cli.Post("/post", body, content_type.c_str());
  8047. ASSERT_TRUE(res);
  8048. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8049. }
  8050. TEST(MultipartFormDataTest, WithPreamble) {
  8051. Server svr;
  8052. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8053. res.set_content("ok", "text/plain");
  8054. });
  8055. thread t = thread([&] { svr.listen(HOST, PORT); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. t.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. const std::string body =
  8063. "This is the preamble. It is to be ignored, though it\r\n"
  8064. "is a handy place for composition agents to include an\r\n"
  8065. "explanatory note to non-MIME conformant readers.\r\n"
  8066. "\r\n"
  8067. "\r\n"
  8068. "--simple boundary\r\n"
  8069. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8070. "\r\n"
  8071. "value1\r\n"
  8072. "--simple boundary\r\n"
  8073. "Content-Disposition: form-data; name=\"field2\"; "
  8074. "filename=\"example.txt\"\r\n"
  8075. "\r\n"
  8076. "value2\r\n"
  8077. "--simple boundary--\r\n"
  8078. "This is the epilogue. It is also to be ignored.\r\n";
  8079. std::string content_type =
  8080. R"(multipart/form-data; boundary="simple boundary")";
  8081. Client cli(HOST, PORT);
  8082. auto res = cli.Post("/post", body, content_type.c_str());
  8083. ASSERT_TRUE(res);
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. }
  8086. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8088. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8089. const ContentReader &content_reader) {
  8090. if (req.is_multipart_form_data()) {
  8091. std::vector<FormData> items;
  8092. content_reader(
  8093. [&](const FormData &file) {
  8094. items.push_back(file);
  8095. return true;
  8096. },
  8097. [&](const char *data, size_t data_length) {
  8098. items.back().content.append(data, data_length);
  8099. return true;
  8100. });
  8101. EXPECT_TRUE(std::string(items[0].name) == "document");
  8102. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8103. EXPECT_TRUE(items[0].filename == "2MB_data");
  8104. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8105. EXPECT_TRUE(items[1].name == "hello");
  8106. EXPECT_TRUE(items[1].content == "world");
  8107. EXPECT_TRUE(items[1].filename == "");
  8108. EXPECT_TRUE(items[1].content_type == "");
  8109. } else {
  8110. std::string body;
  8111. content_reader([&](const char *data, size_t data_length) {
  8112. body.append(data, data_length);
  8113. return true;
  8114. });
  8115. }
  8116. });
  8117. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8118. auto se = detail::scope_exit([&] {
  8119. svr.stop();
  8120. t.join();
  8121. ASSERT_FALSE(svr.is_running());
  8122. });
  8123. svr.wait_until_ready();
  8124. {
  8125. std::string data(1024 * 1024 * 2, '.');
  8126. std::stringstream buffer;
  8127. buffer << data;
  8128. Client cli("https://localhost:8080");
  8129. cli.enable_server_certificate_verification(false);
  8130. UploadFormDataItems items{
  8131. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8132. {"hello", "world", "", ""},
  8133. };
  8134. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::OK_200, res->status);
  8137. }
  8138. }
  8139. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8140. std::string data(1024 * 1024 * 2, '&');
  8141. std::stringstream buffer;
  8142. buffer << data;
  8143. Client cli("https://localhost:8080");
  8144. UploadFormDataItems items{
  8145. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8146. {"hello", "world", "", ""},
  8147. };
  8148. for (const char &c : " \t\r\n") {
  8149. auto res =
  8150. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8151. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8152. ASSERT_FALSE(res);
  8153. }
  8154. }
  8155. TEST(MultipartFormDataTest, PutFormData) {
  8156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8157. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8158. const ContentReader &content_reader) {
  8159. if (req.is_multipart_form_data()) {
  8160. std::vector<FormData> items;
  8161. content_reader(
  8162. [&](const FormData &file) {
  8163. items.push_back(file);
  8164. return true;
  8165. },
  8166. [&](const char *data, size_t data_length) {
  8167. items.back().content.append(data, data_length);
  8168. return true;
  8169. });
  8170. EXPECT_TRUE(std::string(items[0].name) == "document");
  8171. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8172. EXPECT_TRUE(items[0].filename == "2MB_data");
  8173. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8174. EXPECT_TRUE(items[1].name == "hello");
  8175. EXPECT_TRUE(items[1].content == "world");
  8176. EXPECT_TRUE(items[1].filename == "");
  8177. EXPECT_TRUE(items[1].content_type == "");
  8178. } else {
  8179. std::string body;
  8180. content_reader([&](const char *data, size_t data_length) {
  8181. body.append(data, data_length);
  8182. return true;
  8183. });
  8184. }
  8185. });
  8186. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8187. auto se = detail::scope_exit([&] {
  8188. svr.stop();
  8189. t.join();
  8190. ASSERT_FALSE(svr.is_running());
  8191. });
  8192. svr.wait_until_ready();
  8193. {
  8194. std::string data(1024 * 1024 * 2, '&');
  8195. std::stringstream buffer;
  8196. buffer << data;
  8197. Client cli("https://localhost:8080");
  8198. cli.enable_server_certificate_verification(false);
  8199. UploadFormDataItems items{
  8200. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8201. {"hello", "world", "", ""},
  8202. };
  8203. auto res = cli.Put("/put", items);
  8204. ASSERT_TRUE(res);
  8205. ASSERT_EQ(StatusCode::OK_200, res->status);
  8206. }
  8207. }
  8208. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8209. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8210. svr.Put("/put_customboundary",
  8211. [&](const Request &req, const Response & /*res*/,
  8212. const ContentReader &content_reader) {
  8213. if (req.is_multipart_form_data()) {
  8214. std::vector<FormData> items;
  8215. content_reader(
  8216. [&](const FormData &file) {
  8217. items.push_back(file);
  8218. return true;
  8219. },
  8220. [&](const char *data, size_t data_length) {
  8221. items.back().content.append(data, data_length);
  8222. return true;
  8223. });
  8224. EXPECT_TRUE(std::string(items[0].name) == "document");
  8225. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8226. EXPECT_TRUE(items[0].filename == "2MB_data");
  8227. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8228. EXPECT_TRUE(items[1].name == "hello");
  8229. EXPECT_TRUE(items[1].content == "world");
  8230. EXPECT_TRUE(items[1].filename == "");
  8231. EXPECT_TRUE(items[1].content_type == "");
  8232. } else {
  8233. std::string body;
  8234. content_reader([&](const char *data, size_t data_length) {
  8235. body.append(data, data_length);
  8236. return true;
  8237. });
  8238. }
  8239. });
  8240. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8241. auto se = detail::scope_exit([&] {
  8242. svr.stop();
  8243. t.join();
  8244. ASSERT_FALSE(svr.is_running());
  8245. });
  8246. svr.wait_until_ready();
  8247. {
  8248. std::string data(1024 * 1024 * 2, '&');
  8249. std::stringstream buffer;
  8250. buffer << data;
  8251. Client cli("https://localhost:8080");
  8252. cli.enable_server_certificate_verification(false);
  8253. UploadFormDataItems items{
  8254. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8255. {"hello", "world", "", ""},
  8256. };
  8257. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8258. ASSERT_TRUE(res);
  8259. ASSERT_EQ(StatusCode::OK_200, res->status);
  8260. }
  8261. }
  8262. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8263. std::string data(1024 * 1024 * 2, '&');
  8264. std::stringstream buffer;
  8265. buffer << data;
  8266. Client cli("https://localhost:8080");
  8267. cli.enable_server_certificate_verification(false);
  8268. UploadFormDataItems items{
  8269. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8270. {"hello", "world", "", ""},
  8271. };
  8272. for (const char &c : " \t\r\n") {
  8273. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8274. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8275. ASSERT_FALSE(res);
  8276. }
  8277. }
  8278. TEST(MultipartFormDataTest, AlternateFilename) {
  8279. auto handled = false;
  8280. Server svr;
  8281. svr.Post("/test", [&](const Request &req, Response &res) {
  8282. ASSERT_EQ(2u, req.form.files.size());
  8283. ASSERT_EQ(1u, req.form.fields.size());
  8284. // Test files
  8285. const auto &file1 = req.form.get_file("file1");
  8286. ASSERT_EQ("file1", file1.name);
  8287. ASSERT_EQ("A.txt", file1.filename);
  8288. ASSERT_EQ("text/plain", file1.content_type);
  8289. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8290. const auto &file2 = req.form.get_file("file2");
  8291. ASSERT_EQ("file2", file2.name);
  8292. ASSERT_EQ("a.html", file2.filename);
  8293. ASSERT_EQ("text/html", file2.content_type);
  8294. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8295. file2.content);
  8296. // Test text field
  8297. const auto &text = req.form.get_field("text");
  8298. ASSERT_EQ("text default", text);
  8299. res.set_content("ok", "text/plain");
  8300. handled = true;
  8301. });
  8302. thread t = thread([&] { svr.listen(HOST, PORT); });
  8303. auto se = detail::scope_exit([&] {
  8304. svr.stop();
  8305. t.join();
  8306. ASSERT_FALSE(svr.is_running());
  8307. ASSERT_TRUE(handled);
  8308. });
  8309. svr.wait_until_ready();
  8310. auto req = "POST /test HTTP/1.1\r\n"
  8311. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8312. "Content-Length: 399\r\n"
  8313. "\r\n"
  8314. "----------\r\n"
  8315. "Content-Disposition: form-data; name=\"text\"\r\n"
  8316. "\r\n"
  8317. "text default\r\n"
  8318. "----------\r\n"
  8319. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8320. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8321. "Content-Type: text/plain\r\n"
  8322. "\r\n"
  8323. "Content of a.txt.\r\n"
  8324. "\r\n"
  8325. "----------\r\n"
  8326. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8327. "\"a.html\"\r\n"
  8328. "Content-Type: text/html\r\n"
  8329. "\r\n"
  8330. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8331. "\r\n"
  8332. "------------\r\n";
  8333. ASSERT_TRUE(send_request(1, req));
  8334. }
  8335. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8336. auto handled = false;
  8337. Server svr;
  8338. svr.Post("/test", [&](const Request &req, Response &) {
  8339. ASSERT_EQ(2u, req.form.fields.size());
  8340. const auto &text1 = req.form.get_field("text1");
  8341. ASSERT_EQ("text1", text1);
  8342. const auto &text2 = req.form.get_field("text2");
  8343. ASSERT_EQ("text2", text2);
  8344. handled = true;
  8345. });
  8346. thread t = thread([&] { svr.listen(HOST, PORT); });
  8347. auto se = detail::scope_exit([&] {
  8348. svr.stop();
  8349. t.join();
  8350. ASSERT_FALSE(svr.is_running());
  8351. ASSERT_TRUE(handled);
  8352. });
  8353. svr.wait_until_ready();
  8354. auto req = "POST /test HTTP/1.1\r\n"
  8355. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8356. "Content-Length: 146\r\n"
  8357. "\r\n----------\r\n"
  8358. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8359. "\r\n"
  8360. "text1"
  8361. "\r\n----------\r\n"
  8362. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8363. "\r\n"
  8364. "text2"
  8365. "\r\n------------";
  8366. std::string response;
  8367. ASSERT_TRUE(send_request(1, req, &response));
  8368. ASSERT_EQ("200", response.substr(9, 3));
  8369. }
  8370. TEST(MultipartFormDataTest, ContentLength) {
  8371. auto handled = false;
  8372. Server svr;
  8373. svr.Post("/test", [&](const Request &req, Response &) {
  8374. ASSERT_EQ(2u, req.form.fields.size());
  8375. const auto &text1 = req.form.get_field("text1");
  8376. ASSERT_EQ("text1", text1);
  8377. const auto &text2 = req.form.get_field("text2");
  8378. ASSERT_EQ("text2", text2);
  8379. handled = true;
  8380. });
  8381. thread t = thread([&] { svr.listen(HOST, PORT); });
  8382. auto se = detail::scope_exit([&] {
  8383. svr.stop();
  8384. t.join();
  8385. ASSERT_FALSE(svr.is_running());
  8386. ASSERT_TRUE(handled);
  8387. });
  8388. svr.wait_until_ready();
  8389. auto req = "POST /test HTTP/1.1\r\n"
  8390. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8391. "Content-Length: 167\r\n"
  8392. "\r\n----------\r\n"
  8393. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8394. "Content-Length: 5\r\n"
  8395. "\r\n"
  8396. "text1"
  8397. "\r\n----------\r\n"
  8398. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8399. "\r\n"
  8400. "text2"
  8401. "\r\n------------\r\n";
  8402. std::string response;
  8403. ASSERT_TRUE(send_request(1, req, &response));
  8404. ASSERT_EQ("200", response.substr(9, 3));
  8405. }
  8406. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8407. auto handled = false;
  8408. Server svr;
  8409. svr.Post("/test", [&](const Request &req, Response &) {
  8410. ASSERT_EQ(2u, req.form.fields.size());
  8411. const auto &text1 = req.form.get_field("text1");
  8412. ASSERT_EQ("text1", text1);
  8413. // TODO: Add header access for text fields if needed
  8414. const auto &text2 = req.form.get_field("text2");
  8415. ASSERT_EQ("text2", text2);
  8416. // TODO: Header access for text fields needs to be implemented
  8417. // auto &headers = it->second.headers;
  8418. // ASSERT_EQ(3U, headers.size());
  8419. // auto custom_header = headers.find("x-whatever");
  8420. // ASSERT_TRUE(custom_header != headers.end());
  8421. // ASSERT_NE("customvalue", custom_header->second);
  8422. // ASSERT_EQ("CustomValue", custom_header->second);
  8423. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8424. handled = true;
  8425. });
  8426. thread t = thread([&] { svr.listen(HOST, PORT); });
  8427. auto se = detail::scope_exit([&] {
  8428. svr.stop();
  8429. t.join();
  8430. ASSERT_FALSE(svr.is_running());
  8431. ASSERT_TRUE(handled);
  8432. });
  8433. svr.wait_until_ready();
  8434. auto req = "POST /test HTTP/1.1\r\n"
  8435. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8436. "Content-Length: 232\r\n"
  8437. "\r\n----------\r\n"
  8438. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8439. "Content-Length: 5\r\n"
  8440. "X-Test: 1\r\n"
  8441. "\r\n"
  8442. "text1"
  8443. "\r\n----------\r\n"
  8444. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8445. "Content-Type: text/plain\r\n"
  8446. "X-Whatever: CustomValue\r\n"
  8447. "\r\n"
  8448. "text2"
  8449. "\r\n------------\r\n"
  8450. "That should be disregarded. Not even read";
  8451. std::string response;
  8452. ASSERT_TRUE(send_request(1, req, &response));
  8453. ASSERT_EQ("200", response.substr(9, 3));
  8454. }
  8455. #endif
  8456. TEST(MultipartFormDataTest, LargeHeader) {
  8457. auto handled = false;
  8458. Server svr;
  8459. svr.Post("/test", [&](const Request &req, Response &) {
  8460. ASSERT_EQ(1u, req.form.fields.size());
  8461. const auto &text = req.form.get_field("name1");
  8462. ASSERT_EQ("text1", text);
  8463. handled = true;
  8464. });
  8465. thread t = thread([&] { svr.listen(HOST, PORT); });
  8466. auto se = detail::scope_exit([&] {
  8467. svr.stop();
  8468. t.join();
  8469. ASSERT_FALSE(svr.is_running());
  8470. ASSERT_TRUE(handled);
  8471. });
  8472. svr.wait_until_ready();
  8473. auto boundary = std::string("cpp-httplib-multipart-data");
  8474. std::string content = "--" + boundary +
  8475. "\r\n"
  8476. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8477. "\r\n"
  8478. "text1\r\n"
  8479. "--" +
  8480. boundary + "--\r\n";
  8481. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8482. "Content-Type: multipart/form-data;boundary=" +
  8483. boundary +
  8484. "\r\n"
  8485. "Content-Length: " +
  8486. std::to_string(content.size()) +
  8487. "\r\n"
  8488. "Dummy-Header: ";
  8489. std::string header_suffix = "\r\n"
  8490. "\r\n";
  8491. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8492. size_t header_dummy_size =
  8493. read_buff_size -
  8494. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8495. auto header_dummy = std::string(header_dummy_size, '@');
  8496. auto req = header_prefix + header_dummy + header_suffix + content;
  8497. std::string response;
  8498. ASSERT_TRUE(send_request(1, req, &response));
  8499. ASSERT_EQ("200", response.substr(9, 3));
  8500. }
  8501. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8502. static constexpr unsigned int number_of_tasks{1000000};
  8503. std::atomic_uint count{0};
  8504. std::unique_ptr<TaskQueue> task_queue{
  8505. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8506. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8507. auto queued = task_queue->enqueue(
  8508. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8509. EXPECT_TRUE(queued);
  8510. }
  8511. EXPECT_NO_THROW(task_queue->shutdown());
  8512. EXPECT_EQ(number_of_tasks, count.load());
  8513. }
  8514. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8515. static constexpr unsigned int number_of_tasks{1000000};
  8516. static constexpr unsigned int qlimit{2};
  8517. unsigned int queued_count{0};
  8518. std::atomic_uint count{0};
  8519. std::unique_ptr<TaskQueue> task_queue{
  8520. new ThreadPool{/*num_threads=*/1, qlimit}};
  8521. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8522. if (task_queue->enqueue(
  8523. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8524. queued_count++;
  8525. }
  8526. }
  8527. EXPECT_NO_THROW(task_queue->shutdown());
  8528. EXPECT_EQ(queued_count, count.load());
  8529. EXPECT_TRUE(queued_count <= number_of_tasks);
  8530. EXPECT_TRUE(queued_count >= qlimit);
  8531. }
  8532. TEST(TaskQueueTest, MaxQueuedRequests) {
  8533. static constexpr unsigned int qlimit{3};
  8534. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8535. std::condition_variable sem_cv;
  8536. std::mutex sem_mtx;
  8537. int credits = 0;
  8538. bool queued;
  8539. /* Fill up the queue with tasks that will block until we give them credits to
  8540. * complete. */
  8541. for (unsigned int n = 0; n <= qlimit;) {
  8542. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8543. std::unique_lock<std::mutex> lock(sem_mtx);
  8544. while (credits <= 0) {
  8545. sem_cv.wait(lock);
  8546. }
  8547. /* Consume the credit and signal the test code if they are all gone. */
  8548. if (--credits == 0) { sem_cv.notify_one(); }
  8549. });
  8550. if (n < qlimit) {
  8551. /* The first qlimit enqueues must succeed. */
  8552. EXPECT_TRUE(queued);
  8553. } else {
  8554. /* The last one will succeed only when the worker thread
  8555. * starts and dequeues the first blocking task. Although
  8556. * not necessary for the correctness of this test, we sleep for
  8557. * a short while to avoid busy waiting. */
  8558. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8559. }
  8560. if (queued) { n++; }
  8561. }
  8562. /* Further enqueues must fail since the queue is full. */
  8563. for (auto i = 0; i < 4; i++) {
  8564. queued = task_queue->enqueue([] {});
  8565. EXPECT_FALSE(queued);
  8566. }
  8567. /* Give the credits to allow the previous tasks to complete. */
  8568. {
  8569. std::unique_lock<std::mutex> lock(sem_mtx);
  8570. credits += qlimit + 1;
  8571. }
  8572. sem_cv.notify_all();
  8573. /* Wait for all the credits to be consumed. */
  8574. {
  8575. std::unique_lock<std::mutex> lock(sem_mtx);
  8576. while (credits > 0) {
  8577. sem_cv.wait(lock);
  8578. }
  8579. }
  8580. /* Check that we are able again to enqueue at least qlimit tasks. */
  8581. for (unsigned int i = 0; i < qlimit; i++) {
  8582. queued = task_queue->enqueue([] {});
  8583. EXPECT_TRUE(queued);
  8584. }
  8585. EXPECT_NO_THROW(task_queue->shutdown());
  8586. }
  8587. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8588. Server svr;
  8589. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8590. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8591. });
  8592. svr.Get("/hello", [](const Request &req, Response &res) {
  8593. res.set_content(req.get_param_value("key"), "text/plain");
  8594. });
  8595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8596. auto se = detail::scope_exit([&] {
  8597. svr.stop();
  8598. thread.join();
  8599. ASSERT_FALSE(svr.is_running());
  8600. });
  8601. svr.wait_until_ready();
  8602. {
  8603. Client cli(HOST, PORT);
  8604. cli.set_follow_location(true);
  8605. auto res = cli.Get("/");
  8606. ASSERT_TRUE(res);
  8607. EXPECT_EQ(StatusCode::OK_200, res->status);
  8608. EXPECT_EQ("val&key2=val2", res->body);
  8609. }
  8610. }
  8611. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8612. Server svr;
  8613. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8614. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8615. });
  8616. svr.Get("/hello", [](const Request &req, Response &res) {
  8617. res.set_content(req.get_param_value("key"), "text/plain");
  8618. });
  8619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8620. auto se = detail::scope_exit([&] {
  8621. svr.stop();
  8622. thread.join();
  8623. ASSERT_FALSE(svr.is_running());
  8624. });
  8625. svr.wait_until_ready();
  8626. {
  8627. Client cli(HOST, PORT);
  8628. cli.set_follow_location(true);
  8629. auto res = cli.Get("/");
  8630. ASSERT_TRUE(res);
  8631. EXPECT_EQ(StatusCode::OK_200, res->status);
  8632. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8633. }
  8634. }
  8635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8636. TEST(RedirectTest, Issue2185_Online) {
  8637. SSLClient client("github.com");
  8638. client.set_follow_location(true);
  8639. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8640. "Coollab-Windows.zip");
  8641. ASSERT_TRUE(res);
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. EXPECT_EQ(9920427U, res->body.size());
  8644. }
  8645. #endif
  8646. TEST(VulnerabilityTest, CRLFInjection) {
  8647. Server svr;
  8648. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8649. res.set_content("Hello 1", "text/plain");
  8650. });
  8651. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8652. res.set_content("Hello 2", "text/plain");
  8653. });
  8654. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8655. res.set_content("Hello 3", "text/plain");
  8656. });
  8657. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8658. res.set_content("Hello 4", "text/plain");
  8659. });
  8660. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8661. for (const auto &x : req.headers) {
  8662. auto key = x.first;
  8663. EXPECT_STRNE("evil", key.c_str());
  8664. }
  8665. });
  8666. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. thread.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. {
  8674. Client cli(HOST, PORT);
  8675. cli.Post("/test1", "A=B",
  8676. "application/x-www-form-urlencoded\r\nevil: hello1");
  8677. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8678. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8679. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8680. }
  8681. }
  8682. TEST(PathParamsTest, StaticMatch) {
  8683. const auto pattern = "/users/all";
  8684. detail::PathParamsMatcher matcher(pattern);
  8685. Request request;
  8686. request.path = "/users/all";
  8687. ASSERT_TRUE(matcher.match(request));
  8688. std::unordered_map<std::string, std::string> expected_params = {};
  8689. EXPECT_EQ(request.path_params, expected_params);
  8690. }
  8691. TEST(PathParamsTest, StaticMismatch) {
  8692. const auto pattern = "/users/all";
  8693. detail::PathParamsMatcher matcher(pattern);
  8694. Request request;
  8695. request.path = "/users/1";
  8696. ASSERT_FALSE(matcher.match(request));
  8697. }
  8698. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8699. const auto pattern = "/users/:id/subscriptions";
  8700. detail::PathParamsMatcher matcher(pattern);
  8701. Request request;
  8702. request.path = "/users/42/subscriptions";
  8703. ASSERT_TRUE(matcher.match(request));
  8704. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8705. EXPECT_EQ(request.path_params, expected_params);
  8706. }
  8707. TEST(PathParamsTest, SingleParamInTheEnd) {
  8708. const auto pattern = "/users/:id";
  8709. detail::PathParamsMatcher matcher(pattern);
  8710. Request request;
  8711. request.path = "/users/24";
  8712. ASSERT_TRUE(matcher.match(request));
  8713. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8714. EXPECT_EQ(request.path_params, expected_params);
  8715. }
  8716. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8717. const auto pattern = "/users/:id/";
  8718. detail::PathParamsMatcher matcher(pattern);
  8719. Request request;
  8720. request.path = "/users/42/";
  8721. ASSERT_TRUE(matcher.match(request));
  8722. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8723. EXPECT_EQ(request.path_params, expected_params);
  8724. }
  8725. TEST(PathParamsTest, EmptyParam) {
  8726. const auto pattern = "/users/:id/";
  8727. detail::PathParamsMatcher matcher(pattern);
  8728. Request request;
  8729. request.path = "/users//";
  8730. ASSERT_TRUE(matcher.match(request));
  8731. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8732. EXPECT_EQ(request.path_params, expected_params);
  8733. }
  8734. TEST(PathParamsTest, FragmentMismatch) {
  8735. const auto pattern = "/users/:id/";
  8736. detail::PathParamsMatcher matcher(pattern);
  8737. Request request;
  8738. request.path = "/admins/24/";
  8739. ASSERT_FALSE(matcher.match(request));
  8740. }
  8741. TEST(PathParamsTest, ExtraFragments) {
  8742. const auto pattern = "/users/:id";
  8743. detail::PathParamsMatcher matcher(pattern);
  8744. Request request;
  8745. request.path = "/users/42/subscriptions";
  8746. ASSERT_FALSE(matcher.match(request));
  8747. }
  8748. TEST(PathParamsTest, MissingTrailingParam) {
  8749. const auto pattern = "/users/:id";
  8750. detail::PathParamsMatcher matcher(pattern);
  8751. Request request;
  8752. request.path = "/users";
  8753. ASSERT_FALSE(matcher.match(request));
  8754. }
  8755. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8756. const auto pattern = "/users/:id/subscriptions";
  8757. detail::PathParamsMatcher matcher(pattern);
  8758. Request request;
  8759. request.path = "/users/subscriptions";
  8760. ASSERT_FALSE(matcher.match(request));
  8761. }
  8762. TEST(PathParamsTest, MultipleParams) {
  8763. const auto pattern = "/users/:userid/subscriptions/:subid";
  8764. detail::PathParamsMatcher matcher(pattern);
  8765. Request request;
  8766. request.path = "/users/42/subscriptions/2";
  8767. ASSERT_TRUE(matcher.match(request));
  8768. std::unordered_map<std::string, std::string> expected_params = {
  8769. {"userid", "42"}, {"subid", "2"}};
  8770. EXPECT_EQ(request.path_params, expected_params);
  8771. }
  8772. TEST(PathParamsTest, SequenceOfParams) {
  8773. const auto pattern = "/values/:x/:y/:z";
  8774. detail::PathParamsMatcher matcher(pattern);
  8775. Request request;
  8776. request.path = "/values/1/2/3";
  8777. ASSERT_TRUE(matcher.match(request));
  8778. std::unordered_map<std::string, std::string> expected_params = {
  8779. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8780. EXPECT_EQ(request.path_params, expected_params);
  8781. }
  8782. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8783. const auto pattern = "/prefix:suffix";
  8784. detail::PathParamsMatcher matcher(pattern);
  8785. Request request;
  8786. request.path = "/prefix:suffix";
  8787. ASSERT_TRUE(matcher.match(request));
  8788. const std::unordered_map<std::string, std::string> expected_params = {};
  8789. EXPECT_EQ(request.path_params, expected_params);
  8790. }
  8791. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8792. // If ipv6 regex working, regex match codepath is taken.
  8793. // else port will default to 80 in Client impl
  8794. int clientImplMagicPort = 80;
  8795. int port = 4321;
  8796. // above ports must be different to avoid false negative
  8797. EXPECT_NE(clientImplMagicPort, port);
  8798. std::string ipV6TestURL = "http://[ff06::c3]";
  8799. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8800. CLIENT_PRIVATE_KEY_FILE);
  8801. EXPECT_EQ(cli.port(), port);
  8802. }
  8803. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8804. auto file_path = "./www/dir/index.html";
  8805. auto dir_path = "./www/dir";
  8806. detail::FileStat stat_file(file_path);
  8807. EXPECT_TRUE(stat_file.is_file());
  8808. EXPECT_FALSE(stat_file.is_dir());
  8809. detail::FileStat stat_dir(dir_path);
  8810. EXPECT_FALSE(stat_dir.is_file());
  8811. EXPECT_TRUE(stat_dir.is_dir());
  8812. }
  8813. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8814. // IPv4 with default HTTP port (80)
  8815. EXPECT_EQ("example.com",
  8816. detail::make_host_and_port_string("example.com", 80, false));
  8817. // IPv4 with default HTTPS port (443)
  8818. EXPECT_EQ("example.com",
  8819. detail::make_host_and_port_string("example.com", 443, true));
  8820. // IPv4 with non-default HTTP port
  8821. EXPECT_EQ("example.com:8080",
  8822. detail::make_host_and_port_string("example.com", 8080, false));
  8823. // IPv4 with non-default HTTPS port
  8824. EXPECT_EQ("example.com:8443",
  8825. detail::make_host_and_port_string("example.com", 8443, true));
  8826. // IPv6 with default HTTP port (80)
  8827. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8828. // IPv6 with default HTTPS port (443)
  8829. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8830. // IPv6 with non-default HTTP port
  8831. EXPECT_EQ("[::1]:8080",
  8832. detail::make_host_and_port_string("::1", 8080, false));
  8833. // IPv6 with non-default HTTPS port
  8834. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8835. // IPv6 full address with default port
  8836. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8837. detail::make_host_and_port_string(
  8838. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8839. // IPv6 full address with non-default port
  8840. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8841. detail::make_host_and_port_string(
  8842. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8843. // IPv6 localhost with non-default port
  8844. EXPECT_EQ("[::1]:3000",
  8845. detail::make_host_and_port_string("::1", 3000, false));
  8846. // IPv6 with zone ID (link-local address) with default port
  8847. EXPECT_EQ("[fe80::1%eth0]",
  8848. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8849. // IPv6 with zone ID (link-local address) with non-default port
  8850. EXPECT_EQ("[fe80::1%eth0]:8080",
  8851. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8852. // Edge case: Port 443 with is_ssl=false (should add port)
  8853. EXPECT_EQ("example.com:443",
  8854. detail::make_host_and_port_string("example.com", 443, false));
  8855. // Edge case: Port 80 with is_ssl=true (should add port)
  8856. EXPECT_EQ("example.com:80",
  8857. detail::make_host_and_port_string("example.com", 80, true));
  8858. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8859. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8860. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8861. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8862. // Security fix: Already bracketed IPv6 should not get double brackets
  8863. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8864. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8865. EXPECT_EQ("[::1]:8080",
  8866. detail::make_host_and_port_string("[::1]", 8080, false));
  8867. EXPECT_EQ("[2001:db8::1]:8080",
  8868. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8869. EXPECT_EQ("[fe80::1%eth0]",
  8870. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8871. EXPECT_EQ("[fe80::1%eth0]:8080",
  8872. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8873. // Edge case: Empty host (should return as-is)
  8874. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8875. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8876. // This is a known limitation but shouldn't crash
  8877. EXPECT_EQ("[host:name]",
  8878. detail::make_host_and_port_string("host:name", 80, false));
  8879. // Port number edge cases (no validation, but should not crash)
  8880. EXPECT_EQ("example.com:0",
  8881. detail::make_host_and_port_string("example.com", 0, false));
  8882. EXPECT_EQ("example.com:-1",
  8883. detail::make_host_and_port_string("example.com", -1, false));
  8884. EXPECT_EQ("example.com:65535",
  8885. detail::make_host_and_port_string("example.com", 65535, false));
  8886. EXPECT_EQ("example.com:65536",
  8887. detail::make_host_and_port_string("example.com", 65536, false));
  8888. }
  8889. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8890. Server svr;
  8891. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8892. EXPECT_EQ(res.status, 400);
  8893. });
  8894. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8895. auto se = detail::scope_exit([&] {
  8896. svr.stop();
  8897. thread.join();
  8898. ASSERT_FALSE(svr.is_running());
  8899. });
  8900. svr.wait_until_ready();
  8901. Client cli(HOST, PORT);
  8902. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8903. }
  8904. TEST(InvalidHeaderCharsTest, is_field_name) {
  8905. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8906. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8907. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8908. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8909. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8910. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8911. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8912. EXPECT_FALSE(detail::fields::is_field_name(""));
  8913. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8914. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8915. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8916. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8917. }
  8918. TEST(InvalidHeaderCharsTest, is_field_value) {
  8919. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8920. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8921. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8922. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8923. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8924. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8925. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8926. EXPECT_TRUE(detail::fields::is_field_value(""));
  8927. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8928. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8929. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8930. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8931. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8932. }
  8933. TEST(InvalidHeaderCharsTest, OnServer) {
  8934. Server svr;
  8935. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8936. std::string header = "Not Set";
  8937. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8938. res.set_header(header, "value");
  8939. res.set_content("Page Content Page Content", "text/plain");
  8940. });
  8941. svr.Get("/test_value", [&](const Request &req, Response &res) {
  8942. std::string header = "Not Set";
  8943. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8944. res.set_header("X-Test", header);
  8945. res.set_content("Page Content Page Content", "text/plain");
  8946. });
  8947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. thread.join();
  8951. ASSERT_FALSE(svr.is_running());
  8952. });
  8953. svr.wait_until_ready();
  8954. Client cli(HOST, PORT);
  8955. {
  8956. auto res = cli.Get(
  8957. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8958. ASSERT_TRUE(res);
  8959. EXPECT_EQ("Page Content Page Content", res->body);
  8960. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8961. }
  8962. {
  8963. auto res = cli.Get(
  8964. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  8965. ASSERT_TRUE(res);
  8966. EXPECT_EQ("Page Content Page Content", res->body);
  8967. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  8968. }
  8969. }
  8970. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  8971. auto handled = false;
  8972. Server svr;
  8973. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  8974. thread t = thread([&] { svr.listen(HOST, PORT); });
  8975. auto se = detail::scope_exit([&] {
  8976. svr.stop();
  8977. t.join();
  8978. ASSERT_FALSE(svr.is_running());
  8979. ASSERT_FALSE(handled);
  8980. });
  8981. svr.wait_until_ready();
  8982. auto req = "POST /test HTTP/1.1\r\n"
  8983. "Content-Length: x\r\n"
  8984. "\r\n";
  8985. std::string response;
  8986. ASSERT_TRUE(send_request(1, req, &response));
  8987. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  8988. response.substr(0, response.find("\r\n")));
  8989. }
  8990. #ifndef _WIN32
  8991. TEST(Expect100ContinueTest, ServerClosesConnection) {
  8992. static constexpr char reject[] = "Unauthorized";
  8993. static constexpr char accept[] = "Upload accepted";
  8994. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  8995. Server svr;
  8996. svr.set_expect_100_continue_handler(
  8997. [](const Request & /*req*/, Response &res) {
  8998. res.status = StatusCode::Unauthorized_401;
  8999. res.set_content(reject, "text/plain");
  9000. return res.status;
  9001. });
  9002. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9003. res.set_content(accept, "text/plain");
  9004. });
  9005. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9006. auto se = detail::scope_exit([&] {
  9007. svr.stop();
  9008. thread.join();
  9009. ASSERT_FALSE(svr.is_running());
  9010. });
  9011. svr.wait_until_ready();
  9012. {
  9013. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9014. curl_easy_init(), &curl_easy_cleanup};
  9015. ASSERT_NE(curl, nullptr);
  9016. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9017. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9018. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9019. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9020. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9021. &curl_slist_free_all};
  9022. ASSERT_NE(list, nullptr);
  9023. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9024. struct read_data {
  9025. size_t read_size;
  9026. size_t total_size;
  9027. } data = {0, total_size};
  9028. using read_callback_t =
  9029. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9030. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9031. void *userdata) -> size_t {
  9032. read_data *data = (read_data *)userdata;
  9033. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9034. std::fill_n(ptr, size * nmemb, 'A');
  9035. data->read_size += size * nmemb;
  9036. return size * nmemb;
  9037. };
  9038. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9039. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9040. std::vector<char> buffer;
  9041. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9042. using write_callback_t =
  9043. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9044. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9045. void *userdata) -> size_t {
  9046. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9047. buffer->reserve(buffer->size() + size * nmemb + 1);
  9048. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9049. return size * nmemb;
  9050. };
  9051. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9052. {
  9053. const auto res = curl_easy_perform(curl.get());
  9054. ASSERT_EQ(res, CURLE_OK);
  9055. }
  9056. {
  9057. auto response_code = long{};
  9058. const auto res =
  9059. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9060. ASSERT_EQ(res, CURLE_OK);
  9061. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9062. }
  9063. {
  9064. auto dl = curl_off_t{};
  9065. const auto res =
  9066. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9067. ASSERT_EQ(res, CURLE_OK);
  9068. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9069. }
  9070. {
  9071. buffer.push_back('\0');
  9072. ASSERT_STRCASEEQ(buffer.data(), reject);
  9073. }
  9074. }
  9075. }
  9076. #endif
  9077. template <typename S, typename C>
  9078. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9079. svr.Get("/stream", [&](const Request &, Response &res) {
  9080. auto data = new std::string("01234567890123456789");
  9081. res.set_content_provider(
  9082. data->size(), "text/plain",
  9083. [&, data](size_t offset, size_t length, DataSink &sink) {
  9084. const size_t DATA_CHUNK_SIZE = 4;
  9085. const auto &d = *data;
  9086. std::this_thread::sleep_for(std::chrono::seconds(1));
  9087. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9088. return true;
  9089. },
  9090. [data](bool success) {
  9091. EXPECT_FALSE(success);
  9092. delete data;
  9093. });
  9094. });
  9095. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9096. auto i = new size_t(0);
  9097. res.set_content_provider(
  9098. "text/plain",
  9099. [i](size_t, DataSink &sink) {
  9100. if (*i < 5) {
  9101. std::this_thread::sleep_for(std::chrono::seconds(1));
  9102. sink.write("abcd", 4);
  9103. (*i)++;
  9104. } else {
  9105. sink.done();
  9106. }
  9107. return true;
  9108. },
  9109. [i](bool success) {
  9110. EXPECT_FALSE(success);
  9111. delete i;
  9112. });
  9113. });
  9114. svr.Get("/chunked", [&](const Request &, Response &res) {
  9115. auto i = new size_t(0);
  9116. res.set_chunked_content_provider(
  9117. "text/plain",
  9118. [i](size_t, DataSink &sink) {
  9119. if (*i < 5) {
  9120. std::this_thread::sleep_for(std::chrono::seconds(1));
  9121. sink.os << "abcd";
  9122. (*i)++;
  9123. } else {
  9124. sink.done();
  9125. }
  9126. return true;
  9127. },
  9128. [i](bool success) {
  9129. EXPECT_FALSE(success);
  9130. delete i;
  9131. });
  9132. });
  9133. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9134. auto se = detail::scope_exit([&] {
  9135. svr.stop();
  9136. listen_thread.join();
  9137. ASSERT_FALSE(svr.is_running());
  9138. });
  9139. svr.wait_until_ready();
  9140. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9141. {
  9142. auto start = std::chrono::steady_clock::now();
  9143. auto res = cli.Get("/stream");
  9144. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9145. std::chrono::steady_clock::now() - start)
  9146. .count();
  9147. ASSERT_FALSE(res);
  9148. EXPECT_EQ(Error::Read, res.error());
  9149. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9150. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9151. }
  9152. {
  9153. auto start = std::chrono::steady_clock::now();
  9154. auto res = cli.Get("/stream_without_length");
  9155. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9156. std::chrono::steady_clock::now() - start)
  9157. .count();
  9158. ASSERT_FALSE(res);
  9159. EXPECT_EQ(Error::Read, res.error());
  9160. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9161. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9162. }
  9163. {
  9164. auto start = std::chrono::steady_clock::now();
  9165. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9166. EXPECT_EQ("abcd", string(data, data_length));
  9167. return true;
  9168. });
  9169. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9170. std::chrono::steady_clock::now() - start)
  9171. .count();
  9172. ASSERT_FALSE(res);
  9173. EXPECT_EQ(Error::Read, res.error());
  9174. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9175. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9176. }
  9177. }
  9178. TEST(MaxTimeoutTest, ContentStream) {
  9179. time_t timeout = 2000;
  9180. time_t threshold = 200;
  9181. Server svr;
  9182. Client cli("localhost", PORT);
  9183. max_timeout_test(svr, cli, timeout, threshold);
  9184. }
  9185. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9186. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9187. time_t timeout = 2000;
  9188. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9190. SSLClient cli("localhost", PORT);
  9191. cli.enable_server_certificate_verification(false);
  9192. max_timeout_test(svr, cli, timeout, threshold);
  9193. }
  9194. #endif
  9195. class EventDispatcher {
  9196. public:
  9197. EventDispatcher() {}
  9198. bool wait_event(DataSink *sink) {
  9199. unique_lock<mutex> lk(m_);
  9200. int id = id_;
  9201. // Wait with timeout to prevent hanging if client disconnects
  9202. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9203. [&] { return cid_ == id; })) {
  9204. return false; // Timeout occurred
  9205. }
  9206. sink->write(message_.data(), message_.size());
  9207. return true;
  9208. }
  9209. void send_event(const string &message) {
  9210. lock_guard<mutex> lk(m_);
  9211. cid_ = id_++;
  9212. message_ = message;
  9213. cv_.notify_all();
  9214. }
  9215. private:
  9216. mutex m_;
  9217. condition_variable cv_;
  9218. atomic_int id_{0};
  9219. atomic_int cid_{-1};
  9220. string message_;
  9221. };
  9222. TEST(ClientInThreadTest, Issue2068) {
  9223. EventDispatcher ed;
  9224. Server svr;
  9225. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9226. res.set_chunked_content_provider("text/event-stream",
  9227. [&](size_t /*offset*/, DataSink &sink) {
  9228. return ed.wait_event(&sink);
  9229. });
  9230. });
  9231. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9232. svr.wait_until_ready();
  9233. thread event_thread([&] {
  9234. int id = 0;
  9235. while (svr.is_running()) {
  9236. this_thread::sleep_for(chrono::milliseconds(500));
  9237. std::stringstream ss;
  9238. ss << "data: " << id << "\n\n";
  9239. ed.send_event(ss.str());
  9240. id++;
  9241. }
  9242. });
  9243. auto se = detail::scope_exit([&] {
  9244. svr.stop();
  9245. listen_thread.join();
  9246. event_thread.join();
  9247. ASSERT_FALSE(svr.is_running());
  9248. });
  9249. {
  9250. auto client = detail::make_unique<Client>(HOST, PORT);
  9251. client->set_read_timeout(std::chrono::minutes(10));
  9252. std::atomic<bool> stop{false};
  9253. std::thread t([&] {
  9254. client->Get("/event1",
  9255. [&](const char *, size_t) -> bool { return !stop; });
  9256. });
  9257. std::this_thread::sleep_for(std::chrono::seconds(2));
  9258. stop = true;
  9259. client->stop();
  9260. t.join();
  9261. // Reset client after thread has finished
  9262. client.reset();
  9263. }
  9264. }
  9265. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9266. Server svr;
  9267. svr.Get("/", [](const Request &req, Response &res) {
  9268. EXPECT_EQ(2U, req.trailers.size());
  9269. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9270. // Denied
  9271. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9272. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9273. // Accepted
  9274. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9275. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9276. EXPECT_TRUE(req.has_trailer("X-World"));
  9277. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9278. res.set_content("ok", "text/plain");
  9279. });
  9280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9281. auto se = detail::scope_exit([&] {
  9282. svr.stop();
  9283. t.join();
  9284. ASSERT_FALSE(svr.is_running());
  9285. });
  9286. svr.wait_until_ready();
  9287. const std::string req = "GET / HTTP/1.1\r\n"
  9288. "Transfer-Encoding: chunked\r\n"
  9289. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9290. "\r\n"
  9291. "0\r\n"
  9292. "Content-Length: 10\r\n"
  9293. "Host: internal.local\r\n"
  9294. "Content-Type: malicious/content\r\n"
  9295. "Cookie: any\r\n"
  9296. "Set-Cookie: any\r\n"
  9297. "X-Forwarded-For: attacker.com\r\n"
  9298. "X-Real-Ip: 1.1.1.1\r\n"
  9299. "X-Hello: hello\r\n"
  9300. "X-World: world\r\n"
  9301. "\r\n";
  9302. std::string res;
  9303. ASSERT_TRUE(send_request(1, req, &res));
  9304. }