test.cc 352 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <curl/curl.h>
  7. #include <netinet/in.h>
  8. #include <sys/socket.h>
  9. #include <unistd.h>
  10. #endif
  11. #include <gtest/gtest.h>
  12. #include <algorithm>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <cstdio>
  16. #include <fstream>
  17. #include <future>
  18. #include <limits>
  19. #include <memory>
  20. #include <sstream>
  21. #include <stdexcept>
  22. #include <thread>
  23. #include <type_traits>
  24. #include <vector>
  25. #define SERVER_CERT_FILE "./cert.pem"
  26. #define SERVER_CERT2_FILE "./cert2.pem"
  27. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  28. #define CA_CERT_FILE "./ca-bundle.crt"
  29. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  30. #define CLIENT_CA_CERT_DIR "."
  31. #define CLIENT_CERT_FILE "./client.cert.pem"
  32. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  33. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  34. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  35. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  36. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  37. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  38. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  39. using namespace std;
  40. using namespace httplib;
  41. const char *HOST = "localhost";
  42. const int PORT = 1234;
  43. const string LONG_QUERY_VALUE = string(25000, '@');
  44. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  45. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  46. const string TOO_LONG_QUERY_URL =
  47. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  48. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  49. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  50. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  51. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  52. return file.name == key;
  53. });
  54. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  55. return *it;
  56. #else
  57. if (it != items.end()) { return *it; }
  58. throw std::runtime_error("invalid multipart form data name error");
  59. #endif
  60. }
  61. static void read_file(const std::string &path, std::string &out) {
  62. std::ifstream fs(path, std::ios_base::binary);
  63. if (!fs) throw std::runtime_error("File not found: " + path);
  64. fs.seekg(0, std::ios_base::end);
  65. auto size = fs.tellg();
  66. fs.seekg(0);
  67. out.resize(static_cast<size_t>(size));
  68. fs.read(&out[0], static_cast<std::streamsize>(size));
  69. }
  70. void performance_test(const char *host) {
  71. auto port = 1234;
  72. Server svr;
  73. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  74. res.set_content("Benchmark Response", "text/plain");
  75. });
  76. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  77. auto se = detail::scope_exit([&] {
  78. svr.stop();
  79. listen_thread.join();
  80. ASSERT_FALSE(svr.is_running());
  81. });
  82. svr.wait_until_ready();
  83. Client cli(host, port);
  84. // Warm-up request to establish connection and resolve DNS
  85. auto warmup_res = cli.Get("/benchmark");
  86. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  87. // Run multiple trials and collect timings
  88. const int num_trials = 20;
  89. std::vector<int64_t> timings;
  90. timings.reserve(num_trials);
  91. for (int i = 0; i < num_trials; i++) {
  92. auto start = std::chrono::high_resolution_clock::now();
  93. auto res = cli.Get("/benchmark");
  94. auto end = std::chrono::high_resolution_clock::now();
  95. auto elapsed =
  96. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  97. .count();
  98. // Assertions after timing measurement to avoid overhead
  99. ASSERT_TRUE(res);
  100. EXPECT_EQ(StatusCode::OK_200, res->status);
  101. timings.push_back(elapsed);
  102. }
  103. // Calculate 25th percentile (lower quartile)
  104. std::sort(timings.begin(), timings.end());
  105. auto p25 = timings[num_trials / 4];
  106. // Format timings for output
  107. std::ostringstream timings_str;
  108. timings_str << "[";
  109. for (size_t i = 0; i < timings.size(); i++) {
  110. if (i > 0) timings_str << ", ";
  111. timings_str << timings[i];
  112. }
  113. timings_str << "]";
  114. // Localhost HTTP GET should be fast even in CI environments
  115. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  116. << "ms (Issue #1777). Timings: " << timings_str.str();
  117. }
  118. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  119. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  120. class UnixSocketTest : public ::testing::Test {
  121. protected:
  122. void TearDown() override { std::remove(pathname_.c_str()); }
  123. void client_GET(const std::string &addr) {
  124. httplib::Client cli{addr};
  125. cli.set_address_family(AF_UNIX);
  126. ASSERT_TRUE(cli.is_valid());
  127. const auto &result = cli.Get(pattern_);
  128. ASSERT_TRUE(result) << "error: " << result.error();
  129. const auto &resp = result.value();
  130. EXPECT_EQ(resp.status, StatusCode::OK_200);
  131. EXPECT_EQ(resp.body, content_);
  132. }
  133. const std::string pathname_{"./httplib-server.sock"};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. }
  154. #if defined(__linux__) || \
  155. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  156. TEST_F(UnixSocketTest, PeerPid) {
  157. httplib::Server svr;
  158. std::string remote_port_val;
  159. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  160. res.set_content(content_, "text/plain");
  161. remote_port_val = std::to_string(req.remote_port);
  162. });
  163. std::thread t{[&] {
  164. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  165. }};
  166. auto se = detail::scope_exit([&] {
  167. svr.stop();
  168. t.join();
  169. ASSERT_FALSE(svr.is_running());
  170. });
  171. svr.wait_until_ready();
  172. ASSERT_TRUE(svr.is_running());
  173. client_GET(pathname_);
  174. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  175. }
  176. #endif
  177. #ifdef __linux__
  178. TEST_F(UnixSocketTest, abstract) {
  179. constexpr char svr_path[]{"\x00httplib-server.sock"};
  180. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  181. httplib::Server svr;
  182. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  183. res.set_content(content_, "text/plain");
  184. });
  185. std::thread t{[&] {
  186. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  187. }};
  188. auto se = detail::scope_exit([&] {
  189. svr.stop();
  190. t.join();
  191. ASSERT_FALSE(svr.is_running());
  192. });
  193. svr.wait_until_ready();
  194. ASSERT_TRUE(svr.is_running());
  195. client_GET(abstract_addr);
  196. }
  197. #endif
  198. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  199. httplib::Server svr;
  200. std::string received_host_header;
  201. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  202. // Capture the Host header sent by the client
  203. auto host_iter = req.headers.find("Host");
  204. if (host_iter != req.headers.end()) {
  205. received_host_header = host_iter->second;
  206. }
  207. res.set_content(content_, "text/plain");
  208. });
  209. std::thread t{[&] {
  210. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  211. }};
  212. auto se = detail::scope_exit([&] {
  213. svr.stop();
  214. t.join();
  215. ASSERT_FALSE(svr.is_running());
  216. });
  217. svr.wait_until_ready();
  218. ASSERT_TRUE(svr.is_running());
  219. // Test that Host header is automatically set to "localhost" for Unix socket
  220. // connections
  221. httplib::Client cli{pathname_};
  222. cli.set_address_family(AF_UNIX);
  223. ASSERT_TRUE(cli.is_valid());
  224. const auto &result = cli.Get(pattern_);
  225. ASSERT_TRUE(result) << "error: " << result.error();
  226. const auto &resp = result.value();
  227. EXPECT_EQ(resp.status, StatusCode::OK_200);
  228. EXPECT_EQ(resp.body, content_);
  229. // Verify that Host header was automatically set to "localhost"
  230. EXPECT_EQ(received_host_header, "localhost");
  231. }
  232. #ifndef _WIN32
  233. TEST(SocketStream, wait_writable_UNIX) {
  234. int fds[2];
  235. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  236. const auto asSocketStream = [&](socket_t fd,
  237. std::function<bool(Stream &)> func) {
  238. return detail::process_client_socket(
  239. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  240. };
  241. asSocketStream(fds[0], [&](Stream &s0) {
  242. EXPECT_EQ(s0.socket(), fds[0]);
  243. EXPECT_TRUE(s0.wait_writable());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.wait_writable());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(PORT + 1);
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  261. ASSERT_EQ(0, listen(s, 1));
  262. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  263. ASSERT_EQ(0, close(s));
  264. }};
  265. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  266. std::thread cli{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, close(s));
  271. }};
  272. cli.join();
  273. svr.join();
  274. ASSERT_NE(disconnected_svr_sock, -1);
  275. const auto asSocketStream = [&](socket_t fd,
  276. std::function<bool(Stream &)> func) {
  277. return detail::process_client_socket(
  278. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  279. };
  280. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  281. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  282. EXPECT_FALSE(ss.wait_writable());
  283. return true;
  284. });
  285. ASSERT_EQ(0, close(disconnected_svr_sock));
  286. }
  287. #endif // #ifndef _WIN32
  288. TEST(ClientTest, MoveConstructible) {
  289. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  290. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  291. }
  292. TEST(ClientTest, MoveAssignable) {
  293. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  294. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  295. }
  296. #ifdef _WIN32
  297. TEST(StartupTest, WSAStartup) {
  298. WSADATA wsaData;
  299. int ret = WSAStartup(0x0002, &wsaData);
  300. ASSERT_EQ(0, ret);
  301. }
  302. #endif
  303. TEST(DecodePathTest, PercentCharacter) {
  304. EXPECT_EQ(
  305. decode_path_component(
  306. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  307. u8"descrip=Gastos áéíóúñÑ 6");
  308. }
  309. TEST(DecodePathTest, PercentCharacterNUL) {
  310. string expected;
  311. expected.push_back('x');
  312. expected.push_back('\0');
  313. expected.push_back('x');
  314. EXPECT_EQ(decode_path_component("x%00x"), expected);
  315. }
  316. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  317. string unescapedCharacters = "-_.!~*'()";
  318. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  319. }
  320. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  321. string reservedCharacters = ";,/?:@&=+$";
  322. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  323. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  324. }
  325. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  326. string chineseCharacters = u8"中国語";
  327. string russianCharacters = u8"дом";
  328. string brazilianCharacters = u8"óculos";
  329. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  330. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  331. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  332. "%D0%B4%D0%BE%D0%BC");
  333. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  334. }
  335. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  336. string unescapedCharacters = "-_.!~*'()";
  337. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  338. }
  339. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  340. string reservedCharacters = ";,/?:@&=+$";
  341. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  342. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  343. }
  344. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  345. string chineseCharacters = u8"中国語";
  346. string russianCharacters = u8"дом";
  347. string brazilianCharacters = u8"óculos";
  348. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  349. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  350. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  351. "%D0%B4%D0%BE%D0%BC");
  352. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  353. }
  354. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  355. // Issue #2082 use case: encoding path component with ampersand
  356. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  357. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  358. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  359. }
  360. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  361. string unescapedCharacters = "-_.!~*'()";
  362. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  363. }
  364. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  365. string reservedCharacters = ";,/?:@&=+$#";
  366. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  367. }
  368. TEST(EncodeUriTest, TestUTF8Characters) {
  369. string chineseCharacters = u8"中国語";
  370. string russianCharacters = u8"дом";
  371. string brazilianCharacters = u8"óculos";
  372. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  373. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  374. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  375. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  376. }
  377. TEST(EncodeUriTest, TestCompleteUri) {
  378. string uri =
  379. "https://example.com/path/to/resource?query=value&param=test#fragment";
  380. EXPECT_EQ(
  381. httplib::encode_uri(uri),
  382. "https://example.com/path/to/resource?query=value&param=test#fragment");
  383. }
  384. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  385. string uri =
  386. "https://example.com/path with spaces/file name.html?q=hello world";
  387. EXPECT_EQ(httplib::encode_uri(uri),
  388. "https://example.com/path%20with%20spaces/"
  389. "file%20name.html?q=hello%20world");
  390. }
  391. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  392. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  393. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  394. }
  395. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  400. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  401. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  402. string encodedBrazilian = "%C3%B3culos";
  403. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  404. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  405. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  406. }
  407. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  408. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  409. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  410. "Piri Tommy Villiers - on & on");
  411. }
  412. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  413. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  414. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  415. }
  416. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  417. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  418. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  419. }
  420. TEST(DecodeUriTest, TestUTF8Characters) {
  421. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  422. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  423. string encodedBrazilian = "%C3%B3culos";
  424. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  425. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  426. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  427. }
  428. TEST(DecodeUriTest, TestCompleteUri) {
  429. string encodedUri = "https://example.com/path%20with%20spaces/"
  430. "file%20name.html?q=hello%20world";
  431. EXPECT_EQ(
  432. httplib::decode_uri(encodedUri),
  433. "https://example.com/path with spaces/file name.html?q=hello world");
  434. }
  435. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  436. string original =
  437. "https://example.com/path with spaces/file name.html?q=hello world";
  438. string encoded = httplib::encode_uri(original);
  439. string decoded = httplib::decode_uri(encoded);
  440. EXPECT_EQ(decoded, original);
  441. }
  442. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  443. string original = "Piri Tommy Villiers - on & on";
  444. string encoded = httplib::encode_uri_component(original);
  445. string decoded = httplib::decode_uri_component(encoded);
  446. EXPECT_EQ(decoded, original);
  447. }
  448. TEST(TrimTests, TrimStringTests) {
  449. EXPECT_EQ("abc", detail::trim_copy("abc"));
  450. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  451. EXPECT_TRUE(detail::trim_copy("").empty());
  452. }
  453. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  454. // Simple case without quality values
  455. std::vector<std::string> result1;
  456. EXPECT_TRUE(detail::parse_accept_header(
  457. "text/html,application/json,text/plain", result1));
  458. EXPECT_EQ(result1.size(), 3U);
  459. EXPECT_EQ(result1[0], "text/html");
  460. EXPECT_EQ(result1[1], "application/json");
  461. EXPECT_EQ(result1[2], "text/plain");
  462. // With quality values
  463. std::vector<std::string> result2;
  464. EXPECT_TRUE(detail::parse_accept_header(
  465. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  466. EXPECT_EQ(result2.size(), 3U);
  467. EXPECT_EQ(result2[0], "application/json"); // highest q value
  468. EXPECT_EQ(result2[1], "text/html");
  469. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  470. }
  471. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  472. // Mixed with and without quality values
  473. std::vector<std::string> result;
  474. EXPECT_TRUE(detail::parse_accept_header(
  475. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  476. EXPECT_EQ(result.size(), 3U);
  477. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  478. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  479. EXPECT_EQ(result[2], "application/json"); // q=0.5
  480. }
  481. TEST(ParseAcceptHeaderTest, EdgeCases) {
  482. // Empty header
  483. std::vector<std::string> empty_result;
  484. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  485. EXPECT_TRUE(empty_result.empty());
  486. // Single type
  487. std::vector<std::string> single_result;
  488. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  489. EXPECT_EQ(single_result.size(), 1U);
  490. EXPECT_EQ(single_result[0], "application/json");
  491. // Wildcard types
  492. std::vector<std::string> wildcard_result;
  493. EXPECT_TRUE(detail::parse_accept_header(
  494. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  495. EXPECT_EQ(wildcard_result.size(), 3U);
  496. EXPECT_EQ(wildcard_result[0], "application/json");
  497. EXPECT_EQ(wildcard_result[1], "text/*");
  498. EXPECT_EQ(wildcard_result[2], "*/*");
  499. }
  500. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  501. // Common browser Accept header
  502. std::vector<std::string> browser_result;
  503. EXPECT_TRUE(
  504. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  505. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  506. browser_result));
  507. EXPECT_EQ(browser_result.size(), 6U);
  508. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  509. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  510. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  511. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  512. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  513. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  514. // API client header
  515. std::vector<std::string> api_result;
  516. EXPECT_TRUE(detail::parse_accept_header(
  517. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  518. api_result));
  519. EXPECT_EQ(api_result.size(), 3U);
  520. EXPECT_EQ(api_result[0], "application/json");
  521. EXPECT_EQ(api_result[1], "application/xml");
  522. EXPECT_EQ(api_result[2], "text/plain");
  523. }
  524. TEST(ParseAcceptHeaderTest, SpecialCases) {
  525. // Quality value with 3 decimal places
  526. std::vector<std::string> decimal_result;
  527. EXPECT_TRUE(detail::parse_accept_header(
  528. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  529. EXPECT_EQ(decimal_result.size(), 2U);
  530. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  531. EXPECT_EQ(decimal_result[1], "text/html");
  532. // Zero quality (should still be included but with lowest priority)
  533. std::vector<std::string> zero_q_result;
  534. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  535. zero_q_result));
  536. EXPECT_EQ(zero_q_result.size(), 2U);
  537. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  538. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  539. // No spaces around commas
  540. std::vector<std::string> no_space_result;
  541. EXPECT_TRUE(detail::parse_accept_header(
  542. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  543. no_space_result));
  544. EXPECT_EQ(no_space_result.size(), 3U);
  545. EXPECT_EQ(no_space_result[0], "text/html");
  546. EXPECT_EQ(no_space_result[1], "application/json");
  547. EXPECT_EQ(no_space_result[2], "text/plain");
  548. }
  549. TEST(ParseAcceptHeaderTest, InvalidCases) {
  550. std::vector<std::string> result;
  551. // Invalid quality value (> 1.0)
  552. EXPECT_FALSE(
  553. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  554. // Invalid quality value (< 0.0)
  555. EXPECT_FALSE(
  556. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  557. // Invalid quality value (not a number)
  558. EXPECT_FALSE(detail::parse_accept_header(
  559. "text/html;q=invalid,application/json", result));
  560. // Empty quality value
  561. EXPECT_FALSE(
  562. detail::parse_accept_header("text/html;q=,application/json", result));
  563. // Invalid media type format (no slash and not wildcard)
  564. EXPECT_FALSE(
  565. detail::parse_accept_header("invalidtype,application/json", result));
  566. // Empty media type
  567. result.clear();
  568. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  569. // Only commas
  570. result.clear();
  571. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  572. // Valid cases should still work
  573. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  574. EXPECT_EQ(result.size(), 1U);
  575. EXPECT_EQ(result[0], "*/*");
  576. EXPECT_TRUE(detail::parse_accept_header("*", result));
  577. EXPECT_EQ(result.size(), 1U);
  578. EXPECT_EQ(result[0], "*");
  579. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  580. EXPECT_EQ(result.size(), 1U);
  581. EXPECT_EQ(result[0], "text/*");
  582. }
  583. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  584. Server svr;
  585. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  586. EXPECT_EQ(req.accept_content_types.size(), 3U);
  587. EXPECT_EQ(req.accept_content_types[0], "application/json");
  588. EXPECT_EQ(req.accept_content_types[1], "text/html");
  589. EXPECT_EQ(req.accept_content_types[2], "*/*");
  590. res.set_content("ok", "text/plain");
  591. });
  592. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  593. EXPECT_TRUE(false);
  594. res.set_content("bad request", "text/plain");
  595. });
  596. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  597. auto se = detail::scope_exit([&] {
  598. svr.stop();
  599. listen_thread.join();
  600. ASSERT_FALSE(svr.is_running());
  601. });
  602. svr.wait_until_ready();
  603. Client cli("localhost", PORT);
  604. {
  605. auto res =
  606. cli.Get("/accept_ok",
  607. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  608. ASSERT_TRUE(res);
  609. EXPECT_EQ(StatusCode::OK_200, res->status);
  610. }
  611. {
  612. auto res = cli.Get("/accept_bad_request",
  613. {{"Accept", "text/html;q=abc,application/json"}});
  614. ASSERT_TRUE(res);
  615. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  616. }
  617. }
  618. TEST(DivideTest, DivideStringTests) {
  619. auto divide = [](const std::string &str, char d) {
  620. std::string lhs;
  621. std::string rhs;
  622. detail::divide(str, d,
  623. [&](const char *lhs_data, std::size_t lhs_size,
  624. const char *rhs_data, std::size_t rhs_size) {
  625. lhs.assign(lhs_data, lhs_size);
  626. rhs.assign(rhs_data, rhs_size);
  627. });
  628. return std::make_pair(std::move(lhs), std::move(rhs));
  629. };
  630. {
  631. const auto res = divide("", '=');
  632. EXPECT_EQ(res.first, "");
  633. EXPECT_EQ(res.second, "");
  634. }
  635. {
  636. const auto res = divide("=", '=');
  637. EXPECT_EQ(res.first, "");
  638. EXPECT_EQ(res.second, "");
  639. }
  640. {
  641. const auto res = divide(" ", '=');
  642. EXPECT_EQ(res.first, " ");
  643. EXPECT_EQ(res.second, "");
  644. }
  645. {
  646. const auto res = divide("a", '=');
  647. EXPECT_EQ(res.first, "a");
  648. EXPECT_EQ(res.second, "");
  649. }
  650. {
  651. const auto res = divide("a=", '=');
  652. EXPECT_EQ(res.first, "a");
  653. EXPECT_EQ(res.second, "");
  654. }
  655. {
  656. const auto res = divide("=b", '=');
  657. EXPECT_EQ(res.first, "");
  658. EXPECT_EQ(res.second, "b");
  659. }
  660. {
  661. const auto res = divide("a=b", '=');
  662. EXPECT_EQ(res.first, "a");
  663. EXPECT_EQ(res.second, "b");
  664. }
  665. {
  666. const auto res = divide("a=b=", '=');
  667. EXPECT_EQ(res.first, "a");
  668. EXPECT_EQ(res.second, "b=");
  669. }
  670. {
  671. const auto res = divide("a=b=c", '=');
  672. EXPECT_EQ(res.first, "a");
  673. EXPECT_EQ(res.second, "b=c");
  674. }
  675. }
  676. TEST(SplitTest, ParseQueryString) {
  677. string s = "key1=val1&key2=val2&key3=val3";
  678. Params dic;
  679. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  680. [&](const char *b, const char *e) {
  681. string key, val;
  682. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  683. if (key.empty()) {
  684. key.assign(b2, e2);
  685. } else {
  686. val.assign(b2, e2);
  687. }
  688. });
  689. dic.emplace(key, val);
  690. });
  691. EXPECT_EQ("val1", dic.find("key1")->second);
  692. EXPECT_EQ("val2", dic.find("key2")->second);
  693. EXPECT_EQ("val3", dic.find("key3")->second);
  694. }
  695. TEST(SplitTest, ParseInvalidQueryTests) {
  696. {
  697. string s = " ";
  698. Params dict;
  699. detail::parse_query_text(s, dict);
  700. EXPECT_TRUE(dict.empty());
  701. }
  702. {
  703. string s = " = =";
  704. Params dict;
  705. detail::parse_query_text(s, dict);
  706. EXPECT_TRUE(dict.empty());
  707. }
  708. }
  709. TEST(ParseQueryTest, ParseQueryString) {
  710. {
  711. std::string s = "key1=val1&key2=val2&key3=val3";
  712. Params dic;
  713. detail::parse_query_text(s, dic);
  714. EXPECT_EQ("val1", dic.find("key1")->second);
  715. EXPECT_EQ("val2", dic.find("key2")->second);
  716. EXPECT_EQ("val3", dic.find("key3")->second);
  717. }
  718. {
  719. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  720. Params dic;
  721. detail::parse_query_text(s, dic);
  722. EXPECT_EQ("", dic.find("key1")->second);
  723. EXPECT_EQ("val1", dic.find("key2")->second);
  724. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  725. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  726. }
  727. }
  728. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  729. Params dic;
  730. EXPECT_EQ(detail::params_to_query_str(dic), "");
  731. dic.emplace("key1", "val1");
  732. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  733. dic.emplace("key2", "val2");
  734. dic.emplace("key3", "val3");
  735. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  736. }
  737. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  738. string content_type = "multipart/form-data; boundary=something";
  739. string boundary;
  740. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  741. EXPECT_TRUE(ret);
  742. EXPECT_EQ(boundary, "something");
  743. }
  744. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  745. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  746. string boundary;
  747. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  748. EXPECT_TRUE(ret);
  749. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  750. }
  751. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  752. string content_type =
  753. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  754. string boundary;
  755. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  756. EXPECT_TRUE(ret);
  757. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  758. }
  759. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  760. string content_type =
  761. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  762. string boundary;
  763. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  764. EXPECT_TRUE(ret);
  765. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  766. }
  767. TEST(GetHeaderValueTest, DefaultValue) {
  768. Headers headers = {{"Dummy", "Dummy"}};
  769. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  770. EXPECT_STREQ("text/plain", val);
  771. }
  772. TEST(GetHeaderValueTest, DefaultValueInt) {
  773. Headers headers = {{"Dummy", "Dummy"}};
  774. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  775. EXPECT_EQ(100ull, val);
  776. }
  777. TEST(GetHeaderValueTest, RegularValue) {
  778. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  779. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  780. EXPECT_STREQ("text/html", val);
  781. }
  782. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  783. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  784. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  785. EXPECT_STREQ("text/html", val);
  786. }
  787. TEST(GetHeaderValueTest, SetContent) {
  788. Response res;
  789. res.set_content("html", "text/html");
  790. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  791. res.set_content("text", "text/plain");
  792. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  793. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  794. }
  795. TEST(GetHeaderValueTest, RegularValueInt) {
  796. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  798. EXPECT_EQ(100ull, val);
  799. }
  800. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  801. Headers headers = {{"Content-Length", "x"}};
  802. auto is_invalid_value = false;
  803. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  804. is_invalid_value);
  805. EXPECT_EQ(0ull, val);
  806. EXPECT_TRUE(is_invalid_value);
  807. }
  808. TEST(GetHeaderValueTest, Range) {
  809. {
  810. Headers headers = {make_range_header({{1, -1}})};
  811. auto val = detail::get_header_value(headers, "Range", 0, 0);
  812. EXPECT_STREQ("bytes=1-", val);
  813. }
  814. {
  815. Headers headers = {make_range_header({{-1, 1}})};
  816. auto val = detail::get_header_value(headers, "Range", 0, 0);
  817. EXPECT_STREQ("bytes=-1", val);
  818. }
  819. {
  820. Headers headers = {make_range_header({{1, 10}})};
  821. auto val = detail::get_header_value(headers, "Range", 0, 0);
  822. EXPECT_STREQ("bytes=1-10", val);
  823. }
  824. {
  825. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  826. auto val = detail::get_header_value(headers, "Range", 0, 0);
  827. EXPECT_STREQ("bytes=1-10, 100-", val);
  828. }
  829. {
  830. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  831. auto val = detail::get_header_value(headers, "Range", 0, 0);
  832. EXPECT_STREQ("bytes=1-10, 100-200", val);
  833. }
  834. {
  835. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  836. auto val = detail::get_header_value(headers, "Range", 0, 0);
  837. EXPECT_STREQ("bytes=0-0, -1", val);
  838. }
  839. }
  840. TEST(ParseHeaderValueTest, Range) {
  841. {
  842. Ranges ranges;
  843. auto ret = detail::parse_range_header("bytes=1-", ranges);
  844. EXPECT_TRUE(ret);
  845. EXPECT_EQ(1u, ranges.size());
  846. EXPECT_EQ(1u, ranges[0].first);
  847. EXPECT_EQ(-1, ranges[0].second);
  848. }
  849. {
  850. Ranges ranges;
  851. auto ret = detail::parse_range_header("bytes=-1", ranges);
  852. EXPECT_TRUE(ret);
  853. EXPECT_EQ(1u, ranges.size());
  854. EXPECT_EQ(-1, ranges[0].first);
  855. EXPECT_EQ(1u, ranges[0].second);
  856. }
  857. {
  858. Ranges ranges;
  859. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  860. EXPECT_TRUE(ret);
  861. EXPECT_EQ(1u, ranges.size());
  862. EXPECT_EQ(1u, ranges[0].first);
  863. EXPECT_EQ(10u, ranges[0].second);
  864. }
  865. {
  866. Ranges ranges;
  867. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  868. EXPECT_FALSE(ret);
  869. }
  870. {
  871. Ranges ranges;
  872. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  873. EXPECT_TRUE(ret);
  874. EXPECT_EQ(2u, ranges.size());
  875. EXPECT_EQ(1u, ranges[0].first);
  876. EXPECT_EQ(10u, ranges[0].second);
  877. EXPECT_EQ(100u, ranges[1].first);
  878. EXPECT_EQ(-1, ranges[1].second);
  879. }
  880. {
  881. Ranges ranges;
  882. auto ret =
  883. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  884. EXPECT_TRUE(ret);
  885. EXPECT_EQ(3u, ranges.size());
  886. EXPECT_EQ(1u, ranges[0].first);
  887. EXPECT_EQ(10u, ranges[0].second);
  888. EXPECT_EQ(100u, ranges[1].first);
  889. EXPECT_EQ(200u, ranges[1].second);
  890. EXPECT_EQ(300u, ranges[2].first);
  891. EXPECT_EQ(400u, ranges[2].second);
  892. }
  893. {
  894. Ranges ranges;
  895. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  896. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  897. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  898. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  899. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  900. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  901. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  902. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  903. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  904. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  905. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  906. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  907. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  908. EXPECT_TRUE(ranges.empty());
  909. }
  910. }
  911. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  912. Request req;
  913. req.set_header("Accept-Encoding", "gzip");
  914. Response res;
  915. res.set_header("Content-Type", "text/plain");
  916. auto ret = detail::encoding_type(req, res);
  917. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  918. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  919. #else
  920. EXPECT_TRUE(ret == detail::EncodingType::None);
  921. #endif
  922. }
  923. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  924. Request req;
  925. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  926. Response res;
  927. res.set_header("Content-Type", "text/plain");
  928. auto ret = detail::encoding_type(req, res);
  929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  930. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  931. #elif CPPHTTPLIB_ZLIB_SUPPORT
  932. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  933. #elif CPPHTTPLIB_ZSTD_SUPPORT
  934. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  935. #else
  936. EXPECT_TRUE(ret == detail::EncodingType::None);
  937. #endif
  938. }
  939. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding",
  942. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  943. Response res;
  944. res.set_header("Content-Type", "text/plain");
  945. auto ret = detail::encoding_type(req, res);
  946. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  947. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  948. #elif CPPHTTPLIB_ZLIB_SUPPORT
  949. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  950. #elif CPPHTTPLIB_ZSTD_SUPPORT
  951. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  952. #else
  953. EXPECT_TRUE(ret == detail::EncodingType::None);
  954. #endif
  955. }
  956. TEST(BufferStreamTest, read) {
  957. detail::BufferStream strm1;
  958. Stream &strm = strm1;
  959. EXPECT_EQ(5, strm.write("hello"));
  960. char buf[512];
  961. EXPECT_EQ(2, strm.read(buf, 2));
  962. EXPECT_EQ('h', buf[0]);
  963. EXPECT_EQ('e', buf[1]);
  964. EXPECT_EQ(2, strm.read(buf, 2));
  965. EXPECT_EQ('l', buf[0]);
  966. EXPECT_EQ('l', buf[1]);
  967. EXPECT_EQ(1, strm.read(buf, 1));
  968. EXPECT_EQ('o', buf[0]);
  969. EXPECT_EQ(0, strm.read(buf, 1));
  970. }
  971. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  972. auto host = "www.httpwatch.com";
  973. auto ip = hosted_at(host);
  974. EXPECT_EQ("23.96.13.243", ip);
  975. std::vector<std::string> addrs;
  976. hosted_at(host, addrs);
  977. EXPECT_EQ(1u, addrs.size());
  978. }
  979. #if 0 // It depends on each test environment...
  980. TEST(HostnameToIPConversionTest, YouTube_Online) {
  981. auto host = "www.youtube.com";
  982. std::vector<std::string> addrs;
  983. hosted_at(host, addrs);
  984. EXPECT_EQ(20u, addrs.size());
  985. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  986. EXPECT_TRUE(it != addrs.end());
  987. }
  988. #endif
  989. class ChunkedEncodingTest : public ::testing::Test {
  990. protected:
  991. ChunkedEncodingTest()
  992. : cli_(HOST, PORT)
  993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  994. ,
  995. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  996. #endif
  997. {
  998. cli_.set_connection_timeout(2);
  999. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1000. cli_.enable_server_certificate_verification(false);
  1001. #endif
  1002. }
  1003. virtual void SetUp() {
  1004. read_file("./image.jpg", image_data_);
  1005. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1006. res.set_content("Hello World!", "text/plain");
  1007. });
  1008. svr_.Get(
  1009. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1010. res.set_chunked_content_provider(
  1011. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1012. size_t remaining = image_data_.size() - offset;
  1013. if (remaining == 0) {
  1014. sink.done();
  1015. } else {
  1016. constexpr size_t CHUNK_SIZE = 1024;
  1017. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1018. sink.write(&image_data_[offset], send_size);
  1019. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1020. }
  1021. return true;
  1022. });
  1023. });
  1024. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1025. svr_.wait_until_ready();
  1026. }
  1027. virtual void TearDown() {
  1028. svr_.stop();
  1029. if (!request_threads_.empty()) {
  1030. std::this_thread::sleep_for(std::chrono::seconds(1));
  1031. for (auto &t : request_threads_) {
  1032. t.join();
  1033. }
  1034. }
  1035. t_.join();
  1036. }
  1037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1038. SSLClient cli_;
  1039. SSLServer svr_;
  1040. #else
  1041. Client cli_;
  1042. Server svr_;
  1043. #endif
  1044. thread t_;
  1045. std::vector<thread> request_threads_;
  1046. std::string image_data_;
  1047. };
  1048. TEST_F(ChunkedEncodingTest, NormalGet) {
  1049. auto res = cli_.Get("/chunked");
  1050. ASSERT_TRUE(res);
  1051. std::string out;
  1052. read_file("./image.jpg", out);
  1053. EXPECT_EQ(StatusCode::OK_200, res->status);
  1054. EXPECT_EQ(out, res->body);
  1055. }
  1056. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1057. std::string body;
  1058. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1059. body.append(data, data_length);
  1060. return true;
  1061. });
  1062. ASSERT_TRUE(res);
  1063. std::string out;
  1064. read_file("./image.jpg", out);
  1065. EXPECT_EQ(StatusCode::OK_200, res->status);
  1066. EXPECT_EQ(out, body);
  1067. }
  1068. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1069. std::string body;
  1070. auto res = cli_.Get(
  1071. "/chunked",
  1072. [&](const Response &response) {
  1073. EXPECT_EQ(StatusCode::OK_200, response.status);
  1074. return true;
  1075. },
  1076. [&](const char *data, size_t data_length) {
  1077. body.append(data, data_length);
  1078. return true;
  1079. });
  1080. ASSERT_TRUE(res);
  1081. std::string out;
  1082. read_file("./image.jpg", out);
  1083. EXPECT_EQ(StatusCode::OK_200, res->status);
  1084. EXPECT_EQ(out, body);
  1085. }
  1086. TEST(RangeTest, FromHTTPBin_Online) {
  1087. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1088. auto host = "httpbin.org";
  1089. auto path = std::string{"/range/32"};
  1090. #else
  1091. auto host = "nghttp2.org";
  1092. auto path = std::string{"/httpbin/range/32"};
  1093. #endif
  1094. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1095. auto port = 443;
  1096. SSLClient cli(host, port);
  1097. #else
  1098. auto port = 80;
  1099. Client cli(host, port);
  1100. #endif
  1101. cli.set_connection_timeout(5);
  1102. {
  1103. auto res = cli.Get(path);
  1104. ASSERT_TRUE(res);
  1105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1106. EXPECT_EQ(StatusCode::OK_200, res->status);
  1107. }
  1108. {
  1109. Headers headers = {make_range_header({{1, -1}})};
  1110. auto res = cli.Get(path, headers);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1114. }
  1115. {
  1116. Headers headers = {make_range_header({{1, 10}})};
  1117. auto res = cli.Get(path, headers);
  1118. ASSERT_TRUE(res);
  1119. EXPECT_EQ("bcdefghijk", res->body);
  1120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1121. }
  1122. {
  1123. Headers headers = {make_range_header({{0, 31}})};
  1124. auto res = cli.Get(path, headers);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1127. EXPECT_EQ(StatusCode::OK_200, res->status);
  1128. }
  1129. {
  1130. Headers headers = {make_range_header({{0, -1}})};
  1131. auto res = cli.Get(path, headers);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{0, 32}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1141. }
  1142. }
  1143. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1144. auto host = "unresolvableaddress.local";
  1145. auto path = std::string{"/"};
  1146. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1147. auto port = 443;
  1148. SSLClient cli(host, port);
  1149. #else
  1150. auto port = 80;
  1151. Client cli(host, port);
  1152. #endif
  1153. cli.set_connection_timeout(1);
  1154. {
  1155. auto res = cli.Get(path);
  1156. ASSERT_FALSE(res);
  1157. }
  1158. std::this_thread::sleep_for(std::chrono::seconds(8));
  1159. }
  1160. TEST(ConnectionErrorTest, InvalidHost) {
  1161. auto host = "-abcde.com";
  1162. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1163. auto port = 443;
  1164. SSLClient cli(host, port);
  1165. #else
  1166. auto port = 80;
  1167. Client cli(host, port);
  1168. #endif
  1169. cli.set_connection_timeout(std::chrono::seconds(2));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(!res);
  1172. EXPECT_EQ(Error::Connection, res.error());
  1173. }
  1174. TEST(ConnectionErrorTest, InvalidHost2) {
  1175. auto host = "httpbin.org/";
  1176. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1177. SSLClient cli(host);
  1178. #else
  1179. Client cli(host);
  1180. #endif
  1181. cli.set_connection_timeout(std::chrono::seconds(2));
  1182. auto res = cli.Get("/");
  1183. ASSERT_TRUE(!res);
  1184. EXPECT_EQ(Error::Connection, res.error());
  1185. }
  1186. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1187. auto host = "httpbin.org/";
  1188. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1189. SSLClient cli(host);
  1190. #else
  1191. Client cli(host);
  1192. #endif
  1193. cli.set_connection_timeout(std::chrono::seconds(2));
  1194. auto res = cli.Get("/");
  1195. ASSERT_TRUE(!res);
  1196. stringstream s;
  1197. s << "error code: " << res.error();
  1198. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1199. }
  1200. TEST(ConnectionErrorTest, InvalidPort) {
  1201. auto host = "localhost";
  1202. auto port = 44380;
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host, port);
  1205. #else
  1206. Client cli(host, port);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_TRUE(Error::Connection == res.error() ||
  1212. Error::ConnectionTimeout == res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, Timeout_Online) {
  1215. auto host = "google.com";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. auto port = 44380;
  1218. SSLClient cli(host, port);
  1219. #else
  1220. auto port = 8080;
  1221. Client cli(host, port);
  1222. #endif
  1223. cli.set_connection_timeout(std::chrono::seconds(2));
  1224. // only probe one address type so that the error reason
  1225. // correlates to the timed-out IPv4, not the unsupported
  1226. // IPv6 connection attempt
  1227. cli.set_address_family(AF_INET);
  1228. auto res = cli.Get("/");
  1229. ASSERT_TRUE(!res);
  1230. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1231. }
  1232. TEST(CancelTest, NoCancel_Online) {
  1233. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1234. auto host = "httpbin.org";
  1235. auto path = std::string{"/range/32"};
  1236. #else
  1237. auto host = "nghttp2.org";
  1238. auto path = std::string{"/httpbin/range/32"};
  1239. #endif
  1240. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1241. auto port = 443;
  1242. SSLClient cli(host, port);
  1243. #else
  1244. auto port = 80;
  1245. Client cli(host, port);
  1246. #endif
  1247. cli.set_connection_timeout(std::chrono::seconds(5));
  1248. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1249. ASSERT_TRUE(res);
  1250. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1251. EXPECT_EQ(StatusCode::OK_200, res->status);
  1252. }
  1253. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1254. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1255. auto host = "httpbin.org";
  1256. auto path = std::string{"/range/32"};
  1257. #else
  1258. auto host = "nghttp2.org";
  1259. auto path = std::string{"/httpbin/range/32"};
  1260. #endif
  1261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1262. auto port = 443;
  1263. SSLClient cli(host, port);
  1264. #else
  1265. auto port = 80;
  1266. Client cli(host, port);
  1267. #endif
  1268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1269. cli.set_connection_timeout(std::chrono::seconds(5));
  1270. ASSERT_TRUE(!res);
  1271. EXPECT_EQ(Error::Canceled, res.error());
  1272. }
  1273. TEST(CancelTest, WithCancelLargePayload_Online) {
  1274. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1275. auto host = "httpbin.org";
  1276. auto path = std::string{"/range/65536"};
  1277. #else
  1278. auto host = "nghttp2.org";
  1279. auto path = std::string{"/httpbin/range/65536"};
  1280. #endif
  1281. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1282. auto port = 443;
  1283. SSLClient cli(host, port);
  1284. #else
  1285. auto port = 80;
  1286. Client cli(host, port);
  1287. #endif
  1288. cli.set_connection_timeout(std::chrono::seconds(5));
  1289. uint32_t count = 0;
  1290. auto res =
  1291. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1292. ASSERT_TRUE(!res);
  1293. EXPECT_EQ(Error::Canceled, res.error());
  1294. }
  1295. TEST(CancelTest, NoCancelPost) {
  1296. Server svr;
  1297. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1298. res.set_content("Hello World!", "text/plain");
  1299. });
  1300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1301. auto se = detail::scope_exit([&] {
  1302. svr.stop();
  1303. thread.join();
  1304. ASSERT_FALSE(svr.is_running());
  1305. });
  1306. svr.wait_until_ready();
  1307. Client cli(HOST, PORT);
  1308. cli.set_connection_timeout(std::chrono::seconds(5));
  1309. auto res =
  1310. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1311. "application/json", [](uint64_t, uint64_t) { return true; });
  1312. ASSERT_TRUE(res);
  1313. EXPECT_EQ("Hello World!", res->body);
  1314. EXPECT_EQ(StatusCode::OK_200, res->status);
  1315. }
  1316. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1317. Server svr;
  1318. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1319. res.set_content("Hello World!", "text/plain");
  1320. });
  1321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1322. auto se = detail::scope_exit([&] {
  1323. svr.stop();
  1324. thread.join();
  1325. ASSERT_FALSE(svr.is_running());
  1326. });
  1327. svr.wait_until_ready();
  1328. Client cli(HOST, PORT);
  1329. cli.set_connection_timeout(std::chrono::seconds(5));
  1330. auto res =
  1331. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1332. "application/json", [](uint64_t, uint64_t) { return false; });
  1333. ASSERT_TRUE(!res);
  1334. EXPECT_EQ(Error::Canceled, res.error());
  1335. }
  1336. TEST(CancelTest, WithCancelLargePayloadPost) {
  1337. Server svr;
  1338. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1339. res.set_content(LARGE_DATA, "text/plain");
  1340. });
  1341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1342. auto se = detail::scope_exit([&] {
  1343. svr.stop();
  1344. thread.join();
  1345. ASSERT_FALSE(svr.is_running());
  1346. });
  1347. svr.wait_until_ready();
  1348. Client cli(HOST, PORT);
  1349. cli.set_connection_timeout(std::chrono::seconds(5));
  1350. auto res =
  1351. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1352. "application/json", [](uint64_t, uint64_t) { return false; });
  1353. ASSERT_TRUE(!res);
  1354. EXPECT_EQ(Error::Canceled, res.error());
  1355. }
  1356. TEST(CancelTest, NoCancelPut) {
  1357. Server svr;
  1358. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1359. res.set_content("Hello World!", "text/plain");
  1360. });
  1361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1362. auto se = detail::scope_exit([&] {
  1363. svr.stop();
  1364. thread.join();
  1365. ASSERT_FALSE(svr.is_running());
  1366. });
  1367. svr.wait_until_ready();
  1368. Client cli(HOST, PORT);
  1369. cli.set_connection_timeout(std::chrono::seconds(5));
  1370. auto res =
  1371. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1372. "application/json", [](uint64_t, uint64_t) { return true; });
  1373. ASSERT_TRUE(res);
  1374. EXPECT_EQ("Hello World!", res->body);
  1375. EXPECT_EQ(StatusCode::OK_200, res->status);
  1376. }
  1377. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1378. Server svr;
  1379. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1380. res.set_content("Hello World!", "text/plain");
  1381. });
  1382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1383. auto se = detail::scope_exit([&] {
  1384. svr.stop();
  1385. thread.join();
  1386. ASSERT_FALSE(svr.is_running());
  1387. });
  1388. svr.wait_until_ready();
  1389. Client cli(HOST, PORT);
  1390. cli.set_connection_timeout(std::chrono::seconds(5));
  1391. auto res =
  1392. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1393. "application/json", [](uint64_t, uint64_t) { return false; });
  1394. ASSERT_TRUE(!res);
  1395. EXPECT_EQ(Error::Canceled, res.error());
  1396. }
  1397. TEST(CancelTest, WithCancelLargePayloadPut) {
  1398. Server svr;
  1399. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1400. res.set_content(LARGE_DATA, "text/plain");
  1401. });
  1402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1403. auto se = detail::scope_exit([&] {
  1404. svr.stop();
  1405. thread.join();
  1406. ASSERT_FALSE(svr.is_running());
  1407. });
  1408. svr.wait_until_ready();
  1409. Client cli(HOST, PORT);
  1410. cli.set_connection_timeout(std::chrono::seconds(5));
  1411. auto res =
  1412. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1413. "application/json", [](uint64_t, uint64_t) { return false; });
  1414. ASSERT_TRUE(!res);
  1415. EXPECT_EQ(Error::Canceled, res.error());
  1416. }
  1417. TEST(CancelTest, NoCancelPatch) {
  1418. Server svr;
  1419. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1420. res.set_content("Hello World!", "text/plain");
  1421. });
  1422. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1423. auto se = detail::scope_exit([&] {
  1424. svr.stop();
  1425. thread.join();
  1426. ASSERT_FALSE(svr.is_running());
  1427. });
  1428. svr.wait_until_ready();
  1429. Client cli(HOST, PORT);
  1430. cli.set_connection_timeout(std::chrono::seconds(5));
  1431. auto res =
  1432. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1433. "application/json", [](uint64_t, uint64_t) { return true; });
  1434. ASSERT_TRUE(res);
  1435. EXPECT_EQ("Hello World!", res->body);
  1436. EXPECT_EQ(StatusCode::OK_200, res->status);
  1437. }
  1438. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1439. Server svr;
  1440. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1441. res.set_content("Hello World!", "text/plain");
  1442. });
  1443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. thread.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. Client cli(HOST, PORT);
  1451. cli.set_connection_timeout(std::chrono::seconds(5));
  1452. auto res =
  1453. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1454. "application/json", [](uint64_t, uint64_t) { return false; });
  1455. ASSERT_TRUE(!res);
  1456. EXPECT_EQ(Error::Canceled, res.error());
  1457. }
  1458. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1459. Server svr;
  1460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1461. res.set_content(LARGE_DATA, "text/plain");
  1462. });
  1463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1464. auto se = detail::scope_exit([&] {
  1465. svr.stop();
  1466. thread.join();
  1467. ASSERT_FALSE(svr.is_running());
  1468. });
  1469. svr.wait_until_ready();
  1470. Client cli(HOST, PORT);
  1471. cli.set_connection_timeout(std::chrono::seconds(5));
  1472. auto res =
  1473. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1474. "application/json", [](uint64_t, uint64_t) { return false; });
  1475. ASSERT_TRUE(!res);
  1476. EXPECT_EQ(Error::Canceled, res.error());
  1477. }
  1478. TEST(CancelTest, NoCancelDelete) {
  1479. Server svr;
  1480. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1481. res.set_content("Hello World!", "text/plain");
  1482. });
  1483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1484. auto se = detail::scope_exit([&] {
  1485. svr.stop();
  1486. thread.join();
  1487. ASSERT_FALSE(svr.is_running());
  1488. });
  1489. svr.wait_until_ready();
  1490. Client cli(HOST, PORT);
  1491. cli.set_connection_timeout(std::chrono::seconds(5));
  1492. auto res =
  1493. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1494. "application/json", [](uint64_t, uint64_t) { return true; });
  1495. ASSERT_TRUE(res);
  1496. EXPECT_EQ("Hello World!", res->body);
  1497. EXPECT_EQ(StatusCode::OK_200, res->status);
  1498. }
  1499. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1500. Server svr;
  1501. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1502. res.set_content("Hello World!", "text/plain");
  1503. });
  1504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1505. auto se = detail::scope_exit([&] {
  1506. svr.stop();
  1507. thread.join();
  1508. ASSERT_FALSE(svr.is_running());
  1509. });
  1510. svr.wait_until_ready();
  1511. Client cli(HOST, PORT);
  1512. cli.set_connection_timeout(std::chrono::seconds(5));
  1513. auto res =
  1514. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1515. "application/json", [](uint64_t, uint64_t) { return false; });
  1516. ASSERT_TRUE(!res);
  1517. EXPECT_EQ(Error::Canceled, res.error());
  1518. }
  1519. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1520. Server svr;
  1521. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1522. res.set_content(LARGE_DATA, "text/plain");
  1523. });
  1524. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1525. auto se = detail::scope_exit([&] {
  1526. svr.stop();
  1527. thread.join();
  1528. ASSERT_FALSE(svr.is_running());
  1529. });
  1530. svr.wait_until_ready();
  1531. Client cli(HOST, PORT);
  1532. cli.set_connection_timeout(std::chrono::seconds(5));
  1533. auto res =
  1534. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1535. "application/json", [](uint64_t, uint64_t) { return false; });
  1536. ASSERT_TRUE(!res);
  1537. EXPECT_EQ(Error::Canceled, res.error());
  1538. }
  1539. static std::string remove_whitespace(const std::string &input) {
  1540. std::string output;
  1541. output.reserve(input.size());
  1542. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1543. [](unsigned char c) { return !std::isspace(c); });
  1544. return output;
  1545. }
  1546. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1547. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1548. auto host = "httpbin.org";
  1549. auto path = std::string{"/basic-auth/hello/world"};
  1550. #else
  1551. auto host = "nghttp2.org";
  1552. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1553. #endif
  1554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1555. auto port = 443;
  1556. SSLClient cli(host, port);
  1557. #else
  1558. auto port = 80;
  1559. Client cli(host, port);
  1560. #endif
  1561. {
  1562. auto res = cli.Get(path);
  1563. ASSERT_TRUE(res);
  1564. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1565. }
  1566. {
  1567. auto res =
  1568. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1569. ASSERT_TRUE(res);
  1570. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1571. remove_whitespace(res->body));
  1572. EXPECT_EQ(StatusCode::OK_200, res->status);
  1573. }
  1574. {
  1575. cli.set_basic_auth("hello", "world");
  1576. auto res = cli.Get(path);
  1577. ASSERT_TRUE(res);
  1578. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1579. remove_whitespace(res->body));
  1580. EXPECT_EQ(StatusCode::OK_200, res->status);
  1581. }
  1582. {
  1583. cli.set_basic_auth("hello", "bad");
  1584. auto res = cli.Get(path);
  1585. ASSERT_TRUE(res);
  1586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1587. }
  1588. {
  1589. cli.set_basic_auth("bad", "world");
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. }
  1595. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1597. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1598. auto host = "httpbin.org";
  1599. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1600. auto paths = std::vector<std::string>{
  1601. "/digest-auth/auth/hello/world/MD5",
  1602. "/digest-auth/auth/hello/world/SHA-256",
  1603. "/digest-auth/auth/hello/world/SHA-512",
  1604. "/digest-auth/auth-int/hello/world/MD5",
  1605. };
  1606. #else
  1607. auto host = "nghttp2.org";
  1608. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1609. auto paths = std::vector<std::string>{
  1610. "/httpbin/digest-auth/auth/hello/world/MD5",
  1611. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1612. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1613. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1614. };
  1615. #endif
  1616. auto port = 443;
  1617. SSLClient cli(host, port);
  1618. {
  1619. auto res = cli.Get(unauth_path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_digest_auth("hello", "world");
  1625. for (const auto &path : paths) {
  1626. auto res = cli.Get(path.c_str());
  1627. ASSERT_TRUE(res);
  1628. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1629. remove_whitespace(res->body));
  1630. EXPECT_EQ(StatusCode::OK_200, res->status);
  1631. }
  1632. cli.set_digest_auth("hello", "bad");
  1633. for (const auto &path : paths) {
  1634. auto res = cli.Get(path.c_str());
  1635. ASSERT_TRUE(res);
  1636. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1637. }
  1638. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1639. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1640. // cli.set_digest_auth("bad", "world");
  1641. // for (const auto& path : paths) {
  1642. // auto res = cli.Get(path.c_str());
  1643. // ASSERT_TRUE(res);
  1644. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1645. // }
  1646. }
  1647. }
  1648. #endif
  1649. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1650. auto host = "google.com";
  1651. auto another_host = "example.com";
  1652. auto wrong_ip = "0.0.0.0";
  1653. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1654. SSLClient cli(host);
  1655. #else
  1656. Client cli(host);
  1657. #endif
  1658. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1659. auto res = cli.Get("/");
  1660. ASSERT_TRUE(res);
  1661. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1662. }
  1663. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1664. auto host = "google.com";
  1665. auto wrong_ip = "0.0.0.0";
  1666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1667. SSLClient cli(host);
  1668. #else
  1669. Client cli(host);
  1670. #endif
  1671. cli.set_hostname_addr_map({{host, wrong_ip}});
  1672. auto res = cli.Get("/");
  1673. ASSERT_TRUE(!res);
  1674. EXPECT_EQ(Error::Connection, res.error());
  1675. }
  1676. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1677. auto host = "nghttp2.org";
  1678. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1679. SSLClient cli(host);
  1680. #else
  1681. Client cli(host);
  1682. #endif
  1683. cli.set_follow_location(true);
  1684. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1685. ASSERT_TRUE(res);
  1686. EXPECT_EQ(StatusCode::OK_200, res->status);
  1687. }
  1688. TEST(RedirectTest, Redirect_Online) {
  1689. auto host = "nghttp2.org";
  1690. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1691. SSLClient cli(host);
  1692. #else
  1693. Client cli(host);
  1694. #endif
  1695. cli.set_follow_location(true);
  1696. auto res = cli.Get("/httpbin/redirect/3");
  1697. ASSERT_TRUE(res);
  1698. EXPECT_EQ(StatusCode::OK_200, res->status);
  1699. }
  1700. TEST(RelativeRedirectTest, Redirect_Online) {
  1701. auto host = "nghttp2.org";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_follow_location(true);
  1708. auto res = cli.Get("/httpbin/relative-redirect/3");
  1709. ASSERT_TRUE(res);
  1710. EXPECT_EQ(StatusCode::OK_200, res->status);
  1711. }
  1712. TEST(TooManyRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/redirect/21");
  1721. ASSERT_TRUE(!res);
  1722. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1723. }
  1724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1725. TEST(YahooRedirectTest, Redirect_Online) {
  1726. Client cli("yahoo.com");
  1727. auto res = cli.Get("/");
  1728. ASSERT_TRUE(res);
  1729. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1730. cli.set_follow_location(true);
  1731. res = cli.Get("/");
  1732. ASSERT_TRUE(res);
  1733. EXPECT_EQ(StatusCode::OK_200, res->status);
  1734. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1735. }
  1736. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1737. #define REDIR_HOST "httpbingo.org"
  1738. #define REDIR_PATH "/redirect-to"
  1739. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1740. SSLClient cli(REDIR_HOST);
  1741. cli.set_follow_location(true);
  1742. auto res =
  1743. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1744. ASSERT_TRUE(res);
  1745. EXPECT_EQ(StatusCode::OK_200, res->status);
  1746. }
  1747. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1748. SSLClient cli(REDIR_HOST);
  1749. cli.set_follow_location(true);
  1750. Params params;
  1751. params.emplace("url", "http://example.com");
  1752. params.emplace("status_code", "302");
  1753. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1754. ASSERT_TRUE(res);
  1755. EXPECT_EQ(StatusCode::OK_200, res->status);
  1756. }
  1757. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1758. SSLClient cli(REDIR_HOST);
  1759. cli.set_follow_location(true);
  1760. Params params;
  1761. params.emplace("url", "http://example.com");
  1762. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1763. ASSERT_TRUE(res);
  1764. EXPECT_EQ(StatusCode::OK_200, res->status);
  1765. }
  1766. TEST(UrlWithSpace, Redirect_Online) {
  1767. SSLClient cli("edge.forgecdn.net");
  1768. cli.set_follow_location(true);
  1769. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1770. ASSERT_TRUE(res);
  1771. EXPECT_EQ(StatusCode::OK_200, res->status);
  1772. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1773. }
  1774. #endif
  1775. #if !defined(_WIN32) && !defined(_WIN64)
  1776. TEST(ReceiveSignals, Signal) {
  1777. auto setupSignalHandlers = []() {
  1778. struct sigaction act;
  1779. sigemptyset(&act.sa_mask);
  1780. act.sa_flags = SA_SIGINFO;
  1781. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1782. switch (sig) {
  1783. case SIGINT:
  1784. default: break;
  1785. }
  1786. };
  1787. ::sigaction(SIGINT, &act, nullptr);
  1788. };
  1789. Server svr;
  1790. int port = 0;
  1791. auto thread = std::thread([&]() {
  1792. setupSignalHandlers();
  1793. port = svr.bind_to_any_port("localhost");
  1794. svr.listen_after_bind();
  1795. });
  1796. auto se = detail::scope_exit([&] {
  1797. svr.stop();
  1798. thread.join();
  1799. ASSERT_FALSE(svr.is_running());
  1800. });
  1801. svr.wait_until_ready();
  1802. ASSERT_TRUE(svr.is_running());
  1803. pthread_kill(thread.native_handle(), SIGINT);
  1804. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1805. ASSERT_TRUE(svr.is_running());
  1806. }
  1807. #endif
  1808. TEST(RedirectToDifferentPort, Redirect) {
  1809. Server svr1;
  1810. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1811. res.set_content("Hello World!", "text/plain");
  1812. });
  1813. int svr1_port = 0;
  1814. auto thread1 = std::thread([&]() {
  1815. svr1_port = svr1.bind_to_any_port("localhost");
  1816. svr1.listen_after_bind();
  1817. });
  1818. Server svr2;
  1819. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1820. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1821. });
  1822. int svr2_port = 0;
  1823. auto thread2 = std::thread([&]() {
  1824. svr2_port = svr2.bind_to_any_port("localhost");
  1825. svr2.listen_after_bind();
  1826. });
  1827. auto se = detail::scope_exit([&] {
  1828. svr2.stop();
  1829. thread2.join();
  1830. svr1.stop();
  1831. thread1.join();
  1832. ASSERT_FALSE(svr2.is_running());
  1833. ASSERT_FALSE(svr1.is_running());
  1834. });
  1835. svr1.wait_until_ready();
  1836. svr2.wait_until_ready();
  1837. Client cli("localhost", svr2_port);
  1838. cli.set_follow_location(true);
  1839. auto res = cli.Get("/2");
  1840. ASSERT_TRUE(res);
  1841. EXPECT_EQ(StatusCode::OK_200, res->status);
  1842. EXPECT_EQ("Hello World!", res->body);
  1843. }
  1844. TEST(RedirectFromPageWithContent, Redirect) {
  1845. Server svr;
  1846. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("___", "text/plain");
  1848. res.set_redirect("/2");
  1849. });
  1850. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1854. auto se = detail::scope_exit([&] {
  1855. svr.stop();
  1856. th.join();
  1857. ASSERT_FALSE(svr.is_running());
  1858. });
  1859. svr.wait_until_ready();
  1860. {
  1861. Client cli("localhost", PORT);
  1862. cli.set_follow_location(true);
  1863. std::string body;
  1864. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1865. body.append(data, data_length);
  1866. return true;
  1867. });
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", body);
  1871. }
  1872. {
  1873. Client cli("localhost", PORT);
  1874. std::string body;
  1875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1876. body.append(data, data_length);
  1877. return true;
  1878. });
  1879. ASSERT_TRUE(res);
  1880. EXPECT_EQ(StatusCode::Found_302, res->status);
  1881. EXPECT_EQ("___", body);
  1882. }
  1883. }
  1884. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1885. Server svr;
  1886. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("___", "text/plain");
  1888. // res.set_redirect("/2");
  1889. res.set_redirect("http://[::1]:1234/2");
  1890. });
  1891. svr.Get("/2", [&](const Request &req, Response &res) {
  1892. auto host_header = req.headers.find("Host");
  1893. ASSERT_TRUE(host_header != req.headers.end());
  1894. EXPECT_EQ("[::1]:1234", host_header->second);
  1895. res.set_content("Hello World!", "text/plain");
  1896. });
  1897. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1898. auto se = detail::scope_exit([&] {
  1899. svr.stop();
  1900. th.join();
  1901. ASSERT_FALSE(svr.is_running());
  1902. });
  1903. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1904. // actually starts anything, so the condition !svr.is_running() will
  1905. // always remain true, and the loop never stops.
  1906. // This basically counts how many milliseconds have passed since the
  1907. // call to svr.listen(), and if after 5 seconds nothing started yet
  1908. // aborts the test.
  1909. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1910. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1911. ASSERT_LT(milliseconds, 5000U);
  1912. }
  1913. {
  1914. Client cli("http://[::1]:1234");
  1915. cli.set_follow_location(true);
  1916. std::string body;
  1917. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1918. body.append(data, data_length);
  1919. return true;
  1920. });
  1921. ASSERT_TRUE(res);
  1922. EXPECT_EQ(StatusCode::OK_200, res->status);
  1923. EXPECT_EQ("Hello World!", body);
  1924. }
  1925. {
  1926. Client cli("http://[::1]:1234");
  1927. std::string body;
  1928. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1929. body.append(data, data_length);
  1930. return true;
  1931. });
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(StatusCode::Found_302, res->status);
  1934. EXPECT_EQ("___", body);
  1935. }
  1936. }
  1937. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1938. Server svr;
  1939. svr.Get("/foo", [](const Request &req, Response &res) {
  1940. auto a = req.params.find("a");
  1941. if (a != req.params.end()) {
  1942. res.set_content((*a).second, "text/plain");
  1943. res.status = StatusCode::OK_200;
  1944. } else {
  1945. res.status = StatusCode::BadRequest_400;
  1946. }
  1947. });
  1948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1949. auto se = detail::scope_exit([&] {
  1950. svr.stop();
  1951. thread.join();
  1952. ASSERT_FALSE(svr.is_running());
  1953. });
  1954. svr.wait_until_ready();
  1955. {
  1956. Client cli(HOST, PORT);
  1957. cli.set_path_encode(false);
  1958. auto res = cli.Get("/foo?a=explicitly+encoded");
  1959. ASSERT_TRUE(res);
  1960. EXPECT_EQ(StatusCode::OK_200, res->status);
  1961. // This expects it back with a space, as the `+` won't have been
  1962. // url-encoded, and server-side the params get decoded turning `+`
  1963. // into spaces.
  1964. EXPECT_EQ("explicitly encoded", res->body);
  1965. }
  1966. }
  1967. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1968. Server svr;
  1969. svr.Get("/", [](const Request &req, Response &) {
  1970. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1971. });
  1972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1973. auto se = detail::scope_exit([&] {
  1974. svr.stop();
  1975. thread.join();
  1976. ASSERT_FALSE(svr.is_running());
  1977. });
  1978. svr.wait_until_ready();
  1979. {
  1980. Client cli(HOST, PORT);
  1981. cli.set_path_encode(false);
  1982. auto res = cli.Get("/?something=%0A");
  1983. ASSERT_TRUE(res);
  1984. EXPECT_EQ(StatusCode::OK_200, res->status);
  1985. }
  1986. }
  1987. TEST(BindServerTest, DISABLED_BindDualStack) {
  1988. Server svr;
  1989. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1990. res.set_content("Hello World!", "text/plain");
  1991. });
  1992. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1993. auto se = detail::scope_exit([&] {
  1994. svr.stop();
  1995. thread.join();
  1996. ASSERT_FALSE(svr.is_running());
  1997. });
  1998. svr.wait_until_ready();
  1999. {
  2000. Client cli("127.0.0.1", PORT);
  2001. auto res = cli.Get("/1");
  2002. ASSERT_TRUE(res);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ("Hello World!", res->body);
  2005. }
  2006. {
  2007. Client cli("::1", PORT);
  2008. auto res = cli.Get("/1");
  2009. ASSERT_TRUE(res);
  2010. EXPECT_EQ(StatusCode::OK_200, res->status);
  2011. EXPECT_EQ("Hello World!", res->body);
  2012. }
  2013. }
  2014. TEST(BindServerTest, BindAndListenSeparately) {
  2015. Server svr;
  2016. int port = svr.bind_to_any_port("0.0.0.0");
  2017. ASSERT_TRUE(svr.is_valid());
  2018. ASSERT_TRUE(port > 0);
  2019. svr.stop();
  2020. }
  2021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2022. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2024. CLIENT_CA_CERT_DIR);
  2025. int port = svr.bind_to_any_port("0.0.0.0");
  2026. ASSERT_TRUE(svr.is_valid());
  2027. ASSERT_TRUE(port > 0);
  2028. svr.stop();
  2029. }
  2030. #endif
  2031. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2032. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2033. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2034. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2035. int port = svr.bind_to_any_port("0.0.0.0");
  2036. ASSERT_TRUE(svr.is_valid());
  2037. ASSERT_TRUE(port > 0);
  2038. svr.stop();
  2039. }
  2040. #endif
  2041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2042. X509 *readCertificate(const std::string &strFileName) {
  2043. std::ifstream inStream(strFileName);
  2044. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2045. std::istreambuf_iterator<char>());
  2046. if (strCertPEM.empty()) return (nullptr);
  2047. BIO *pbCert = BIO_new(BIO_s_mem());
  2048. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2049. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2050. BIO_free(pbCert);
  2051. return (pCert);
  2052. }
  2053. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2054. std::ifstream inStream(strFileName);
  2055. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2056. std::istreambuf_iterator<char>());
  2057. if (strPrivateKeyPEM.empty()) return (nullptr);
  2058. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2059. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2060. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2061. BIO_free(pbPrivKey);
  2062. return (pPrivateKey);
  2063. }
  2064. TEST(BindServerTest, UpdateCerts) {
  2065. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2066. int port = svr.bind_to_any_port("0.0.0.0");
  2067. ASSERT_TRUE(svr.is_valid());
  2068. ASSERT_TRUE(port > 0);
  2069. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2070. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2071. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2072. ASSERT_TRUE(cert != nullptr);
  2073. ASSERT_TRUE(ca_cert != nullptr);
  2074. ASSERT_TRUE(key != nullptr);
  2075. X509_STORE *cert_store = X509_STORE_new();
  2076. X509_STORE_add_cert(cert_store, ca_cert);
  2077. svr.update_certs(cert, key, cert_store);
  2078. ASSERT_TRUE(svr.is_valid());
  2079. svr.stop();
  2080. X509_free(cert);
  2081. X509_free(ca_cert);
  2082. EVP_PKEY_free(key);
  2083. }
  2084. #endif
  2085. TEST(ErrorHandlerTest, ContentLength) {
  2086. Server svr;
  2087. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2088. res.status = StatusCode::OK_200;
  2089. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2090. "text/html"); // <= Content-Length still 13
  2091. });
  2092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2093. res.set_content("Hello World!\n", "text/plain");
  2094. res.status = 524;
  2095. });
  2096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2097. auto se = detail::scope_exit([&] {
  2098. svr.stop();
  2099. thread.join();
  2100. ASSERT_FALSE(svr.is_running());
  2101. });
  2102. svr.wait_until_ready();
  2103. {
  2104. Client cli(HOST, PORT);
  2105. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2106. ASSERT_TRUE(res);
  2107. EXPECT_EQ(StatusCode::OK_200, res->status);
  2108. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2109. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2110. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2111. }
  2112. }
  2113. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2114. TEST(ExceptionTest, WithoutExceptionHandler) {
  2115. Server svr;
  2116. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2117. throw std::runtime_error("exception...");
  2118. });
  2119. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2120. throw std::runtime_error("exception\r\n...");
  2121. });
  2122. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2123. auto se = detail::scope_exit([&] {
  2124. svr.stop();
  2125. listen_thread.join();
  2126. ASSERT_FALSE(svr.is_running());
  2127. });
  2128. svr.wait_until_ready();
  2129. Client cli("localhost", PORT);
  2130. {
  2131. auto res = cli.Get("/exception");
  2132. ASSERT_TRUE(res);
  2133. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2134. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2135. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2136. }
  2137. {
  2138. auto res = cli.Get("/unknown");
  2139. ASSERT_TRUE(res);
  2140. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2141. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2142. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2143. }
  2144. }
  2145. TEST(ExceptionTest, WithExceptionHandler) {
  2146. Server svr;
  2147. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2148. std::exception_ptr ep) {
  2149. EXPECT_FALSE(ep == nullptr);
  2150. try {
  2151. std::rethrow_exception(ep);
  2152. } catch (std::exception &e) {
  2153. EXPECT_EQ("abc", std::string(e.what()));
  2154. } catch (...) {}
  2155. res.status = StatusCode::InternalServerError_500;
  2156. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2157. "text/html"); // <= Content-Length still 13 at this point
  2158. });
  2159. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2160. res.set_content("Hello World!\n", "text/plain");
  2161. throw std::runtime_error("abc");
  2162. });
  2163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2164. auto se = detail::scope_exit([&] {
  2165. svr.stop();
  2166. thread.join();
  2167. ASSERT_FALSE(svr.is_running());
  2168. });
  2169. svr.wait_until_ready();
  2170. for (size_t i = 0; i < 10; i++) {
  2171. Client cli(HOST, PORT);
  2172. for (size_t j = 0; j < 100; j++) {
  2173. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2174. ASSERT_TRUE(res);
  2175. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2176. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2177. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2178. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2179. }
  2180. cli.set_keep_alive(true);
  2181. for (size_t j = 0; j < 100; j++) {
  2182. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2183. ASSERT_TRUE(res);
  2184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2186. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2187. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2188. }
  2189. }
  2190. }
  2191. TEST(ExceptionTest, AndErrorHandler) {
  2192. Server svr;
  2193. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2194. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2195. });
  2196. svr.set_exception_handler(
  2197. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2198. EXPECT_FALSE(ep == nullptr);
  2199. try {
  2200. std::rethrow_exception(ep);
  2201. } catch (std::exception &e) {
  2202. res.set_content(e.what(), "text/html");
  2203. } catch (...) {}
  2204. res.status = StatusCode::InternalServerError_500;
  2205. });
  2206. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2207. throw std::runtime_error("EXCEPTION");
  2208. });
  2209. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2210. res.set_content("ERROR", "text/html");
  2211. res.status = StatusCode::InternalServerError_500;
  2212. });
  2213. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2214. auto se = detail::scope_exit([&] {
  2215. svr.stop();
  2216. thread.join();
  2217. ASSERT_FALSE(svr.is_running());
  2218. });
  2219. svr.wait_until_ready();
  2220. Client cli(HOST, PORT);
  2221. {
  2222. auto res = cli.Get("/exception");
  2223. ASSERT_TRUE(res);
  2224. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2225. EXPECT_EQ("EXCEPTION", res->body);
  2226. }
  2227. {
  2228. auto res = cli.Get("/error");
  2229. ASSERT_TRUE(res);
  2230. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2231. EXPECT_EQ("ERROR", res->body);
  2232. }
  2233. {
  2234. auto res = cli.Get("/invalid");
  2235. ASSERT_TRUE(res);
  2236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2237. EXPECT_EQ("NOT_FOUND", res->body);
  2238. }
  2239. }
  2240. #endif
  2241. TEST(NoContentTest, ContentLength) {
  2242. Server svr;
  2243. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2244. res.status = StatusCode::NoContent_204;
  2245. });
  2246. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2247. auto se = detail::scope_exit([&] {
  2248. svr.stop();
  2249. thread.join();
  2250. ASSERT_FALSE(svr.is_running());
  2251. });
  2252. svr.wait_until_ready();
  2253. {
  2254. Client cli(HOST, PORT);
  2255. auto res = cli.Get("/hi");
  2256. ASSERT_TRUE(res);
  2257. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2258. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2259. }
  2260. }
  2261. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2264. ASSERT_TRUE(svr.is_valid());
  2265. #else
  2266. Server svr;
  2267. #endif
  2268. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2269. if (req.path == "/routing_handler") {
  2270. res.set_header("PRE_ROUTING", "on");
  2271. res.set_content("Routing Handler", "text/plain");
  2272. return httplib::Server::HandlerResponse::Handled;
  2273. }
  2274. return httplib::Server::HandlerResponse::Unhandled;
  2275. });
  2276. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2277. res.set_content("Error", "text/html");
  2278. });
  2279. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2280. if (req.path == "/routing_handler") {
  2281. res.set_header("POST_ROUTING", "on");
  2282. }
  2283. });
  2284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!\n", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. {
  2295. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2296. SSLClient cli(HOST, PORT);
  2297. cli.enable_server_certificate_verification(false);
  2298. #else
  2299. Client cli(HOST, PORT);
  2300. #endif
  2301. auto res = cli.Get("/routing_handler");
  2302. ASSERT_TRUE(res);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ("Routing Handler", res->body);
  2305. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2306. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2307. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2308. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2309. }
  2310. {
  2311. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2312. SSLClient cli(HOST, PORT);
  2313. cli.enable_server_certificate_verification(false);
  2314. #else
  2315. Client cli(HOST, PORT);
  2316. #endif
  2317. auto res = cli.Get("/hi");
  2318. ASSERT_TRUE(res);
  2319. EXPECT_EQ(StatusCode::OK_200, res->status);
  2320. EXPECT_EQ("Hello World!\n", res->body);
  2321. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2322. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2323. }
  2324. {
  2325. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2326. SSLClient cli(HOST, PORT);
  2327. cli.enable_server_certificate_verification(false);
  2328. #else
  2329. Client cli(HOST, PORT);
  2330. #endif
  2331. auto res = cli.Get("/aaa");
  2332. ASSERT_TRUE(res);
  2333. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2334. EXPECT_EQ("Error", res->body);
  2335. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2336. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2337. }
  2338. }
  2339. TEST(RequestHandlerTest, PreRequestHandler) {
  2340. auto route_path = "/user/:user";
  2341. Server svr;
  2342. svr.Get("/hi", [](const Request &, Response &res) {
  2343. res.set_content("hi", "text/plain");
  2344. });
  2345. svr.Get(route_path, [](const Request &req, Response &res) {
  2346. res.set_content(req.path_params.at("user"), "text/plain");
  2347. });
  2348. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2349. if (req.matched_route == route_path) {
  2350. auto user = req.path_params.at("user");
  2351. if (user != "john") {
  2352. res.status = StatusCode::Forbidden_403;
  2353. res.set_content("error", "text/html");
  2354. return Server::HandlerResponse::Handled;
  2355. }
  2356. }
  2357. return Server::HandlerResponse::Unhandled;
  2358. });
  2359. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2360. auto se = detail::scope_exit([&] {
  2361. svr.stop();
  2362. thread.join();
  2363. ASSERT_FALSE(svr.is_running());
  2364. });
  2365. svr.wait_until_ready();
  2366. Client cli(HOST, PORT);
  2367. {
  2368. auto res = cli.Get("/hi");
  2369. ASSERT_TRUE(res);
  2370. EXPECT_EQ(StatusCode::OK_200, res->status);
  2371. EXPECT_EQ("hi", res->body);
  2372. }
  2373. {
  2374. auto res = cli.Get("/user/john");
  2375. ASSERT_TRUE(res);
  2376. EXPECT_EQ(StatusCode::OK_200, res->status);
  2377. EXPECT_EQ("john", res->body);
  2378. }
  2379. {
  2380. auto res = cli.Get("/user/invalid-user");
  2381. ASSERT_TRUE(res);
  2382. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2383. EXPECT_EQ("error", res->body);
  2384. }
  2385. }
  2386. TEST(InvalidFormatTest, StatusCode) {
  2387. Server svr;
  2388. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2389. res.set_content("Hello World!\n", "text/plain");
  2390. res.status = 9999; // Status should be a three-digit code...
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. {
  2400. Client cli(HOST, PORT);
  2401. auto res = cli.Get("/hi");
  2402. ASSERT_FALSE(res);
  2403. }
  2404. }
  2405. TEST(URLFragmentTest, WithFragment) {
  2406. Server svr;
  2407. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2408. EXPECT_TRUE(req.target == "/hi");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. {
  2418. Client cli(HOST, PORT);
  2419. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2420. EXPECT_TRUE(res);
  2421. EXPECT_EQ(StatusCode::OK_200, res->status);
  2422. res = cli.Get("/hi%23key1=val1=key2=val2");
  2423. EXPECT_TRUE(res);
  2424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2425. }
  2426. }
  2427. TEST(HeaderWriter, SetHeaderWriter) {
  2428. Server svr;
  2429. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2430. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2431. return detail::write_headers(strm, hdrs);
  2432. });
  2433. svr.Get("/hi", [](const Request &req, Response &res) {
  2434. auto it = req.headers.find("CustomClientHeader");
  2435. EXPECT_TRUE(it != req.headers.end());
  2436. EXPECT_EQ(it->second, "CustomClientValue");
  2437. res.set_content("Hello World!\n", "text/plain");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2449. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2450. return detail::write_headers(strm, hdrs);
  2451. });
  2452. auto res = cli.Get("/hi");
  2453. EXPECT_TRUE(res);
  2454. EXPECT_EQ(StatusCode::OK_200, res->status);
  2455. auto it = res->headers.find("CustomServerHeader");
  2456. EXPECT_TRUE(it != res->headers.end());
  2457. EXPECT_EQ(it->second, "CustomServerValue");
  2458. }
  2459. }
  2460. class ServerTest : public ::testing::Test {
  2461. protected:
  2462. ServerTest()
  2463. : cli_(HOST, PORT)
  2464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2465. ,
  2466. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2467. #endif
  2468. {
  2469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2470. cli_.enable_server_certificate_verification(false);
  2471. #endif
  2472. }
  2473. virtual void SetUp() {
  2474. svr_.set_mount_point("/", "./www");
  2475. svr_.set_mount_point("/mount", "./www2");
  2476. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2477. svr_.Get("/hi",
  2478. [&](const Request & /*req*/, Response &res) {
  2479. res.set_content("Hello World!", "text/plain");
  2480. })
  2481. .Get("/file_content",
  2482. [&](const Request & /*req*/, Response &res) {
  2483. res.set_file_content("./www/dir/test.html");
  2484. })
  2485. .Get("/file_content_with_content_type",
  2486. [&](const Request & /*req*/, Response &res) {
  2487. res.set_file_content("./www/file", "text/plain");
  2488. })
  2489. .Get("/invalid_file_content",
  2490. [&](const Request & /*req*/, Response &res) {
  2491. res.set_file_content("./www/dir/invalid_file_path");
  2492. })
  2493. .Get("/http_response_splitting",
  2494. [&](const Request & /*req*/, Response &res) {
  2495. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2496. EXPECT_EQ(0U, res.headers.size());
  2497. EXPECT_FALSE(res.has_header("a"));
  2498. res.set_header("a", "1\nSet-Cookie: a=1");
  2499. EXPECT_EQ(0U, res.headers.size());
  2500. EXPECT_FALSE(res.has_header("a"));
  2501. res.set_header("a", "1\rSet-Cookie: a=1");
  2502. EXPECT_EQ(0U, res.headers.size());
  2503. EXPECT_FALSE(res.has_header("a"));
  2504. res.set_header("a\r\nb", "0");
  2505. EXPECT_EQ(0U, res.headers.size());
  2506. EXPECT_FALSE(res.has_header("a"));
  2507. res.set_header("a\rb", "0");
  2508. EXPECT_EQ(0U, res.headers.size());
  2509. EXPECT_FALSE(res.has_header("a"));
  2510. res.set_header("a\nb", "0");
  2511. EXPECT_EQ(0U, res.headers.size());
  2512. EXPECT_FALSE(res.has_header("a"));
  2513. res.set_redirect("1\r\nSet-Cookie: a=1");
  2514. EXPECT_EQ(0U, res.headers.size());
  2515. EXPECT_FALSE(res.has_header("Location"));
  2516. })
  2517. .Get("/slow",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. std::this_thread::sleep_for(std::chrono::seconds(2));
  2520. res.set_content("slow", "text/plain");
  2521. })
  2522. #if 0
  2523. .Post("/slowpost",
  2524. [&](const Request & /*req*/, Response &res) {
  2525. std::this_thread::sleep_for(std::chrono::seconds(2));
  2526. res.set_content("slow", "text/plain");
  2527. })
  2528. #endif
  2529. .Get("/remote_addr",
  2530. [&](const Request &req, Response &res) {
  2531. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2532. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2533. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2534. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2535. res.set_content(req.remote_addr, "text/plain");
  2536. })
  2537. .Get("/local_addr",
  2538. [&](const Request &req, Response &res) {
  2539. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2540. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2541. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2542. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2543. auto local_addr = req.local_addr;
  2544. auto local_port = std::to_string(req.local_port);
  2545. res.set_content(local_addr.append(":").append(local_port),
  2546. "text/plain");
  2547. })
  2548. .Get("/endwith%",
  2549. [&](const Request & /*req*/, Response &res) {
  2550. res.set_content("Hello World!", "text/plain");
  2551. })
  2552. .Get("/a\\+\\+b",
  2553. [&](const Request &req, Response &res) {
  2554. ASSERT_TRUE(req.has_param("a +b"));
  2555. auto val = req.get_param_value("a +b");
  2556. res.set_content(val, "text/plain");
  2557. })
  2558. .Get("/", [&](const Request & /*req*/,
  2559. Response &res) { res.set_redirect("/hi"); })
  2560. .Post("/1",
  2561. [](const Request & /*req*/, Response &res) {
  2562. res.set_redirect("/2", StatusCode::SeeOther_303);
  2563. })
  2564. .Get("/2",
  2565. [](const Request & /*req*/, Response &res) {
  2566. res.set_content("redirected.", "text/plain");
  2567. res.status = StatusCode::OK_200;
  2568. })
  2569. .Post("/person",
  2570. [&](const Request &req, Response &res) {
  2571. if (req.has_param("name") && req.has_param("note")) {
  2572. persons_[req.get_param_value("name")] =
  2573. req.get_param_value("note");
  2574. } else {
  2575. res.status = StatusCode::BadRequest_400;
  2576. }
  2577. })
  2578. .Put("/person",
  2579. [&](const Request &req, Response &res) {
  2580. if (req.has_param("name") && req.has_param("note")) {
  2581. persons_[req.get_param_value("name")] =
  2582. req.get_param_value("note");
  2583. } else {
  2584. res.status = StatusCode::BadRequest_400;
  2585. }
  2586. })
  2587. .Get("/person/(.*)",
  2588. [&](const Request &req, Response &res) {
  2589. string name = req.matches[1];
  2590. if (persons_.find(name) != persons_.end()) {
  2591. auto note = persons_[name];
  2592. res.set_content(note, "text/plain");
  2593. } else {
  2594. res.status = StatusCode::NotFound_404;
  2595. }
  2596. })
  2597. .Delete("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name")) {
  2600. string name = req.get_param_value("name");
  2601. if (persons_.find(name) != persons_.end()) {
  2602. persons_.erase(name);
  2603. res.set_content("DELETED", "text/plain");
  2604. } else {
  2605. res.status = StatusCode::NotFound_404;
  2606. }
  2607. } else {
  2608. res.status = StatusCode::BadRequest_400;
  2609. }
  2610. })
  2611. .Post("/x-www-form-urlencoded-json",
  2612. [&](const Request &req, Response &res) {
  2613. auto json = req.get_param_value("json");
  2614. ASSERT_EQ(JSON_DATA, json);
  2615. res.set_content(json, "appliation/json");
  2616. res.status = StatusCode::OK_200;
  2617. })
  2618. .Get("/streamed-chunked",
  2619. [&](const Request & /*req*/, Response &res) {
  2620. res.set_chunked_content_provider(
  2621. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2622. sink.os << "123";
  2623. sink.os << "456";
  2624. sink.os << "789";
  2625. sink.done();
  2626. return true;
  2627. });
  2628. })
  2629. .Get("/streamed-chunked2",
  2630. [&](const Request & /*req*/, Response &res) {
  2631. auto i = new int(0);
  2632. res.set_chunked_content_provider(
  2633. "text/plain",
  2634. [i](size_t /*offset*/, DataSink &sink) {
  2635. switch (*i) {
  2636. case 0: sink.os << "123"; break;
  2637. case 1: sink.os << "456"; break;
  2638. case 2: sink.os << "789"; break;
  2639. case 3: sink.done(); break;
  2640. }
  2641. (*i)++;
  2642. return true;
  2643. },
  2644. [i](bool success) {
  2645. EXPECT_TRUE(success);
  2646. delete i;
  2647. });
  2648. })
  2649. .Get("/streamed-chunked-with-trailer",
  2650. [&](const Request & /*req*/, Response &res) {
  2651. auto i = new int(0);
  2652. res.set_header("Trailer", "Dummy1, Dummy2");
  2653. res.set_chunked_content_provider(
  2654. "text/plain",
  2655. [i](size_t /*offset*/, DataSink &sink) {
  2656. switch (*i) {
  2657. case 0: sink.os << "123"; break;
  2658. case 1: sink.os << "456"; break;
  2659. case 2: sink.os << "789"; break;
  2660. case 3: {
  2661. sink.done_with_trailer(
  2662. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2663. } break;
  2664. }
  2665. (*i)++;
  2666. return true;
  2667. },
  2668. [i](bool success) {
  2669. EXPECT_TRUE(success);
  2670. delete i;
  2671. });
  2672. })
  2673. .Get("/streamed",
  2674. [&](const Request & /*req*/, Response &res) {
  2675. res.set_content_provider(
  2676. 6, "text/plain",
  2677. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2678. sink.os << (offset < 3 ? "a" : "b");
  2679. return true;
  2680. });
  2681. })
  2682. .Get("/streamed-with-range",
  2683. [&](const Request &req, Response &res) {
  2684. auto data = new std::string("abcdefg");
  2685. res.set_content_provider(
  2686. data->size(), "text/plain",
  2687. [data](size_t offset, size_t length, DataSink &sink) {
  2688. size_t DATA_CHUNK_SIZE = 4;
  2689. const auto &d = *data;
  2690. auto out_len =
  2691. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2692. auto ret =
  2693. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2694. EXPECT_TRUE(ret);
  2695. return true;
  2696. },
  2697. [data, &req](bool success) {
  2698. EXPECT_EQ(success, !req.has_param("error"));
  2699. delete data;
  2700. });
  2701. })
  2702. .Get("/streamed-cancel",
  2703. [&](const Request & /*req*/, Response &res) {
  2704. res.set_content_provider(
  2705. size_t(-1), "text/plain",
  2706. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2707. sink.os << "data_chunk";
  2708. return true;
  2709. });
  2710. })
  2711. .Get("/regex-with-delimiter",
  2712. [&](const Request &req, Response & /*res*/) {
  2713. ASSERT_TRUE(req.has_param("key"));
  2714. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2715. })
  2716. .Get("/with-range",
  2717. [&](const Request & /*req*/, Response &res) {
  2718. res.set_content("abcdefg", "text/plain");
  2719. })
  2720. .Get("/test-start-time",
  2721. [&](const Request &req, Response & /*res*/) {
  2722. EXPECT_NE(req.start_time_,
  2723. std::chrono::steady_clock::time_point::min());
  2724. })
  2725. .Get("/with-range-customized-response",
  2726. [&](const Request & /*req*/, Response &res) {
  2727. res.status = StatusCode::BadRequest_400;
  2728. res.set_content(JSON_DATA, "application/json");
  2729. })
  2730. .Post("/chunked",
  2731. [&](const Request &req, Response & /*res*/) {
  2732. EXPECT_EQ(req.body, "dechunked post body");
  2733. })
  2734. .Post("/large-chunked",
  2735. [&](const Request &req, Response & /*res*/) {
  2736. std::string expected(6 * 30 * 1024u, 'a');
  2737. EXPECT_EQ(req.body, expected);
  2738. })
  2739. .Post("/multipart",
  2740. [&](const Request &req, Response & /*res*/) {
  2741. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2742. req.form.get_field_count("text2") +
  2743. req.form.get_field_count("file3") +
  2744. req.form.get_field_count("file4"));
  2745. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2746. req.form.get_file_count("file2"));
  2747. ASSERT_TRUE(!req.form.has_file("???"));
  2748. ASSERT_TRUE(!req.form.has_field("???"));
  2749. ASSERT_TRUE(req.body.empty());
  2750. {
  2751. const auto &text = req.form.get_field("text1");
  2752. EXPECT_EQ("text default", text);
  2753. }
  2754. {
  2755. const auto &text = req.form.get_field("text2");
  2756. EXPECT_EQ("aωb", text);
  2757. }
  2758. {
  2759. const auto &file = req.form.get_file("file1");
  2760. EXPECT_EQ("hello.txt", file.filename);
  2761. EXPECT_EQ("text/plain", file.content_type);
  2762. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2763. }
  2764. {
  2765. const auto &file = req.form.get_file("file2");
  2766. EXPECT_EQ("world.json", file.filename);
  2767. EXPECT_EQ("application/json", file.content_type);
  2768. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2769. }
  2770. {
  2771. const auto &text = req.form.get_field("file3");
  2772. EXPECT_EQ(0u, text.size());
  2773. }
  2774. {
  2775. const auto &text = req.form.get_field("file4");
  2776. EXPECT_EQ(0u, text.size());
  2777. }
  2778. })
  2779. .Post("/multipart/multi_file_values",
  2780. [&](const Request &req, Response & /*res*/) {
  2781. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2782. req.form.get_field_count("multi_text1"));
  2783. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2784. ASSERT_TRUE(!req.form.has_file("???"));
  2785. ASSERT_TRUE(!req.form.has_field("???"));
  2786. ASSERT_TRUE(req.body.empty());
  2787. {
  2788. const auto &text = req.form.get_field("text");
  2789. EXPECT_EQ("default text", text);
  2790. }
  2791. {
  2792. const auto &text1_values = req.form.get_fields("multi_text1");
  2793. EXPECT_EQ(2u, text1_values.size());
  2794. EXPECT_EQ("aaaaa", text1_values[0]);
  2795. EXPECT_EQ("bbbbb", text1_values[1]);
  2796. }
  2797. {
  2798. const auto &file1_values = req.form.get_files("multi_file1");
  2799. EXPECT_EQ(2u, file1_values.size());
  2800. auto file1 = file1_values[0];
  2801. EXPECT_EQ(file1.filename, "hello.txt");
  2802. EXPECT_EQ(file1.content_type, "text/plain");
  2803. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2804. auto file2 = file1_values[1];
  2805. EXPECT_EQ(file2.filename, "world.json");
  2806. EXPECT_EQ(file2.content_type, "application/json");
  2807. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2808. }
  2809. })
  2810. .Post("/empty",
  2811. [&](const Request &req, Response &res) {
  2812. EXPECT_EQ(req.body, "");
  2813. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2814. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2815. res.set_content("empty", "text/plain");
  2816. })
  2817. .Post("/empty-no-content-type",
  2818. [&](const Request &req, Response &res) {
  2819. EXPECT_EQ(req.body, "");
  2820. EXPECT_FALSE(req.has_header("Content-Type"));
  2821. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2822. res.set_content("empty-no-content-type", "text/plain");
  2823. })
  2824. .Post("/path-only",
  2825. [&](const Request &req, Response &res) {
  2826. EXPECT_EQ(req.body, "");
  2827. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2828. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2829. res.set_content("path-only", "text/plain");
  2830. })
  2831. .Post("/path-headers-only",
  2832. [&](const Request &req, Response &res) {
  2833. EXPECT_EQ(req.body, "");
  2834. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2835. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2836. EXPECT_EQ("world", req.get_header_value("hello"));
  2837. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2838. res.set_content("path-headers-only", "text/plain");
  2839. })
  2840. .Post("/post-large",
  2841. [&](const Request &req, Response &res) {
  2842. EXPECT_EQ(req.body, LARGE_DATA);
  2843. res.set_content(req.body, "text/plain");
  2844. })
  2845. .Put("/empty-no-content-type",
  2846. [&](const Request &req, Response &res) {
  2847. EXPECT_EQ(req.body, "");
  2848. EXPECT_FALSE(req.has_header("Content-Type"));
  2849. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2850. res.set_content("empty-no-content-type", "text/plain");
  2851. })
  2852. .Put("/put",
  2853. [&](const Request &req, Response &res) {
  2854. EXPECT_EQ(req.body, "PUT");
  2855. res.set_content(req.body, "text/plain");
  2856. })
  2857. .Put("/put-large",
  2858. [&](const Request &req, Response &res) {
  2859. EXPECT_EQ(req.body, LARGE_DATA);
  2860. res.set_content(req.body, "text/plain");
  2861. })
  2862. .Patch("/patch",
  2863. [&](const Request &req, Response &res) {
  2864. EXPECT_EQ(req.body, "PATCH");
  2865. res.set_content(req.body, "text/plain");
  2866. })
  2867. .Delete("/delete",
  2868. [&](const Request & /*req*/, Response &res) {
  2869. res.set_content("DELETE", "text/plain");
  2870. })
  2871. .Delete("/delete-body",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "content");
  2874. res.set_content(req.body, "text/plain");
  2875. })
  2876. .Options(R"(\*)",
  2877. [&](const Request & /*req*/, Response &res) {
  2878. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2879. })
  2880. .Get("/request-target",
  2881. [&](const Request &req, Response & /*res*/) {
  2882. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2883. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2884. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2885. })
  2886. .Get("/long-query-value",
  2887. [&](const Request &req, Response & /*res*/) {
  2888. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2889. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2890. })
  2891. .Get("/too-long-query-value",
  2892. [&](const Request &req, Response & /*res*/) {
  2893. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2894. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2895. })
  2896. .Get("/array-param",
  2897. [&](const Request &req, Response & /*res*/) {
  2898. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2899. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2900. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2901. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2902. })
  2903. .Post("/validate-no-multiple-headers",
  2904. [&](const Request &req, Response & /*res*/) {
  2905. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2906. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2907. })
  2908. .Post("/content_receiver",
  2909. [&](const Request &req, Response &res,
  2910. const ContentReader &content_reader) {
  2911. if (req.is_multipart_form_data()) {
  2912. std::vector<FormData> items;
  2913. content_reader(
  2914. [&](const FormData &file) {
  2915. items.push_back(file);
  2916. return true;
  2917. },
  2918. [&](const char *data, size_t data_length) {
  2919. items.back().content.append(data, data_length);
  2920. return true;
  2921. });
  2922. EXPECT_EQ(5u, items.size());
  2923. {
  2924. const auto &file = get_file_value(items, "text1");
  2925. EXPECT_TRUE(file.filename.empty());
  2926. EXPECT_EQ("text default", file.content);
  2927. }
  2928. {
  2929. const auto &file = get_file_value(items, "text2");
  2930. EXPECT_TRUE(file.filename.empty());
  2931. EXPECT_EQ("aωb", file.content);
  2932. }
  2933. {
  2934. const auto &file = get_file_value(items, "file1");
  2935. EXPECT_EQ("hello.txt", file.filename);
  2936. EXPECT_EQ("text/plain", file.content_type);
  2937. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2938. }
  2939. {
  2940. const auto &file = get_file_value(items, "file2");
  2941. EXPECT_EQ("world.json", file.filename);
  2942. EXPECT_EQ("application/json", file.content_type);
  2943. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2944. }
  2945. {
  2946. const auto &file = get_file_value(items, "file3");
  2947. EXPECT_TRUE(file.filename.empty());
  2948. EXPECT_EQ("application/octet-stream", file.content_type);
  2949. EXPECT_EQ(0u, file.content.size());
  2950. }
  2951. } else {
  2952. std::string body;
  2953. content_reader([&](const char *data, size_t data_length) {
  2954. EXPECT_EQ(7U, data_length);
  2955. body.append(data, data_length);
  2956. return true;
  2957. });
  2958. EXPECT_EQ(body, "content");
  2959. res.set_content(body, "text/plain");
  2960. }
  2961. })
  2962. .Put("/content_receiver",
  2963. [&](const Request & /*req*/, Response &res,
  2964. const ContentReader &content_reader) {
  2965. std::string body;
  2966. content_reader([&](const char *data, size_t data_length) {
  2967. body.append(data, data_length);
  2968. return true;
  2969. });
  2970. EXPECT_EQ(body, "content");
  2971. res.set_content(body, "text/plain");
  2972. })
  2973. .Patch("/content_receiver",
  2974. [&](const Request & /*req*/, Response &res,
  2975. const ContentReader &content_reader) {
  2976. std::string body;
  2977. content_reader([&](const char *data, size_t data_length) {
  2978. body.append(data, data_length);
  2979. return true;
  2980. });
  2981. EXPECT_EQ(body, "content");
  2982. res.set_content(body, "text/plain");
  2983. })
  2984. .Post("/query-string-and-body",
  2985. [&](const Request &req, Response & /*res*/) {
  2986. ASSERT_TRUE(req.has_param("key"));
  2987. EXPECT_EQ(req.get_param_value("key"), "value");
  2988. EXPECT_EQ(req.body, "content");
  2989. })
  2990. .Get("/last-request",
  2991. [&](const Request &req, Response & /*res*/) {
  2992. EXPECT_EQ("close", req.get_header_value("Connection"));
  2993. })
  2994. .Get(R"(/redirect/(\d+))",
  2995. [&](const Request &req, Response &res) {
  2996. auto num = std::stoi(req.matches[1]) + 1;
  2997. std::string url = "/redirect/" + std::to_string(num);
  2998. res.set_redirect(url);
  2999. })
  3000. .Post("/binary",
  3001. [&](const Request &req, Response &res) {
  3002. EXPECT_EQ(4U, req.body.size());
  3003. EXPECT_EQ("application/octet-stream",
  3004. req.get_header_value("Content-Type"));
  3005. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3006. res.set_content(req.body, "application/octet-stream");
  3007. })
  3008. .Put("/binary",
  3009. [&](const Request &req, Response &res) {
  3010. EXPECT_EQ(4U, req.body.size());
  3011. EXPECT_EQ("application/octet-stream",
  3012. req.get_header_value("Content-Type"));
  3013. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3014. res.set_content(req.body, "application/octet-stream");
  3015. })
  3016. .Patch("/binary",
  3017. [&](const Request &req, Response &res) {
  3018. EXPECT_EQ(4U, req.body.size());
  3019. EXPECT_EQ("application/octet-stream",
  3020. req.get_header_value("Content-Type"));
  3021. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3022. res.set_content(req.body, "application/octet-stream");
  3023. })
  3024. .Delete("/binary",
  3025. [&](const Request &req, Response &res) {
  3026. EXPECT_EQ(4U, req.body.size());
  3027. EXPECT_EQ("application/octet-stream",
  3028. req.get_header_value("Content-Type"));
  3029. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3030. res.set_content(req.body, "application/octet-stream");
  3031. })
  3032. .Get("/issue1772",
  3033. [&](const Request & /*req*/, Response &res) {
  3034. res.status = 401;
  3035. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3036. })
  3037. .Delete("/issue609",
  3038. [](const httplib::Request &, httplib::Response &res,
  3039. const httplib::ContentReader &) {
  3040. res.set_content("ok", "text/plain");
  3041. })
  3042. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3043. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3044. .Get("/compress",
  3045. [&](const Request & /*req*/, Response &res) {
  3046. res.set_content(
  3047. "12345678901234567890123456789012345678901234567890123456789"
  3048. "01234567890123456789012345678901234567890",
  3049. "text/plain");
  3050. })
  3051. .Get("/nocompress",
  3052. [&](const Request & /*req*/, Response &res) {
  3053. res.set_content(
  3054. "12345678901234567890123456789012345678901234567890123456789"
  3055. "01234567890123456789012345678901234567890",
  3056. "application/octet-stream");
  3057. })
  3058. .Post("/compress-multipart",
  3059. [&](const Request &req, Response & /*res*/) {
  3060. EXPECT_EQ(2u, req.form.fields.size());
  3061. ASSERT_TRUE(!req.form.has_field("???"));
  3062. {
  3063. const auto &text = req.form.get_field("key1");
  3064. EXPECT_EQ("test", text);
  3065. }
  3066. {
  3067. const auto &text = req.form.get_field("key2");
  3068. EXPECT_EQ("--abcdefg123", text);
  3069. }
  3070. })
  3071. #endif
  3072. ;
  3073. persons_["john"] = "programmer";
  3074. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3075. svr_.wait_until_ready();
  3076. }
  3077. virtual void TearDown() {
  3078. svr_.stop();
  3079. if (!request_threads_.empty()) {
  3080. std::this_thread::sleep_for(std::chrono::seconds(1));
  3081. for (auto &t : request_threads_) {
  3082. t.join();
  3083. }
  3084. }
  3085. t_.join();
  3086. }
  3087. map<string, string> persons_;
  3088. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3089. SSLClient cli_;
  3090. SSLServer svr_;
  3091. #else
  3092. Client cli_;
  3093. Server svr_;
  3094. #endif
  3095. thread t_;
  3096. std::vector<thread> request_threads_;
  3097. };
  3098. TEST_F(ServerTest, GetMethod200) {
  3099. auto res = cli_.Get("/hi");
  3100. ASSERT_TRUE(res);
  3101. EXPECT_EQ("HTTP/1.1", res->version);
  3102. EXPECT_EQ(StatusCode::OK_200, res->status);
  3103. EXPECT_EQ("OK", res->reason);
  3104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3105. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3106. EXPECT_EQ("Hello World!", res->body);
  3107. }
  3108. TEST_F(ServerTest, GetEmptyFile) {
  3109. auto res = cli_.Get("/empty_file");
  3110. ASSERT_TRUE(res);
  3111. EXPECT_EQ(StatusCode::OK_200, res->status);
  3112. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3113. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3114. EXPECT_EQ("", res->body);
  3115. }
  3116. TEST_F(ServerTest, GetFileContent) {
  3117. auto res = cli_.Get("/file_content");
  3118. ASSERT_TRUE(res);
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3121. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3122. EXPECT_EQ("test.html", res->body);
  3123. }
  3124. TEST_F(ServerTest, GetFileContentWithRange) {
  3125. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3128. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3129. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3130. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3131. EXPECT_EQ("est", res->body);
  3132. }
  3133. TEST_F(ServerTest, GetFileContentWithContentType) {
  3134. auto res = cli_.Get("/file_content_with_content_type");
  3135. ASSERT_TRUE(res);
  3136. EXPECT_EQ(StatusCode::OK_200, res->status);
  3137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3138. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3139. EXPECT_EQ("file\n", res->body);
  3140. }
  3141. TEST_F(ServerTest, GetInvalidFileContent) {
  3142. auto res = cli_.Get("/invalid_file_content");
  3143. ASSERT_TRUE(res);
  3144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3145. }
  3146. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3147. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ("HTTP/1.1", res->version);
  3150. EXPECT_EQ(StatusCode::OK_200, res->status);
  3151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3152. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3153. EXPECT_EQ("Hello World!", res->body);
  3154. }
  3155. TEST_F(ServerTest, GetMethod302) {
  3156. auto res = cli_.Get("/");
  3157. ASSERT_TRUE(res);
  3158. EXPECT_EQ(StatusCode::Found_302, res->status);
  3159. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3160. }
  3161. TEST_F(ServerTest, GetMethod302Redirect) {
  3162. cli_.set_follow_location(true);
  3163. auto res = cli_.Get("/");
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ(StatusCode::OK_200, res->status);
  3166. EXPECT_EQ("Hello World!", res->body);
  3167. EXPECT_EQ("/hi", res->location);
  3168. }
  3169. TEST_F(ServerTest, GetMethod404) {
  3170. auto res = cli_.Get("/invalid");
  3171. ASSERT_TRUE(res);
  3172. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3173. }
  3174. TEST_F(ServerTest, HeadMethod200) {
  3175. auto res = cli_.Head("/hi");
  3176. ASSERT_TRUE(res);
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3179. EXPECT_TRUE(res->body.empty());
  3180. }
  3181. TEST_F(ServerTest, HeadMethod200Static) {
  3182. auto res = cli_.Head("/mount/dir/index.html");
  3183. ASSERT_TRUE(res);
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3186. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3187. EXPECT_TRUE(res->body.empty());
  3188. }
  3189. TEST_F(ServerTest, HeadMethod404) {
  3190. auto res = cli_.Head("/invalid");
  3191. ASSERT_TRUE(res);
  3192. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3193. EXPECT_TRUE(res->body.empty());
  3194. }
  3195. TEST_F(ServerTest, GetMethodPersonJohn) {
  3196. auto res = cli_.Get("/person/john");
  3197. ASSERT_TRUE(res);
  3198. EXPECT_EQ(StatusCode::OK_200, res->status);
  3199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3200. EXPECT_EQ("programmer", res->body);
  3201. }
  3202. TEST_F(ServerTest, PostMethod1) {
  3203. auto res = cli_.Get("/person/john1");
  3204. ASSERT_TRUE(res);
  3205. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3206. res = cli_.Post("/person", "name=john1&note=coder",
  3207. "application/x-www-form-urlencoded");
  3208. ASSERT_TRUE(res);
  3209. ASSERT_EQ(StatusCode::OK_200, res->status);
  3210. res = cli_.Get("/person/john1");
  3211. ASSERT_TRUE(res);
  3212. ASSERT_EQ(StatusCode::OK_200, res->status);
  3213. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3214. ASSERT_EQ("coder", res->body);
  3215. }
  3216. TEST_F(ServerTest, PostMethod2) {
  3217. auto res = cli_.Get("/person/john2");
  3218. ASSERT_TRUE(res);
  3219. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3220. Params params;
  3221. params.emplace("name", "john2");
  3222. params.emplace("note", "coder");
  3223. res = cli_.Post("/person", params);
  3224. ASSERT_TRUE(res);
  3225. ASSERT_EQ(StatusCode::OK_200, res->status);
  3226. res = cli_.Get("/person/john2");
  3227. ASSERT_TRUE(res);
  3228. ASSERT_EQ(StatusCode::OK_200, res->status);
  3229. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. ASSERT_EQ("coder", res->body);
  3231. }
  3232. TEST_F(ServerTest, PutMethod3) {
  3233. auto res = cli_.Get("/person/john3");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. Params params;
  3237. params.emplace("name", "john3");
  3238. params.emplace("note", "coder");
  3239. res = cli_.Put("/person", params);
  3240. ASSERT_TRUE(res);
  3241. ASSERT_EQ(StatusCode::OK_200, res->status);
  3242. res = cli_.Get("/person/john3");
  3243. ASSERT_TRUE(res);
  3244. ASSERT_EQ(StatusCode::OK_200, res->status);
  3245. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3246. ASSERT_EQ("coder", res->body);
  3247. }
  3248. TEST_F(ServerTest, DeleteMethod1) {
  3249. auto res = cli_.Get("/person/john4");
  3250. ASSERT_TRUE(res);
  3251. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3252. Params params;
  3253. params.emplace("name", "john4");
  3254. params.emplace("note", "coder");
  3255. res = cli_.Post("/person", params);
  3256. ASSERT_TRUE(res);
  3257. ASSERT_EQ(StatusCode::OK_200, res->status);
  3258. res = cli_.Get("/person/john4");
  3259. ASSERT_TRUE(res);
  3260. ASSERT_EQ(StatusCode::OK_200, res->status);
  3261. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3262. ASSERT_EQ("coder", res->body);
  3263. Params delete_params;
  3264. delete_params.emplace("name", "john4");
  3265. res = cli_.Delete("/person", delete_params);
  3266. ASSERT_TRUE(res);
  3267. ASSERT_EQ(StatusCode::OK_200, res->status);
  3268. ASSERT_EQ("DELETED", res->body);
  3269. res = cli_.Get("/person/john4");
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3272. }
  3273. TEST_F(ServerTest, DeleteMethod2) {
  3274. auto res = cli_.Get("/person/john5");
  3275. ASSERT_TRUE(res);
  3276. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3277. Params params;
  3278. params.emplace("name", "john5");
  3279. params.emplace("note", "developer");
  3280. res = cli_.Post("/person", params);
  3281. ASSERT_TRUE(res);
  3282. ASSERT_EQ(StatusCode::OK_200, res->status);
  3283. res = cli_.Get("/person/john5");
  3284. ASSERT_TRUE(res);
  3285. ASSERT_EQ(StatusCode::OK_200, res->status);
  3286. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3287. ASSERT_EQ("developer", res->body);
  3288. Params delete_params;
  3289. delete_params.emplace("name", "john5");
  3290. Headers headers;
  3291. headers.emplace("Custom-Header", "test-value");
  3292. res = cli_.Delete("/person", headers, delete_params);
  3293. ASSERT_TRUE(res);
  3294. ASSERT_EQ(StatusCode::OK_200, res->status);
  3295. ASSERT_EQ("DELETED", res->body);
  3296. res = cli_.Get("/person/john5");
  3297. ASSERT_TRUE(res);
  3298. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3299. }
  3300. TEST_F(ServerTest, DeleteMethod3) {
  3301. auto res = cli_.Get("/person/john6");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john6");
  3306. params.emplace("note", "tester");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john6");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("tester", res->body);
  3315. Params delete_params;
  3316. delete_params.emplace("name", "john6");
  3317. Headers headers;
  3318. headers.emplace("Custom-Header", "test-value");
  3319. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3320. ASSERT_TRUE(res);
  3321. ASSERT_EQ(StatusCode::OK_200, res->status);
  3322. ASSERT_EQ("DELETED", res->body);
  3323. res = cli_.Get("/person/john6");
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3326. }
  3327. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3328. Params params;
  3329. params.emplace("json", JSON_DATA);
  3330. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3331. ASSERT_TRUE(res);
  3332. ASSERT_EQ(StatusCode::OK_200, res->status);
  3333. ASSERT_EQ(JSON_DATA, res->body);
  3334. }
  3335. TEST_F(ServerTest, PostEmptyContent) {
  3336. auto res = cli_.Post("/empty", "", "text/plain");
  3337. ASSERT_TRUE(res);
  3338. ASSERT_EQ(StatusCode::OK_200, res->status);
  3339. ASSERT_EQ("empty", res->body);
  3340. }
  3341. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3342. auto res = cli_.Post("/empty-no-content-type");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("empty-no-content-type", res->body);
  3346. }
  3347. TEST_F(ServerTest, PostPathOnly) {
  3348. auto res = cli_.Post("/path-only");
  3349. ASSERT_TRUE(res);
  3350. ASSERT_EQ(StatusCode::OK_200, res->status);
  3351. ASSERT_EQ("path-only", res->body);
  3352. }
  3353. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3354. auto res = cli_.Post("/path-headers-only",
  3355. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3356. ASSERT_TRUE(res);
  3357. ASSERT_EQ(StatusCode::OK_200, res->status);
  3358. ASSERT_EQ("path-headers-only", res->body);
  3359. }
  3360. TEST_F(ServerTest, PostLarge) {
  3361. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::OK_200, res->status);
  3364. EXPECT_EQ(LARGE_DATA, res->body);
  3365. }
  3366. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3367. auto res = cli_.Put("/empty-no-content-type");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("empty-no-content-type", res->body);
  3371. }
  3372. TEST_F(ServerTest, GetMethodDir) {
  3373. auto res = cli_.Get("/dir/");
  3374. ASSERT_TRUE(res);
  3375. EXPECT_EQ(StatusCode::OK_200, res->status);
  3376. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3377. auto body = R"(<html>
  3378. <head>
  3379. </head>
  3380. <body>
  3381. <a href="/dir/test.html">Test</a>
  3382. <a href="/hi">hi</a>
  3383. </body>
  3384. </html>
  3385. )";
  3386. EXPECT_EQ(body, res->body);
  3387. }
  3388. TEST_F(ServerTest, GetMethodDirTest) {
  3389. auto res = cli_.Get("/dir/test.html");
  3390. ASSERT_TRUE(res);
  3391. EXPECT_EQ(StatusCode::OK_200, res->status);
  3392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3393. EXPECT_EQ("test.html", res->body);
  3394. }
  3395. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3396. auto res = cli_.Get("/dir/../dir/test.html");
  3397. ASSERT_TRUE(res);
  3398. EXPECT_EQ(StatusCode::OK_200, res->status);
  3399. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3400. EXPECT_EQ("test.html", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethodInvalidPath) {
  3403. auto res = cli_.Get("/dir/../test.html");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3406. }
  3407. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3408. auto res = cli_.Get("/../www/dir/test.html");
  3409. ASSERT_TRUE(res);
  3410. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3413. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3414. ASSERT_TRUE(res);
  3415. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3416. }
  3417. TEST_F(ServerTest, GetMethodDirMountTest) {
  3418. auto res = cli_.Get("/mount/dir/test.html");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::OK_200, res->status);
  3421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3422. EXPECT_EQ("test.html", res->body);
  3423. }
  3424. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3425. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3426. ASSERT_TRUE(res);
  3427. EXPECT_EQ(StatusCode::OK_200, res->status);
  3428. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3429. EXPECT_EQ("test.html", res->body);
  3430. }
  3431. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3432. auto res = cli_.Get("/mount/dir/../test.html");
  3433. ASSERT_TRUE(res);
  3434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3435. }
  3436. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3437. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3438. ASSERT_TRUE(res);
  3439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3440. }
  3441. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3442. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3443. ASSERT_TRUE(res);
  3444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3445. }
  3446. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3447. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3448. ASSERT_TRUE(res);
  3449. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3450. }
  3451. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3452. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3453. ASSERT_TRUE(res);
  3454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3455. }
  3456. TEST_F(ServerTest, PostMethod303) {
  3457. auto res = cli_.Post("/1", "body", "text/plain");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3460. EXPECT_EQ("/2", res->get_header_value("Location"));
  3461. }
  3462. TEST_F(ServerTest, PostMethod303Redirect) {
  3463. cli_.set_follow_location(true);
  3464. auto res = cli_.Post("/1", "body", "text/plain");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::OK_200, res->status);
  3467. EXPECT_EQ("redirected.", res->body);
  3468. EXPECT_EQ("/2", res->location);
  3469. }
  3470. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3471. auto res = cli_.Get("/dir/test.abcde");
  3472. ASSERT_TRUE(res);
  3473. EXPECT_EQ(StatusCode::OK_200, res->status);
  3474. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3475. EXPECT_EQ("abcde", res->body);
  3476. }
  3477. TEST_F(ServerTest, StaticFileRange) {
  3478. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3481. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3482. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3483. EXPECT_EQ(true, res->has_header("Content-Range"));
  3484. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3485. EXPECT_EQ(std::string("cd"), res->body);
  3486. }
  3487. TEST_F(ServerTest, StaticFileRanges) {
  3488. auto res =
  3489. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3490. ASSERT_TRUE(res);
  3491. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3492. EXPECT_TRUE(
  3493. res->get_header_value("Content-Type")
  3494. .find(
  3495. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3496. 0);
  3497. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3498. }
  3499. TEST_F(ServerTest, StaticFileRangeHead) {
  3500. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3503. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3504. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3505. EXPECT_EQ(true, res->has_header("Content-Range"));
  3506. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3507. }
  3508. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3509. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3514. EXPECT_EQ(true, res->has_header("Content-Range"));
  3515. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3516. res->get_header_value("Content-Range"));
  3517. EXPECT_EQ("LAST\n", res->body);
  3518. }
  3519. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3520. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3521. ASSERT_TRUE(res);
  3522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3523. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3524. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3525. EXPECT_EQ(true, res->has_header("Content-Range"));
  3526. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3527. }
  3528. TEST_F(ServerTest, StaticFileBigFile) {
  3529. auto res = cli_.Get("/dir/1MB.txt");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3533. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3534. }
  3535. TEST_F(ServerTest, InvalidBaseDirMount) {
  3536. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3537. }
  3538. TEST_F(ServerTest, Binary) {
  3539. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3540. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3541. "application/octet-stream");
  3542. ASSERT_TRUE(res);
  3543. ASSERT_EQ(StatusCode::OK_200, res->status);
  3544. ASSERT_EQ(4U, res->body.size());
  3545. res = cli_.Put("/binary", binary.data(), binary.size(),
  3546. "application/octet-stream");
  3547. ASSERT_TRUE(res);
  3548. ASSERT_EQ(StatusCode::OK_200, res->status);
  3549. ASSERT_EQ(4U, res->body.size());
  3550. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3551. "application/octet-stream");
  3552. ASSERT_TRUE(res);
  3553. ASSERT_EQ(StatusCode::OK_200, res->status);
  3554. ASSERT_EQ(4U, res->body.size());
  3555. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3556. "application/octet-stream");
  3557. ASSERT_TRUE(res);
  3558. ASSERT_EQ(StatusCode::OK_200, res->status);
  3559. ASSERT_EQ(4U, res->body.size());
  3560. }
  3561. TEST_F(ServerTest, BinaryString) {
  3562. auto binary = std::string("\x00\x01\x02\x03", 4);
  3563. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3564. ASSERT_TRUE(res);
  3565. ASSERT_EQ(StatusCode::OK_200, res->status);
  3566. ASSERT_EQ(4U, res->body.size());
  3567. res = cli_.Put("/binary", binary, "application/octet-stream");
  3568. ASSERT_TRUE(res);
  3569. ASSERT_EQ(StatusCode::OK_200, res->status);
  3570. ASSERT_EQ(4U, res->body.size());
  3571. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3572. ASSERT_TRUE(res);
  3573. ASSERT_EQ(StatusCode::OK_200, res->status);
  3574. ASSERT_EQ(4U, res->body.size());
  3575. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3576. ASSERT_TRUE(res);
  3577. ASSERT_EQ(StatusCode::OK_200, res->status);
  3578. ASSERT_EQ(4U, res->body.size());
  3579. }
  3580. TEST_F(ServerTest, EmptyRequest) {
  3581. auto res = cli_.Get("");
  3582. ASSERT_TRUE(!res);
  3583. EXPECT_EQ(Error::Connection, res.error());
  3584. }
  3585. TEST_F(ServerTest, LongRequest) {
  3586. std::string request;
  3587. for (size_t i = 0; i < 545; i++) {
  3588. request += "/TooLongRequest";
  3589. }
  3590. request += "OK";
  3591. auto res = cli_.Get(request.c_str());
  3592. ASSERT_TRUE(res);
  3593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3594. }
  3595. TEST_F(ServerTest, TooLongRequest) {
  3596. std::string request;
  3597. for (size_t i = 0; i < 546; i++) {
  3598. request += "/TooLongRequest";
  3599. }
  3600. request += "_NG";
  3601. auto start = std::chrono::high_resolution_clock::now();
  3602. cli_.set_keep_alive(true);
  3603. auto res = cli_.Get(request.c_str());
  3604. auto end = std::chrono::high_resolution_clock::now();
  3605. auto elapsed =
  3606. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3607. .count();
  3608. ASSERT_TRUE(res);
  3609. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3610. EXPECT_LE(elapsed, 100);
  3611. EXPECT_EQ("close", res->get_header_value("Connection"));
  3612. EXPECT_FALSE(cli_.is_socket_open());
  3613. }
  3614. TEST_F(ServerTest, AlmostTooLongRequest) {
  3615. // test for #2046 - URI length check shouldn't include other content on req
  3616. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3617. // leading /, space, HTTP/1.1)
  3618. std::string request =
  3619. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3620. auto res = cli_.Get(request.c_str());
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3623. }
  3624. TEST_F(ServerTest, LongHeader) {
  3625. Request req;
  3626. req.method = "GET";
  3627. req.path = "/hi";
  3628. std::string host_and_port;
  3629. host_and_port += HOST;
  3630. host_and_port += ":";
  3631. host_and_port += std::to_string(PORT);
  3632. req.headers.emplace("Host", host_and_port.c_str());
  3633. req.headers.emplace("Accept", "*/*");
  3634. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3635. req.headers.emplace(
  3636. "Header-Name",
  3637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3661. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3662. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3665. "@@@@@@@@@@@@@@@@");
  3666. auto res = std::make_shared<Response>();
  3667. auto error = Error::Success;
  3668. auto ret = cli_.send(req, *res, error);
  3669. ASSERT_TRUE(ret);
  3670. EXPECT_EQ(StatusCode::OK_200, res->status);
  3671. }
  3672. TEST_F(ServerTest, LongQueryValue) {
  3673. auto start = std::chrono::high_resolution_clock::now();
  3674. cli_.set_keep_alive(true);
  3675. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3676. auto end = std::chrono::high_resolution_clock::now();
  3677. auto elapsed =
  3678. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3679. .count();
  3680. ASSERT_TRUE(res);
  3681. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3682. EXPECT_LE(elapsed, 100);
  3683. EXPECT_EQ("close", res->get_header_value("Connection"));
  3684. EXPECT_FALSE(cli_.is_socket_open());
  3685. }
  3686. TEST_F(ServerTest, TooLongQueryValue) {
  3687. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3688. ASSERT_FALSE(res);
  3689. EXPECT_EQ(Error::Read, res.error());
  3690. }
  3691. TEST_F(ServerTest, TooLongHeader) {
  3692. Request req;
  3693. req.method = "GET";
  3694. req.path = "/hi";
  3695. std::string host_and_port;
  3696. host_and_port += HOST;
  3697. host_and_port += ":";
  3698. host_and_port += std::to_string(PORT);
  3699. req.headers.emplace("Host", host_and_port.c_str());
  3700. req.headers.emplace("Accept", "*/*");
  3701. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3702. req.headers.emplace(
  3703. "Header-Name",
  3704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@");
  3733. auto res = std::make_shared<Response>();
  3734. auto error = Error::Success;
  3735. auto ret = cli_.send(req, *res, error);
  3736. ASSERT_TRUE(ret);
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. }
  3739. TEST_F(ServerTest, HeaderCountAtLimit) {
  3740. // Test with headers just under the 100 limit
  3741. httplib::Headers headers;
  3742. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3743. // This should keep us just under the 100 header limit
  3744. for (int i = 0; i < 95; i++) {
  3745. std::string name = "X-Test-Header-" + std::to_string(i);
  3746. std::string value = "value" + std::to_string(i);
  3747. headers.emplace(name, value);
  3748. }
  3749. // This should work fine as we're under the limit
  3750. auto res = cli_.Get("/hi", headers);
  3751. EXPECT_TRUE(res);
  3752. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3753. }
  3754. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3755. // Test with many headers to exceed the 100 limit
  3756. httplib::Headers headers;
  3757. // Add 150 headers to definitely exceed the 100 limit
  3758. for (int i = 0; i < 150; i++) {
  3759. std::string name = "X-Test-Header-" + std::to_string(i);
  3760. std::string value = "value" + std::to_string(i);
  3761. headers.emplace(name, value);
  3762. }
  3763. // This should fail due to exceeding header count limit
  3764. cli_.set_keep_alive(true);
  3765. auto res = cli_.Get("/hi", headers);
  3766. // The request should either fail or return 400 Bad Request
  3767. if (res) {
  3768. // If we get a response, it should be 400 Bad Request
  3769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3770. } else {
  3771. // Or the request should fail entirely
  3772. EXPECT_FALSE(res);
  3773. }
  3774. EXPECT_EQ("close", res->get_header_value("Connection"));
  3775. EXPECT_FALSE(cli_.is_socket_open());
  3776. }
  3777. TEST_F(ServerTest, PercentEncoding) {
  3778. auto res = cli_.Get("/e%6edwith%");
  3779. ASSERT_TRUE(res);
  3780. EXPECT_EQ(StatusCode::OK_200, res->status);
  3781. }
  3782. TEST_F(ServerTest, PercentEncodingUnicode) {
  3783. auto res = cli_.Get("/e%u006edwith%");
  3784. ASSERT_TRUE(res);
  3785. EXPECT_EQ(StatusCode::OK_200, res->status);
  3786. }
  3787. TEST_F(ServerTest, InvalidPercentEncoding) {
  3788. auto res = cli_.Get("/%endwith%");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3791. }
  3792. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3793. auto res = cli_.Get("/%uendwith%");
  3794. ASSERT_TRUE(res);
  3795. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3796. }
  3797. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3798. auto res = cli_.Get("/hello?aaa=bbb%");
  3799. ASSERT_TRUE(res);
  3800. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3801. }
  3802. TEST_F(ServerTest, PlusSignEncoding) {
  3803. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3804. ASSERT_TRUE(res);
  3805. EXPECT_EQ(StatusCode::OK_200, res->status);
  3806. EXPECT_EQ("a +b", res->body);
  3807. }
  3808. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3809. // This test simulates a potential DoS attack using many headers
  3810. // to verify our security fix prevents memory exhaustion
  3811. httplib::Headers attack_headers;
  3812. // Attempt to add many headers like an attacker would (200 headers to far
  3813. // exceed limit)
  3814. for (int i = 0; i < 200; i++) {
  3815. std::string name = "X-Attack-Header-" + std::to_string(i);
  3816. std::string value = "attack_payload_" + std::to_string(i);
  3817. attack_headers.emplace(name, value);
  3818. }
  3819. // Try to POST with excessive headers
  3820. cli_.set_keep_alive(true);
  3821. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3822. // Should either fail or return 400 Bad Request due to security limit
  3823. if (res) {
  3824. // If we get a response, it should be 400 Bad Request
  3825. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3826. } else {
  3827. // Request failed, which is the expected behavior for DoS protection
  3828. EXPECT_FALSE(res);
  3829. }
  3830. EXPECT_EQ("close", res->get_header_value("Connection"));
  3831. EXPECT_FALSE(cli_.is_socket_open());
  3832. }
  3833. TEST_F(ServerTest, MultipartFormData) {
  3834. UploadFormDataItems items = {
  3835. {"text1", "text default", "", ""},
  3836. {"text2", "aωb", "", ""},
  3837. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3838. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3839. {"file3", "", "", "application/octet-stream"},
  3840. {"file4", "", "", " application/json tmp-string "}};
  3841. auto res = cli_.Post("/multipart", items);
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::OK_200, res->status);
  3844. }
  3845. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3846. UploadFormDataItems items = {
  3847. {"text", "default text", "", ""},
  3848. {"multi_text1", "aaaaa", "", ""},
  3849. {"multi_text1", "bbbbb", "", ""},
  3850. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3851. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3852. "application/json"},
  3853. };
  3854. auto res = cli_.Post("/multipart/multi_file_values", items);
  3855. ASSERT_TRUE(res);
  3856. EXPECT_EQ(StatusCode::OK_200, res->status);
  3857. }
  3858. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3859. auto res = cli_.Get("/hi");
  3860. ASSERT_TRUE(res);
  3861. EXPECT_EQ(StatusCode::OK_200, res->status);
  3862. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3863. EXPECT_EQ("Hello World!", res->body);
  3864. }
  3865. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3866. Request req;
  3867. req.method = "POST";
  3868. req.path = "/chunked";
  3869. std::string host_and_port;
  3870. host_and_port += HOST;
  3871. host_and_port += ":";
  3872. host_and_port += std::to_string(PORT);
  3873. req.headers.emplace("Host", host_and_port.c_str());
  3874. req.headers.emplace("Accept", "*/*");
  3875. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3876. req.headers.emplace("Content-Type", "text/plain");
  3877. req.headers.emplace("Content-Length", "0");
  3878. req.headers.emplace(
  3879. "Transfer-Encoding",
  3880. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3881. // Client does not chunk, so make a chunked body manually.
  3882. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3883. auto res = std::make_shared<Response>();
  3884. auto error = Error::Success;
  3885. auto ret = cli_.send(req, *res, error);
  3886. ASSERT_TRUE(ret);
  3887. EXPECT_EQ(StatusCode::OK_200, res->status);
  3888. }
  3889. TEST_F(ServerTest, GetStreamed2) {
  3890. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3893. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3894. EXPECT_EQ(true, res->has_header("Content-Range"));
  3895. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3896. EXPECT_EQ(std::string("ab"), res->body);
  3897. }
  3898. TEST_F(ServerTest, GetStreamed) {
  3899. auto res = cli_.Get("/streamed");
  3900. ASSERT_TRUE(res);
  3901. EXPECT_EQ(StatusCode::OK_200, res->status);
  3902. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3903. EXPECT_EQ(std::string("aaabbb"), res->body);
  3904. }
  3905. TEST_F(ServerTest, GetStreamedWithRange1) {
  3906. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3907. ASSERT_TRUE(res);
  3908. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3909. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3910. EXPECT_EQ(true, res->has_header("Content-Range"));
  3911. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3912. EXPECT_EQ(std::string("def"), res->body);
  3913. }
  3914. TEST_F(ServerTest, GetStreamedWithRange2) {
  3915. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3916. ASSERT_TRUE(res);
  3917. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3918. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3919. EXPECT_EQ(true, res->has_header("Content-Range"));
  3920. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3921. EXPECT_EQ(std::string("bcdefg"), res->body);
  3922. }
  3923. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3924. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3925. ASSERT_TRUE(res);
  3926. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3927. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3928. EXPECT_EQ(true, res->has_header("Content-Range"));
  3929. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3930. EXPECT_EQ(std::string("efg"), res->body);
  3931. }
  3932. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3933. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3934. ASSERT_TRUE(res);
  3935. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3936. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3937. EXPECT_EQ(false, res->has_header("Content-Range"));
  3938. EXPECT_EQ(0U, res->body.size());
  3939. }
  3940. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3941. auto res = cli_.Get("/streamed-with-range",
  3942. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3943. "92233720368547758079223372036854775807"}});
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3946. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3947. EXPECT_EQ(false, res->has_header("Content-Range"));
  3948. EXPECT_EQ(0U, res->body.size());
  3949. }
  3950. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3951. auto res = cli_.Get(
  3952. "/with-range",
  3953. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3954. {"Accept-Encoding", ""}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3958. EXPECT_EQ(true, res->has_header("Content-Range"));
  3959. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3960. EXPECT_EQ(std::string("abcdefg"), res->body);
  3961. }
  3962. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3963. auto res = cli_.Get("/with-range", {
  3964. {"Range", "bytes=0-"},
  3965. {"Accept-Encoding", ""},
  3966. });
  3967. ASSERT_TRUE(res);
  3968. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3969. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3970. EXPECT_EQ(true, res->has_header("Content-Range"));
  3971. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3972. EXPECT_EQ(std::string("abcdefg"), res->body);
  3973. }
  3974. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3975. auto res =
  3976. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3977. ASSERT_TRUE(res);
  3978. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3979. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3980. EXPECT_EQ(false, res->has_header("Content-Range"));
  3981. EXPECT_EQ(267U, res->body.size());
  3982. // Check that both range contents are present
  3983. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  3984. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  3985. // Check that Content-Range headers are present for both ranges
  3986. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  3987. std::string::npos);
  3988. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  3989. std::string::npos);
  3990. }
  3991. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3992. Ranges ranges;
  3993. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3994. ranges.emplace_back(0, -1);
  3995. }
  3996. auto res =
  3997. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3998. ASSERT_TRUE(res);
  3999. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4000. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4001. EXPECT_EQ(false, res->has_header("Content-Range"));
  4002. EXPECT_EQ(0U, res->body.size());
  4003. }
  4004. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4005. auto res =
  4006. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4009. EXPECT_EQ(5U, res->body.size());
  4010. // Check that overlapping ranges are coalesced into a single range
  4011. EXPECT_EQ("bcdef", res->body);
  4012. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4013. // Should be single range, not multipart
  4014. EXPECT_TRUE(res->has_header("Content-Range"));
  4015. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4016. }
  4017. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4018. auto res =
  4019. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4020. ASSERT_TRUE(res);
  4021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4022. EXPECT_EQ(268U, res->body.size());
  4023. // Check that both range contents are present
  4024. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4025. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4026. // Check that Content-Range headers are present for both ranges
  4027. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4028. std::string::npos);
  4029. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4030. std::string::npos);
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4033. auto res =
  4034. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4035. ASSERT_TRUE(res);
  4036. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4037. EXPECT_EQ(269U, res->body.size());
  4038. // Check that both duplicate range contents are present
  4039. size_t first_abc = res->body.find("abc\r\n");
  4040. EXPECT_TRUE(first_abc != std::string::npos);
  4041. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4042. EXPECT_TRUE(second_abc != std::string::npos);
  4043. // Check that Content-Range headers are present for both ranges
  4044. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4045. EXPECT_TRUE(first_range != std::string::npos);
  4046. size_t second_range =
  4047. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4048. EXPECT_TRUE(second_range != std::string::npos);
  4049. }
  4050. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4051. auto res = cli_.Get("/streamed-with-range?error",
  4052. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4053. ASSERT_TRUE(res);
  4054. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4055. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4056. EXPECT_EQ(false, res->has_header("Content-Range"));
  4057. EXPECT_EQ(0U, res->body.size());
  4058. }
  4059. TEST_F(ServerTest, GetStreamedEndless) {
  4060. uint64_t offset = 0;
  4061. auto res = cli_.Get("/streamed-cancel",
  4062. [&](const char * /*data*/, uint64_t data_length) {
  4063. if (offset < 100) {
  4064. offset += data_length;
  4065. return true;
  4066. }
  4067. return false;
  4068. });
  4069. ASSERT_TRUE(!res);
  4070. EXPECT_EQ(Error::Canceled, res.error());
  4071. }
  4072. TEST_F(ServerTest, ClientStop) {
  4073. std::atomic_size_t count{4};
  4074. std::vector<std::thread> threads;
  4075. for (auto i = count.load(); i != 0; --i) {
  4076. threads.emplace_back([&]() {
  4077. auto res = cli_.Get("/streamed-cancel",
  4078. [&](const char *, uint64_t) { return true; });
  4079. --count;
  4080. ASSERT_TRUE(!res);
  4081. EXPECT_TRUE(res.error() == Error::Canceled ||
  4082. res.error() == Error::Read || res.error() == Error::Write);
  4083. });
  4084. }
  4085. std::this_thread::sleep_for(std::chrono::seconds(2));
  4086. while (count != 0) {
  4087. cli_.stop();
  4088. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4089. }
  4090. for (auto &t : threads) {
  4091. t.join();
  4092. }
  4093. }
  4094. TEST_F(ServerTest, GetWithRange1) {
  4095. auto res = cli_.Get("/with-range", {
  4096. make_range_header({{3, 5}}),
  4097. {"Accept-Encoding", ""},
  4098. });
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ(true, res->has_header("Content-Range"));
  4103. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4104. EXPECT_EQ(std::string("def"), res->body);
  4105. }
  4106. TEST_F(ServerTest, GetWithRange2) {
  4107. auto res = cli_.Get("/with-range", {
  4108. make_range_header({{1, -1}}),
  4109. {"Accept-Encoding", ""},
  4110. });
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4113. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(true, res->has_header("Content-Range"));
  4115. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4116. EXPECT_EQ(std::string("bcdefg"), res->body);
  4117. }
  4118. TEST_F(ServerTest, GetWithRange3) {
  4119. auto res = cli_.Get("/with-range", {
  4120. make_range_header({{0, 0}}),
  4121. {"Accept-Encoding", ""},
  4122. });
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4125. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4126. EXPECT_EQ(true, res->has_header("Content-Range"));
  4127. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4128. EXPECT_EQ(std::string("a"), res->body);
  4129. }
  4130. TEST_F(ServerTest, GetWithRange4) {
  4131. auto res = cli_.Get("/with-range", {
  4132. make_range_header({{-1, 2}}),
  4133. {"Accept-Encoding", ""},
  4134. });
  4135. ASSERT_TRUE(res);
  4136. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4137. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4138. EXPECT_EQ(true, res->has_header("Content-Range"));
  4139. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4140. EXPECT_EQ(std::string("fg"), res->body);
  4141. }
  4142. TEST_F(ServerTest, GetWithRange5) {
  4143. auto res = cli_.Get("/with-range", {
  4144. make_range_header({{0, 5}}),
  4145. {"Accept-Encoding", ""},
  4146. });
  4147. ASSERT_TRUE(res);
  4148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4149. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4150. EXPECT_EQ(true, res->has_header("Content-Range"));
  4151. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4152. EXPECT_EQ(std::string("abcdef"), res->body);
  4153. }
  4154. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4155. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4156. ASSERT_TRUE(res);
  4157. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4158. }
  4159. TEST_F(ServerTest, GetWithRangeMultipart) {
  4160. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4161. ASSERT_TRUE(res);
  4162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4163. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4164. EXPECT_EQ(false, res->has_header("Content-Range"));
  4165. EXPECT_EQ(267U, res->body.size());
  4166. }
  4167. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4168. auto res =
  4169. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4170. ASSERT_TRUE(res);
  4171. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4172. }
  4173. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4174. auto res = cli_.Get("/with-range-customized-response",
  4175. {{make_range_header({{1, 2}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4178. EXPECT_EQ(true, res->has_header("Content-Length"));
  4179. EXPECT_EQ(false, res->has_header("Content-Range"));
  4180. EXPECT_EQ(JSON_DATA, res->body);
  4181. }
  4182. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4183. auto res = cli_.Get("/with-range-customized-response",
  4184. {{make_range_header({{1, 2}, {4, 5}})}});
  4185. ASSERT_TRUE(res);
  4186. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4187. EXPECT_EQ(true, res->has_header("Content-Length"));
  4188. EXPECT_EQ(false, res->has_header("Content-Range"));
  4189. EXPECT_EQ(JSON_DATA, res->body);
  4190. }
  4191. TEST_F(ServerTest, Issue1772) {
  4192. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4193. ASSERT_TRUE(res);
  4194. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4195. }
  4196. TEST_F(ServerTest, Issue609) {
  4197. auto res = cli_.Delete("/issue609");
  4198. ASSERT_TRUE(res);
  4199. EXPECT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ(std::string("ok"), res->body);
  4201. }
  4202. TEST_F(ServerTest, GetStreamedChunked) {
  4203. auto res = cli_.Get("/streamed-chunked");
  4204. ASSERT_TRUE(res);
  4205. EXPECT_EQ(StatusCode::OK_200, res->status);
  4206. EXPECT_EQ(std::string("123456789"), res->body);
  4207. }
  4208. TEST_F(ServerTest, GetStreamedChunked2) {
  4209. auto res = cli_.Get("/streamed-chunked2");
  4210. ASSERT_TRUE(res);
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. EXPECT_EQ(std::string("123456789"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4215. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4216. ASSERT_TRUE(res);
  4217. EXPECT_EQ(StatusCode::OK_200, res->status);
  4218. EXPECT_EQ(std::string("123456789"), res->body);
  4219. EXPECT_TRUE(res->has_header("Trailer"));
  4220. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4221. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4222. // Trailers are now stored separately from headers (security fix)
  4223. EXPECT_EQ(2U, res->trailers.size());
  4224. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4225. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4226. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4227. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4228. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4229. // Verify trailers are NOT in headers (security verification)
  4230. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4231. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4232. }
  4233. TEST_F(ServerTest, LargeChunkedPost) {
  4234. Request req;
  4235. req.method = "POST";
  4236. req.path = "/large-chunked";
  4237. std::string host_and_port;
  4238. host_and_port += HOST;
  4239. host_and_port += ":";
  4240. host_and_port += std::to_string(PORT);
  4241. req.headers.emplace("Host", host_and_port.c_str());
  4242. req.headers.emplace("Accept", "*/*");
  4243. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4244. req.headers.emplace("Content-Type", "text/plain");
  4245. req.headers.emplace("Content-Length", "0");
  4246. req.headers.emplace("Transfer-Encoding", "chunked");
  4247. std::string long_string(30 * 1024u, 'a');
  4248. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4249. // Attempt to make a large enough post to exceed OS buffers, to test that
  4250. // the server handles short reads if the full chunk data isn't available.
  4251. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4252. auto res = std::make_shared<Response>();
  4253. auto error = Error::Success;
  4254. auto ret = cli_.send(req, *res, error);
  4255. ASSERT_TRUE(ret);
  4256. EXPECT_EQ(StatusCode::OK_200, res->status);
  4257. }
  4258. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4259. auto res = cli_.Get("/remote_addr");
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::OK_200, res->status);
  4262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4263. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4264. }
  4265. TEST_F(ServerTest, GetMethodLocalAddr) {
  4266. auto res = cli_.Get("/local_addr");
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::OK_200, res->status);
  4269. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4270. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4271. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4272. }
  4273. TEST_F(ServerTest, HTTPResponseSplitting) {
  4274. auto res = cli_.Get("/http_response_splitting");
  4275. ASSERT_TRUE(res);
  4276. EXPECT_EQ(StatusCode::OK_200, res->status);
  4277. }
  4278. TEST_F(ServerTest, SlowRequest) {
  4279. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4280. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4281. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4282. }
  4283. #if 0
  4284. TEST_F(ServerTest, SlowPost) {
  4285. char buffer[64 * 1024];
  4286. memset(buffer, 0x42, sizeof(buffer));
  4287. auto res = cli_.Post(
  4288. "/slowpost", 64 * 1024 * 1024,
  4289. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4290. auto ret = sink.write(buffer, sizeof(buffer));
  4291. EXPECT_TRUE(ret);
  4292. return true;
  4293. },
  4294. "text/plain");
  4295. ASSERT_TRUE(res);
  4296. EXPECT_EQ(StatusCode::OK_200, res->status);
  4297. }
  4298. TEST_F(ServerTest, SlowPostFail) {
  4299. char buffer[64 * 1024];
  4300. memset(buffer, 0x42, sizeof(buffer));
  4301. cli_.set_write_timeout(std::chrono::seconds(0));
  4302. auto res = cli_.Post(
  4303. "/slowpost", 64 * 1024 * 1024,
  4304. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4305. sink.write(buffer, sizeof(buffer));
  4306. return true;
  4307. },
  4308. "text/plain");
  4309. ASSERT_TRUE(!res);
  4310. EXPECT_EQ(Error::Write, res.error());
  4311. }
  4312. #endif
  4313. TEST_F(ServerTest, Put) {
  4314. auto res = cli_.Put("/put", "PUT", "text/plain");
  4315. ASSERT_TRUE(res);
  4316. EXPECT_EQ(StatusCode::OK_200, res->status);
  4317. EXPECT_EQ("PUT", res->body);
  4318. }
  4319. TEST_F(ServerTest, PutWithContentProvider) {
  4320. auto res = cli_.Put(
  4321. "/put", 3,
  4322. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4323. sink.os << "PUT";
  4324. return true;
  4325. },
  4326. "text/plain");
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::OK_200, res->status);
  4329. EXPECT_EQ("PUT", res->body);
  4330. }
  4331. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4332. auto res = cli_.Post(
  4333. "/post", 42,
  4334. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4335. return false;
  4336. },
  4337. "text/plain");
  4338. ASSERT_TRUE(!res);
  4339. EXPECT_EQ(Error::Canceled, res.error());
  4340. }
  4341. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4342. auto res = cli_.Put(
  4343. "/put",
  4344. [](size_t /*offset*/, DataSink &sink) {
  4345. sink.os << "PUT";
  4346. sink.done();
  4347. return true;
  4348. },
  4349. "text/plain");
  4350. ASSERT_TRUE(res);
  4351. EXPECT_EQ(StatusCode::OK_200, res->status);
  4352. EXPECT_EQ("PUT", res->body);
  4353. }
  4354. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  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. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4362. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4363. cli_.set_compress(true);
  4364. auto res = cli_.Put(
  4365. "/put", 3,
  4366. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4367. sink.os << "PUT";
  4368. return true;
  4369. },
  4370. "text/plain");
  4371. ASSERT_TRUE(res);
  4372. EXPECT_EQ(StatusCode::OK_200, res->status);
  4373. EXPECT_EQ("PUT", res->body);
  4374. }
  4375. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4376. cli_.set_compress(true);
  4377. auto res = cli_.Post(
  4378. "/post", 42,
  4379. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4380. return false;
  4381. },
  4382. "text/plain");
  4383. ASSERT_TRUE(!res);
  4384. EXPECT_EQ(Error::Canceled, res.error());
  4385. }
  4386. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4387. cli_.set_compress(true);
  4388. auto res = cli_.Put(
  4389. "/put",
  4390. [](size_t /*offset*/, DataSink &sink) {
  4391. sink.os << "PUT";
  4392. sink.done();
  4393. return true;
  4394. },
  4395. "text/plain");
  4396. ASSERT_TRUE(res);
  4397. EXPECT_EQ(StatusCode::OK_200, res->status);
  4398. EXPECT_EQ("PUT", res->body);
  4399. }
  4400. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4401. cli_.set_compress(true);
  4402. auto res = cli_.Post(
  4403. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4404. "text/plain");
  4405. ASSERT_TRUE(!res);
  4406. EXPECT_EQ(Error::Canceled, res.error());
  4407. }
  4408. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4409. cli_.set_compress(true);
  4410. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ(LARGE_DATA, res->body);
  4414. }
  4415. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4416. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4417. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4418. Client cli(s.c_str());
  4419. cli.enable_server_certificate_verification(false);
  4420. #else
  4421. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4422. Client cli(s.c_str());
  4423. #endif
  4424. cli.set_compress(true);
  4425. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4426. ASSERT_TRUE(res);
  4427. EXPECT_EQ(StatusCode::OK_200, res->status);
  4428. EXPECT_EQ(LARGE_DATA, res->body);
  4429. // The compressed size should be less than a 10th of the original. May vary
  4430. // depending on the zlib library.
  4431. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4432. static_cast<uint64_t>(10 * 1024 * 1024));
  4433. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4434. }
  4435. TEST_F(ServerTest, PutContentWithDeflate) {
  4436. cli_.set_compress(false);
  4437. Headers headers;
  4438. headers.emplace("Content-Encoding", "deflate");
  4439. // PUT in deflate format:
  4440. auto res = cli_.Put("/put", headers,
  4441. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::OK_200, res->status);
  4444. EXPECT_EQ("PUT", res->body);
  4445. }
  4446. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4447. Headers headers;
  4448. headers.emplace("Accept-Encoding", "gzip, deflate");
  4449. auto res = cli_.Get("/streamed-chunked", headers);
  4450. ASSERT_TRUE(res);
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ(std::string("123456789"), res->body);
  4453. }
  4454. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4455. Headers headers;
  4456. headers.emplace("Accept-Encoding", "gzip, deflate");
  4457. auto res = cli_.Get("/streamed-chunked2", headers);
  4458. ASSERT_TRUE(res);
  4459. EXPECT_EQ(StatusCode::OK_200, res->status);
  4460. EXPECT_EQ(std::string("123456789"), res->body);
  4461. }
  4462. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4463. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4464. ASSERT_TRUE(res);
  4465. EXPECT_EQ(StatusCode::OK_200, res->status);
  4466. }
  4467. TEST(GzipDecompressor, ChunkedDecompression) {
  4468. std::string data;
  4469. for (size_t i = 0; i < 32 * 1024; ++i) {
  4470. data.push_back(static_cast<char>('a' + i % 26));
  4471. }
  4472. std::string compressed_data;
  4473. {
  4474. httplib::detail::gzip_compressor compressor;
  4475. bool result = compressor.compress(
  4476. data.data(), data.size(),
  4477. /*last=*/true,
  4478. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4479. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4480. compressed_data_size);
  4481. return true;
  4482. });
  4483. ASSERT_TRUE(result);
  4484. }
  4485. std::string decompressed_data;
  4486. {
  4487. httplib::detail::gzip_decompressor decompressor;
  4488. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4489. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4490. size_t chunk_size = 130;
  4491. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4492. chunk_begin += chunk_size) {
  4493. size_t current_chunk_size =
  4494. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4495. bool result = decompressor.decompress(
  4496. compressed_data.data() + chunk_begin, current_chunk_size,
  4497. [&](const char *decompressed_data_chunk,
  4498. size_t decompressed_data_chunk_size) {
  4499. decompressed_data.insert(decompressed_data.size(),
  4500. decompressed_data_chunk,
  4501. decompressed_data_chunk_size);
  4502. return true;
  4503. });
  4504. ASSERT_TRUE(result);
  4505. }
  4506. }
  4507. ASSERT_EQ(data, decompressed_data);
  4508. }
  4509. TEST(GzipDecompressor, DeflateDecompression) {
  4510. std::string original_text = "Raw deflate without gzip";
  4511. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4512. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4513. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4514. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4515. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4516. std::string decompressed_data;
  4517. {
  4518. httplib::detail::gzip_decompressor decompressor;
  4519. bool result = decompressor.decompress(
  4520. compressed_data.data(), compressed_data.size(),
  4521. [&](const char *decompressed_data_chunk,
  4522. size_t decompressed_data_chunk_size) {
  4523. decompressed_data.insert(decompressed_data.size(),
  4524. decompressed_data_chunk,
  4525. decompressed_data_chunk_size);
  4526. return true;
  4527. });
  4528. ASSERT_TRUE(result);
  4529. }
  4530. ASSERT_EQ(original_text, decompressed_data);
  4531. }
  4532. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4533. std::string original_text = "Raw deflate without gzip";
  4534. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4535. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4536. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4537. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4538. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4539. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4540. std::string decompressed_data;
  4541. {
  4542. httplib::detail::gzip_decompressor decompressor;
  4543. bool result = decompressor.decompress(
  4544. compressed_data.data(), compressed_data.size(),
  4545. [&](const char *decompressed_data_chunk,
  4546. size_t decompressed_data_chunk_size) {
  4547. decompressed_data.insert(decompressed_data.size(),
  4548. decompressed_data_chunk,
  4549. decompressed_data_chunk_size);
  4550. return true;
  4551. });
  4552. ASSERT_TRUE(result);
  4553. }
  4554. ASSERT_EQ(original_text, decompressed_data);
  4555. }
  4556. #ifdef _WIN32
  4557. TEST(GzipDecompressor, LargeRandomData) {
  4558. // prepare large random data that is difficult to be compressed and is
  4559. // expected to have large size even when compressed
  4560. std::random_device seed_gen;
  4561. std::mt19937 random(seed_gen());
  4562. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4563. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4564. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4565. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4566. // compress data over 4GiB
  4567. std::string compressed_data;
  4568. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4569. httplib::detail::gzip_compressor compressor;
  4570. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4571. data.size() * sizeof(std::uint32_t), true,
  4572. [&](const char *data, size_t size) {
  4573. compressed_data.insert(
  4574. compressed_data.size(), data, size);
  4575. return true;
  4576. });
  4577. ASSERT_TRUE(result);
  4578. // FIXME: compressed data size is expected to be greater than 4GiB,
  4579. // but there is no guarantee
  4580. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4581. // decompress data over 4GiB
  4582. std::string decompressed_data;
  4583. decompressed_data.reserve(data_size);
  4584. httplib::detail::gzip_decompressor decompressor;
  4585. result = decompressor.decompress(
  4586. compressed_data.data(), compressed_data.size(),
  4587. [&](const char *data, size_t size) {
  4588. decompressed_data.insert(decompressed_data.size(), data, size);
  4589. return true;
  4590. });
  4591. ASSERT_TRUE(result);
  4592. // compare
  4593. ASSERT_EQ(data_size, decompressed_data.size());
  4594. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4595. 0);
  4596. }
  4597. #endif
  4598. #endif
  4599. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4600. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4601. Headers headers;
  4602. headers.emplace("Accept-Encoding", "br");
  4603. auto res = cli_.Get("/streamed-chunked", headers);
  4604. ASSERT_TRUE(res);
  4605. EXPECT_EQ(StatusCode::OK_200, res->status);
  4606. EXPECT_EQ(std::string("123456789"), res->body);
  4607. }
  4608. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4609. Headers headers;
  4610. headers.emplace("Accept-Encoding", "br");
  4611. auto res = cli_.Get("/streamed-chunked2", headers);
  4612. ASSERT_TRUE(res);
  4613. EXPECT_EQ(StatusCode::OK_200, res->status);
  4614. EXPECT_EQ(std::string("123456789"), res->body);
  4615. }
  4616. #endif
  4617. TEST_F(ServerTest, Patch) {
  4618. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4619. ASSERT_TRUE(res);
  4620. EXPECT_EQ(StatusCode::OK_200, res->status);
  4621. EXPECT_EQ("PATCH", res->body);
  4622. }
  4623. TEST_F(ServerTest, Delete) {
  4624. auto res = cli_.Delete("/delete");
  4625. ASSERT_TRUE(res);
  4626. EXPECT_EQ(StatusCode::OK_200, res->status);
  4627. EXPECT_EQ("DELETE", res->body);
  4628. }
  4629. TEST_F(ServerTest, DeleteContentReceiver) {
  4630. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4631. ASSERT_TRUE(res);
  4632. EXPECT_EQ(StatusCode::OK_200, res->status);
  4633. EXPECT_EQ("content", res->body);
  4634. }
  4635. TEST_F(ServerTest, Options) {
  4636. auto res = cli_.Options("*");
  4637. ASSERT_TRUE(res);
  4638. EXPECT_EQ(StatusCode::OK_200, res->status);
  4639. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4640. EXPECT_TRUE(res->body.empty());
  4641. }
  4642. TEST_F(ServerTest, URL) {
  4643. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4644. ASSERT_TRUE(res);
  4645. EXPECT_EQ(StatusCode::OK_200, res->status);
  4646. }
  4647. TEST_F(ServerTest, ArrayParam) {
  4648. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4649. ASSERT_TRUE(res);
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. }
  4652. TEST_F(ServerTest, NoMultipleHeaders) {
  4653. Headers headers = {{"Content-Length", "5"}};
  4654. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4655. "text/plain");
  4656. ASSERT_TRUE(res);
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. }
  4659. TEST_F(ServerTest, PostContentReceiver) {
  4660. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4661. ASSERT_TRUE(res);
  4662. ASSERT_EQ(StatusCode::OK_200, res->status);
  4663. ASSERT_EQ("content", res->body);
  4664. }
  4665. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4666. UploadFormDataItems items = {
  4667. {"text1", "text default", "", ""},
  4668. {"text2", "aωb", "", ""},
  4669. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4670. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4671. {"file3", "", "", "application/octet-stream"},
  4672. };
  4673. auto res = cli_.Post("/content_receiver", items);
  4674. ASSERT_TRUE(res);
  4675. EXPECT_EQ(StatusCode::OK_200, res->status);
  4676. }
  4677. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4678. UploadFormDataItems items = {
  4679. {"text1", "text default", "", ""},
  4680. {"text2", "aωb", "", ""},
  4681. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4682. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4683. {"file3", "", "", "application/octet-stream"},
  4684. };
  4685. auto boundary = std::string("+++++");
  4686. std::string body;
  4687. for (const auto &item : items) {
  4688. body += "--" + boundary + "\r\n";
  4689. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4690. if (!item.filename.empty()) {
  4691. body += "; filename=\"" + item.filename + "\"";
  4692. }
  4693. body += "\r\n";
  4694. if (!item.content_type.empty()) {
  4695. body += "Content-Type: " + item.content_type + "\r\n";
  4696. }
  4697. body += "\r\n";
  4698. body += item.content + "\r\n";
  4699. }
  4700. body += "--" + boundary + "--\r\n";
  4701. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4702. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. }
  4706. TEST_F(ServerTest, PostContentReceiverGzip) {
  4707. cli_.set_compress(true);
  4708. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4709. ASSERT_TRUE(res);
  4710. ASSERT_EQ(StatusCode::OK_200, res->status);
  4711. ASSERT_EQ("content", res->body);
  4712. }
  4713. TEST_F(ServerTest, PutContentReceiver) {
  4714. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4715. ASSERT_TRUE(res);
  4716. ASSERT_EQ(StatusCode::OK_200, res->status);
  4717. ASSERT_EQ("content", res->body);
  4718. }
  4719. TEST_F(ServerTest, PatchContentReceiver) {
  4720. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4721. ASSERT_TRUE(res);
  4722. ASSERT_EQ(StatusCode::OK_200, res->status);
  4723. ASSERT_EQ("content", res->body);
  4724. }
  4725. template <typename ClientType>
  4726. void TestWithHeadersAndContentReceiver(
  4727. ClientType &cli,
  4728. std::function<Result(ClientType &, const std::string &, const Headers &,
  4729. const std::string &, const std::string &,
  4730. ContentReceiver, DownloadProgress)>
  4731. request_func) {
  4732. Headers headers;
  4733. headers.emplace("X-Custom-Header", "test-value");
  4734. std::string received_body;
  4735. auto res = request_func(
  4736. cli, "/content_receiver", headers, "content", "application/json",
  4737. [&](const char *data, size_t data_length) {
  4738. received_body.append(data, data_length);
  4739. return true;
  4740. },
  4741. nullptr);
  4742. ASSERT_TRUE(res);
  4743. EXPECT_EQ(StatusCode::OK_200, res->status);
  4744. EXPECT_EQ("content", received_body);
  4745. }
  4746. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4748. using ClientT = SSLClient;
  4749. #else
  4750. using ClientT = Client;
  4751. #endif
  4752. TestWithHeadersAndContentReceiver<ClientT>(
  4753. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4754. const std::string &body, const std::string &content_type,
  4755. ContentReceiver receiver, DownloadProgress progress) {
  4756. return cli.Post(path, headers, body, content_type, receiver, progress);
  4757. });
  4758. }
  4759. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4761. using ClientT = SSLClient;
  4762. #else
  4763. using ClientT = Client;
  4764. #endif
  4765. TestWithHeadersAndContentReceiver<ClientT>(
  4766. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4767. const std::string &body, const std::string &content_type,
  4768. ContentReceiver receiver, DownloadProgress progress) {
  4769. return cli.Put(path, headers, body, content_type, receiver, progress);
  4770. });
  4771. }
  4772. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4774. using ClientT = SSLClient;
  4775. #else
  4776. using ClientT = Client;
  4777. #endif
  4778. TestWithHeadersAndContentReceiver<ClientT>(
  4779. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4780. const std::string &body, const std::string &content_type,
  4781. ContentReceiver receiver, DownloadProgress progress) {
  4782. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4783. });
  4784. }
  4785. template <typename ClientType>
  4786. void TestWithHeadersAndContentReceiverWithProgress(
  4787. ClientType &cli,
  4788. std::function<Result(ClientType &, const std::string &, const Headers &,
  4789. const std::string &, const std::string &,
  4790. ContentReceiver, DownloadProgress)>
  4791. request_func) {
  4792. Headers headers;
  4793. headers.emplace("X-Test-Header", "progress-test");
  4794. std::string received_body;
  4795. auto progress_called = false;
  4796. auto res = request_func(
  4797. cli, "/content_receiver", headers, "content", "text/plain",
  4798. [&](const char *data, size_t data_length) {
  4799. received_body.append(data, data_length);
  4800. return true;
  4801. },
  4802. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4803. progress_called = true;
  4804. return true;
  4805. });
  4806. ASSERT_TRUE(res);
  4807. EXPECT_EQ(StatusCode::OK_200, res->status);
  4808. EXPECT_EQ("content", received_body);
  4809. EXPECT_TRUE(progress_called);
  4810. }
  4811. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4812. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4813. using ClientT = SSLClient;
  4814. #else
  4815. using ClientT = Client;
  4816. #endif
  4817. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4819. const std::string &body, const std::string &content_type,
  4820. ContentReceiver receiver, DownloadProgress progress) {
  4821. return cli.Post(path, headers, body, content_type, receiver, progress);
  4822. });
  4823. }
  4824. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4825. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4826. using ClientT = SSLClient;
  4827. #else
  4828. using ClientT = Client;
  4829. #endif
  4830. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4831. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4832. const std::string &body, const std::string &content_type,
  4833. ContentReceiver receiver, DownloadProgress progress) {
  4834. return cli.Put(path, headers, body, content_type, receiver, progress);
  4835. });
  4836. }
  4837. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4839. using ClientT = SSLClient;
  4840. #else
  4841. using ClientT = Client;
  4842. #endif
  4843. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4844. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4845. const std::string &body, const std::string &content_type,
  4846. ContentReceiver receiver, DownloadProgress progress) {
  4847. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4848. });
  4849. }
  4850. template <typename ClientType>
  4851. void TestWithHeadersAndContentReceiverError(
  4852. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4853. const Headers &, const std::string &,
  4854. const std::string &, ContentReceiver)>
  4855. request_func) {
  4856. Headers headers;
  4857. headers.emplace("X-Error-Test", "true");
  4858. std::string received_body;
  4859. auto receiver_failed = false;
  4860. auto res =
  4861. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4862. [&](const char *data, size_t data_length) {
  4863. received_body.append(data, data_length);
  4864. receiver_failed = true;
  4865. return false;
  4866. });
  4867. ASSERT_FALSE(res);
  4868. EXPECT_TRUE(receiver_failed);
  4869. }
  4870. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4871. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4872. using ClientT = SSLClient;
  4873. #else
  4874. using ClientT = Client;
  4875. #endif
  4876. TestWithHeadersAndContentReceiverError<ClientT>(
  4877. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4878. const std::string &body, const std::string &content_type,
  4879. ContentReceiver receiver) {
  4880. return cli.Post(path, headers, body, content_type, receiver);
  4881. });
  4882. }
  4883. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4884. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4885. using ClientT = SSLClient;
  4886. #else
  4887. using ClientT = Client;
  4888. #endif
  4889. TestWithHeadersAndContentReceiverError<ClientT>(
  4890. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4891. const std::string &body, const std::string &content_type,
  4892. ContentReceiver receiver) {
  4893. return cli.Put(path, headers, body, content_type, receiver);
  4894. });
  4895. }
  4896. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  4897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4898. using ClientT = SSLClient;
  4899. #else
  4900. using ClientT = Client;
  4901. #endif
  4902. TestWithHeadersAndContentReceiverError<ClientT>(
  4903. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4904. const std::string &body, const std::string &content_type,
  4905. ContentReceiver receiver) {
  4906. return cli.Patch(path, headers, body, content_type, receiver);
  4907. });
  4908. }
  4909. TEST_F(ServerTest, PostQueryStringAndBody) {
  4910. auto res =
  4911. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  4912. ASSERT_TRUE(res);
  4913. ASSERT_EQ(StatusCode::OK_200, res->status);
  4914. }
  4915. TEST_F(ServerTest, HTTP2Magic) {
  4916. Request req;
  4917. req.method = "PRI";
  4918. req.path = "*";
  4919. req.body = "SM";
  4920. auto res = std::make_shared<Response>();
  4921. auto error = Error::Success;
  4922. auto ret = cli_.send(req, *res, error);
  4923. ASSERT_TRUE(ret);
  4924. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4925. }
  4926. TEST_F(ServerTest, KeepAlive) {
  4927. auto res = cli_.Get("/hi");
  4928. ASSERT_TRUE(res);
  4929. EXPECT_EQ(StatusCode::OK_200, res->status);
  4930. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4931. EXPECT_EQ("Hello World!", res->body);
  4932. res = cli_.Get("/hi");
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4936. EXPECT_EQ("Hello World!", res->body);
  4937. res = cli_.Get("/hi");
  4938. ASSERT_TRUE(res);
  4939. EXPECT_EQ(StatusCode::OK_200, res->status);
  4940. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4941. EXPECT_EQ("Hello World!", res->body);
  4942. res = cli_.Get("/not-exist");
  4943. ASSERT_TRUE(res);
  4944. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4945. res = cli_.Post("/empty", "", "text/plain");
  4946. ASSERT_TRUE(res);
  4947. EXPECT_EQ(StatusCode::OK_200, res->status);
  4948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4949. EXPECT_EQ("empty", res->body);
  4950. EXPECT_EQ("close", res->get_header_value("Connection"));
  4951. res = cli_.Post(
  4952. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  4953. "text/plain");
  4954. ASSERT_TRUE(res);
  4955. EXPECT_EQ(StatusCode::OK_200, res->status);
  4956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4957. EXPECT_EQ("empty", res->body);
  4958. cli_.set_keep_alive(false);
  4959. res = cli_.Get("/last-request");
  4960. ASSERT_TRUE(res);
  4961. EXPECT_EQ(StatusCode::OK_200, res->status);
  4962. EXPECT_EQ("close", res->get_header_value("Connection"));
  4963. }
  4964. TEST_F(ServerTest, TooManyRedirect) {
  4965. cli_.set_follow_location(true);
  4966. auto res = cli_.Get("/redirect/0");
  4967. ASSERT_TRUE(!res);
  4968. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  4969. }
  4970. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  4971. Request req;
  4972. req.method = "FOOBAR";
  4973. req.path = "/hi";
  4974. cli_.set_keep_alive(true);
  4975. auto res = cli_.send(req);
  4976. ASSERT_TRUE(res);
  4977. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4978. EXPECT_EQ("close", res->get_header_value("Connection"));
  4979. EXPECT_FALSE(cli_.is_socket_open());
  4980. }
  4981. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  4982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4983. TEST_F(ServerTest, Gzip) {
  4984. Headers headers;
  4985. headers.emplace("Accept-Encoding", "gzip, deflate");
  4986. auto res = cli_.Get("/compress", headers);
  4987. ASSERT_TRUE(res);
  4988. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  4989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4990. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  4991. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  4992. "7890123456789012345678901234567890",
  4993. res->body);
  4994. EXPECT_EQ(StatusCode::OK_200, res->status);
  4995. }
  4996. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  4997. Headers headers;
  4998. headers.emplace("Accept-Encoding", "");
  4999. auto res = cli_.Get("/compress", headers);
  5000. ASSERT_TRUE(res);
  5001. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5003. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5004. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5005. "7890123456789012345678901234567890",
  5006. res->body);
  5007. EXPECT_EQ(StatusCode::OK_200, res->status);
  5008. }
  5009. TEST_F(ServerTest, GzipWithContentReceiver) {
  5010. Headers headers;
  5011. headers.emplace("Accept-Encoding", "gzip, deflate");
  5012. std::string body;
  5013. auto res = cli_.Get("/compress", headers,
  5014. [&](const char *data, uint64_t data_length) {
  5015. EXPECT_EQ(100U, data_length);
  5016. body.append(data, data_length);
  5017. return true;
  5018. });
  5019. ASSERT_TRUE(res);
  5020. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5022. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5024. "7890123456789012345678901234567890",
  5025. body);
  5026. EXPECT_EQ(StatusCode::OK_200, res->status);
  5027. }
  5028. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5029. Headers headers;
  5030. headers.emplace("Accept-Encoding", "gzip, deflate");
  5031. cli_.set_decompress(false);
  5032. auto res = cli_.Get("/compress", headers);
  5033. ASSERT_TRUE(res);
  5034. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5035. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5036. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5037. EXPECT_EQ(33U, res->body.size());
  5038. EXPECT_EQ(StatusCode::OK_200, res->status);
  5039. }
  5040. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5041. Headers headers;
  5042. headers.emplace("Accept-Encoding", "");
  5043. std::string body;
  5044. auto res = cli_.Get("/compress", headers,
  5045. [&](const char *data, uint64_t data_length) {
  5046. EXPECT_EQ(100U, data_length);
  5047. body.append(data, data_length);
  5048. return true;
  5049. });
  5050. ASSERT_TRUE(res);
  5051. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5053. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5054. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5055. "7890123456789012345678901234567890",
  5056. body);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. }
  5059. TEST_F(ServerTest, NoGzip) {
  5060. Headers headers;
  5061. headers.emplace("Accept-Encoding", "gzip, deflate");
  5062. auto res = cli_.Get("/nocompress", headers);
  5063. ASSERT_TRUE(res);
  5064. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5065. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5066. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5067. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5068. "7890123456789012345678901234567890",
  5069. res->body);
  5070. EXPECT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5073. Headers headers;
  5074. headers.emplace("Accept-Encoding", "gzip, deflate");
  5075. std::string body;
  5076. auto res = cli_.Get("/nocompress", headers,
  5077. [&](const char *data, uint64_t data_length) {
  5078. EXPECT_EQ(100U, data_length);
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. ASSERT_TRUE(res);
  5083. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5084. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5085. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5086. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5087. "7890123456789012345678901234567890",
  5088. body);
  5089. EXPECT_EQ(StatusCode::OK_200, res->status);
  5090. }
  5091. TEST_F(ServerTest, MultipartFormDataGzip) {
  5092. UploadFormDataItems items = {
  5093. {"key1", "test", "", ""},
  5094. {"key2", "--abcdefg123", "", ""},
  5095. };
  5096. cli_.set_compress(true);
  5097. auto res = cli_.Post("/compress-multipart", items);
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. }
  5101. #endif
  5102. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5103. TEST_F(ServerTest, Brotli) {
  5104. Headers headers;
  5105. headers.emplace("Accept-Encoding", "br");
  5106. auto res = cli_.Get("/compress", headers);
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5110. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5112. "7890123456789012345678901234567890",
  5113. res->body);
  5114. EXPECT_EQ(StatusCode::OK_200, res->status);
  5115. }
  5116. #endif
  5117. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5118. TEST_F(ServerTest, Zstd) {
  5119. Headers headers;
  5120. headers.emplace("Accept-Encoding", "zstd");
  5121. auto res = cli_.Get("/compress", headers);
  5122. ASSERT_TRUE(res);
  5123. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5126. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5127. "7890123456789012345678901234567890",
  5128. res->body);
  5129. EXPECT_EQ(StatusCode::OK_200, res->status);
  5130. }
  5131. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5132. Headers headers;
  5133. headers.emplace("Accept-Encoding", "");
  5134. auto res = cli_.Get("/compress", headers);
  5135. ASSERT_TRUE(res);
  5136. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5137. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5138. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5139. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5140. "7890123456789012345678901234567890",
  5141. res->body);
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. }
  5144. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5145. Headers headers;
  5146. headers.emplace("Accept-Encoding", "zstd");
  5147. std::string body;
  5148. auto res = cli_.Get("/compress", headers,
  5149. [&](const char *data, uint64_t data_length) {
  5150. EXPECT_EQ(100U, data_length);
  5151. body.append(data, data_length);
  5152. return true;
  5153. });
  5154. ASSERT_TRUE(res);
  5155. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5157. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5158. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5159. "7890123456789012345678901234567890",
  5160. body);
  5161. EXPECT_EQ(StatusCode::OK_200, res->status);
  5162. }
  5163. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5164. Headers headers;
  5165. headers.emplace("Accept-Encoding", "zstd");
  5166. cli_.set_decompress(false);
  5167. auto res = cli_.Get("/compress", headers);
  5168. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5169. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5170. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5171. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5172. ASSERT_TRUE(res);
  5173. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5176. EXPECT_EQ(StatusCode::OK_200, res->status);
  5177. ASSERT_EQ(26U, res->body.size());
  5178. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5179. 0);
  5180. }
  5181. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5182. Headers headers;
  5183. headers.emplace("Accept-Encoding", "");
  5184. std::string body;
  5185. auto res = cli_.Get("/compress", headers,
  5186. [&](const char *data, uint64_t data_length) {
  5187. EXPECT_EQ(100U, data_length);
  5188. body.append(data, data_length);
  5189. return true;
  5190. });
  5191. ASSERT_TRUE(res);
  5192. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5196. "7890123456789012345678901234567890",
  5197. body);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. }
  5200. TEST_F(ServerTest, NoZstd) {
  5201. Headers headers;
  5202. headers.emplace("Accept-Encoding", "zstd");
  5203. auto res = cli_.Get("/nocompress", headers);
  5204. ASSERT_TRUE(res);
  5205. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5206. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5207. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5208. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5209. "7890123456789012345678901234567890",
  5210. res->body);
  5211. EXPECT_EQ(StatusCode::OK_200, res->status);
  5212. }
  5213. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5214. Headers headers;
  5215. headers.emplace("Accept-Encoding", "zstd");
  5216. std::string body;
  5217. auto res = cli_.Get("/nocompress", headers,
  5218. [&](const char *data, uint64_t data_length) {
  5219. EXPECT_EQ(100U, data_length);
  5220. body.append(data, data_length);
  5221. return true;
  5222. });
  5223. ASSERT_TRUE(res);
  5224. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5225. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5226. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5228. "7890123456789012345678901234567890",
  5229. body);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. }
  5232. // TODO: How to enable zstd ??
  5233. TEST_F(ServerTest, MultipartFormDataZstd) {
  5234. UploadFormDataItems items = {
  5235. {"key1", "test", "", ""},
  5236. {"key2", "--abcdefg123", "", ""},
  5237. };
  5238. Headers headers;
  5239. headers.emplace("Accept-Encoding", "zstd");
  5240. cli_.set_compress(true);
  5241. auto res = cli_.Post("/compress-multipart", headers, items);
  5242. ASSERT_TRUE(res);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. }
  5245. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5246. Headers headers;
  5247. headers.emplace("Accept-Encoding", "zstd");
  5248. cli_.set_compress(true);
  5249. auto res = cli_.Put(
  5250. "/put", headers, 3,
  5251. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5252. sink.os << "PUT";
  5253. return true;
  5254. },
  5255. "text/plain");
  5256. ASSERT_TRUE(res);
  5257. EXPECT_EQ(StatusCode::OK_200, res->status);
  5258. EXPECT_EQ("PUT", res->body);
  5259. }
  5260. // Pre-compression logging tests
  5261. TEST_F(ServerTest, PreCompressionLogging) {
  5262. // Test data for compression (matches the actual /compress endpoint content)
  5263. const std::string test_content =
  5264. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5265. "3456789012345678901234567890";
  5266. // Variables to capture logging data
  5267. std::string pre_compression_body;
  5268. std::string pre_compression_content_type;
  5269. std::string pre_compression_content_encoding;
  5270. std::string post_compression_body;
  5271. std::string post_compression_content_type;
  5272. std::string post_compression_content_encoding;
  5273. // Set up pre-compression logger
  5274. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5275. const Response &res) {
  5276. pre_compression_body = res.body;
  5277. pre_compression_content_type = res.get_header_value("Content-Type");
  5278. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5279. });
  5280. // Set up post-compression logger
  5281. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5282. post_compression_body = res.body;
  5283. post_compression_content_type = res.get_header_value("Content-Type");
  5284. post_compression_content_encoding =
  5285. res.get_header_value("Content-Encoding");
  5286. });
  5287. // Test with gzip compression
  5288. Headers headers;
  5289. headers.emplace("Accept-Encoding", "gzip");
  5290. auto res = cli_.Get("/compress", headers);
  5291. // Verify response was compressed
  5292. ASSERT_TRUE(res);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5295. // Verify pre-compression logger captured uncompressed content
  5296. EXPECT_EQ(test_content, pre_compression_body);
  5297. EXPECT_EQ("text/plain", pre_compression_content_type);
  5298. EXPECT_TRUE(pre_compression_content_encoding
  5299. .empty()); // No encoding header before compression
  5300. // Verify post-compression logger captured compressed content
  5301. EXPECT_NE(test_content,
  5302. post_compression_body); // Should be different after compression
  5303. EXPECT_EQ("text/plain", post_compression_content_type);
  5304. EXPECT_EQ("gzip", post_compression_content_encoding);
  5305. // Verify compressed content is smaller
  5306. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5307. }
  5308. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5309. const std::string test_content =
  5310. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5311. "3456789012345678901234567890";
  5312. std::string pre_compression_body;
  5313. std::string post_compression_body;
  5314. svr_.set_pre_compression_logger(
  5315. [&](const Request & /*req*/, const Response &res) {
  5316. pre_compression_body = res.body;
  5317. });
  5318. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5319. post_compression_body = res.body;
  5320. });
  5321. Headers headers;
  5322. headers.emplace("Accept-Encoding", "br");
  5323. auto res = cli_.Get("/compress", headers);
  5324. ASSERT_TRUE(res);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5327. // Verify pre-compression content is uncompressed
  5328. EXPECT_EQ(test_content, pre_compression_body);
  5329. // Verify post-compression content is compressed
  5330. EXPECT_NE(test_content, post_compression_body);
  5331. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5332. }
  5333. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5334. const std::string test_content =
  5335. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5336. "3456789012345678901234567890";
  5337. std::string pre_compression_body;
  5338. std::string post_compression_body;
  5339. svr_.set_pre_compression_logger(
  5340. [&](const Request & /*req*/, const Response &res) {
  5341. pre_compression_body = res.body;
  5342. });
  5343. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5344. post_compression_body = res.body;
  5345. });
  5346. // Request without compression (use /nocompress endpoint)
  5347. Headers headers;
  5348. auto res = cli_.Get("/nocompress", headers);
  5349. ASSERT_TRUE(res);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5352. // Pre-compression logger should not be called when no compression is applied
  5353. EXPECT_TRUE(
  5354. pre_compression_body.empty()); // Pre-compression logger not called
  5355. EXPECT_EQ(
  5356. test_content,
  5357. post_compression_body); // Post-compression logger captures final content
  5358. }
  5359. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5360. const std::string test_content =
  5361. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5362. "3456789012345678901234567890";
  5363. std::string pre_compression_body;
  5364. bool pre_logger_called = false;
  5365. // Set only pre-compression logger
  5366. svr_.set_pre_compression_logger(
  5367. [&](const Request & /*req*/, const Response &res) {
  5368. pre_compression_body = res.body;
  5369. pre_logger_called = true;
  5370. });
  5371. Headers headers;
  5372. headers.emplace("Accept-Encoding", "gzip");
  5373. auto res = cli_.Get("/compress", headers);
  5374. ASSERT_TRUE(res);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5377. // Verify pre-compression logger was called
  5378. EXPECT_TRUE(pre_logger_called);
  5379. EXPECT_EQ(test_content, pre_compression_body);
  5380. }
  5381. TEST(ZstdDecompressor, ChunkedDecompression) {
  5382. std::string data;
  5383. for (size_t i = 0; i < 32 * 1024; ++i) {
  5384. data.push_back(static_cast<char>('a' + i % 26));
  5385. }
  5386. std::string compressed_data;
  5387. {
  5388. httplib::detail::zstd_compressor compressor;
  5389. bool result = compressor.compress(
  5390. data.data(), data.size(),
  5391. /*last=*/true,
  5392. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5393. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5394. compressed_data_size);
  5395. return true;
  5396. });
  5397. ASSERT_TRUE(result);
  5398. }
  5399. std::string decompressed_data;
  5400. {
  5401. httplib::detail::zstd_decompressor decompressor;
  5402. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5403. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5404. size_t chunk_size = 130;
  5405. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5406. chunk_begin += chunk_size) {
  5407. size_t current_chunk_size =
  5408. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5409. bool result = decompressor.decompress(
  5410. compressed_data.data() + chunk_begin, current_chunk_size,
  5411. [&](const char *decompressed_data_chunk,
  5412. size_t decompressed_data_chunk_size) {
  5413. decompressed_data.insert(decompressed_data.size(),
  5414. decompressed_data_chunk,
  5415. decompressed_data_chunk_size);
  5416. return true;
  5417. });
  5418. ASSERT_TRUE(result);
  5419. }
  5420. }
  5421. ASSERT_EQ(data, decompressed_data);
  5422. }
  5423. TEST(ZstdDecompressor, Decompress) {
  5424. std::string original_text = "Compressed with ZSTD";
  5425. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5426. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5427. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5428. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5429. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5430. std::string decompressed_data;
  5431. {
  5432. httplib::detail::zstd_decompressor decompressor;
  5433. bool result = decompressor.decompress(
  5434. compressed_data.data(), compressed_data.size(),
  5435. [&](const char *decompressed_data_chunk,
  5436. size_t decompressed_data_chunk_size) {
  5437. decompressed_data.insert(decompressed_data.size(),
  5438. decompressed_data_chunk,
  5439. decompressed_data_chunk_size);
  5440. return true;
  5441. });
  5442. ASSERT_TRUE(result);
  5443. }
  5444. ASSERT_EQ(original_text, decompressed_data);
  5445. }
  5446. #endif
  5447. // Sends a raw request to a server listening at HOST:PORT.
  5448. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5449. std::string *resp = nullptr) {
  5450. auto error = Error::Success;
  5451. auto client_sock = detail::create_client_socket(
  5452. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5453. /*connection_timeout_sec=*/5, 0,
  5454. /*read_timeout_sec=*/5, 0,
  5455. /*write_timeout_sec=*/5, 0, std::string(), error);
  5456. if (client_sock == INVALID_SOCKET) { return false; }
  5457. auto ret = detail::process_client_socket(
  5458. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5459. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5460. if (req.size() !=
  5461. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5462. return false;
  5463. }
  5464. char buf[512];
  5465. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5466. while (line_reader.getline()) {
  5467. if (resp) { *resp += line_reader.ptr(); }
  5468. }
  5469. return true;
  5470. });
  5471. detail::close_socket(client_sock);
  5472. return ret;
  5473. }
  5474. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5475. Server svr;
  5476. std::string header_value;
  5477. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5478. header_value = req.get_header_value("foo");
  5479. res.set_content("ok", "text/plain");
  5480. });
  5481. thread t = thread([&] { svr.listen(HOST, PORT); });
  5482. auto se = detail::scope_exit([&] {
  5483. svr.stop();
  5484. t.join();
  5485. ASSERT_FALSE(svr.is_running());
  5486. });
  5487. svr.wait_until_ready();
  5488. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5489. // like characters are not treated the same - use vertical tab and escape.
  5490. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5491. "foo: \t \v bar \x1B\t \r\n"
  5492. "Connection: close\r\n"
  5493. "\r\n";
  5494. std::string res;
  5495. ASSERT_TRUE(send_request(5, req, &res));
  5496. EXPECT_EQ(header_value, "");
  5497. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5498. }
  5499. // Sends a raw request and verifies that there isn't a crash or exception.
  5500. static void test_raw_request(const std::string &req,
  5501. std::string *out = nullptr) {
  5502. Server svr;
  5503. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5504. res.set_content("ok", "text/plain");
  5505. });
  5506. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5507. res.set_content("ok", "text/plain");
  5508. });
  5509. svr.Get("/header_field_value_check",
  5510. [&](const Request & /*req*/, Response &res) {
  5511. res.set_content("ok", "text/plain");
  5512. });
  5513. // Server read timeout must be longer than the client read timeout for the
  5514. // bug to reproduce, probably to force the server to process a request
  5515. // without a trailing blank line.
  5516. const time_t client_read_timeout_sec = 1;
  5517. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5518. bool listen_thread_ok = false;
  5519. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5520. auto se = detail::scope_exit([&] {
  5521. svr.stop();
  5522. t.join();
  5523. ASSERT_FALSE(svr.is_running());
  5524. EXPECT_TRUE(listen_thread_ok);
  5525. });
  5526. svr.wait_until_ready();
  5527. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5528. }
  5529. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5530. // A certain header line causes an exception if the header property is parsed
  5531. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5532. test_raw_request(
  5533. "GET /hi HTTP/1.1\r\n"
  5534. " : "
  5535. " "
  5536. " ");
  5537. }
  5538. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5539. // A certain header line causes an exception if the header property *name* is
  5540. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5541. // greedy matcher and requires backtracking when there are a lot of ":"
  5542. // characters.
  5543. // This occurs with libc++ but not libstdc++.
  5544. test_raw_request(
  5545. "GET /hi HTTP/1.1\r\n"
  5546. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5547. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5548. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5549. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5550. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5551. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5552. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5553. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5554. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5555. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5556. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5557. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5558. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5559. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5560. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5561. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5562. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5563. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5564. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5565. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5566. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5567. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5568. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5569. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5570. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5571. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5572. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5573. "&&&%%%");
  5574. }
  5575. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5576. // Make sure this doesn't crash the server.
  5577. // In a previous version of the header line regex, the "\r" rendered the line
  5578. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5579. // a new position where the leading white space ended and the field value
  5580. // began.
  5581. // The crash occurs with libc++ but not libstdc++.
  5582. test_raw_request("GET /hi HTTP/1.1\r\n"
  5583. "a:" +
  5584. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5585. "\r\n"
  5586. "\r\n");
  5587. }
  5588. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5589. std::string out;
  5590. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5591. "Content-Type: text/plain\r\n"
  5592. "Transfer-Encoding: chunked\r\n"
  5593. "\r\n"
  5594. "nothex\r\n",
  5595. &out);
  5596. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5597. }
  5598. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5599. std::string out;
  5600. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5601. "Content-Type: text/plain\r\n"
  5602. "Transfer-Encoding: chunked\r\n"
  5603. "\r\n"
  5604. "3\r\n"
  5605. "xyz\r\n"
  5606. "NaN\r\n",
  5607. &out);
  5608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5609. }
  5610. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5611. std::string out;
  5612. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5613. "Content-Type: text/plain\r\n"
  5614. "Transfer-Encoding: chunked\r\n"
  5615. "\r\n"
  5616. // Length is too large for 64 bits.
  5617. "1ffffffffffffffff\r\n"
  5618. "xyz\r\n",
  5619. &out);
  5620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5621. }
  5622. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5623. test_raw_request("GET /hi HTTP/1.1\r\n"
  5624. "Content-Type: text/plain\r\n\r");
  5625. }
  5626. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5627. std::string out;
  5628. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5629. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5630. }
  5631. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5632. std::string out;
  5633. std::string request(
  5634. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5635. test_raw_request(request, &out);
  5636. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5637. }
  5638. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5639. std::string out;
  5640. std::string request(
  5641. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5642. test_raw_request(request, &out);
  5643. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5644. }
  5645. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5646. std::string out;
  5647. std::string request(
  5648. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5649. test_raw_request(request, &out);
  5650. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5651. }
  5652. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5653. std::string out;
  5654. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5655. "Test: \r\n\r\n",
  5656. &out);
  5657. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5658. }
  5659. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5660. Server svr;
  5661. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5662. res.set_header("Cache-Control", "no-cache");
  5663. res.set_chunked_content_provider(
  5664. "text/event-stream", [](size_t offset, DataSink &sink) {
  5665. std::string s = "data:";
  5666. s += std::to_string(offset);
  5667. s += "\n\n";
  5668. auto ret = sink.write(s.data(), s.size());
  5669. EXPECT_TRUE(ret);
  5670. std::this_thread::sleep_for(std::chrono::seconds(1));
  5671. return true;
  5672. });
  5673. });
  5674. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5675. svr.wait_until_ready();
  5676. Client client(HOST, PORT);
  5677. const Headers headers = {{"Accept", "text/event-stream"}};
  5678. auto get_thread = std::thread([&client, &headers]() {
  5679. auto res = client.Get(
  5680. "/events", headers,
  5681. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5682. });
  5683. auto se = detail::scope_exit([&] {
  5684. svr.stop();
  5685. get_thread.join();
  5686. listen_thread.join();
  5687. ASSERT_FALSE(svr.is_running());
  5688. });
  5689. // Give GET time to get a few messages.
  5690. std::this_thread::sleep_for(std::chrono::seconds(2));
  5691. }
  5692. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5693. httplib::Server svr;
  5694. svr.Post("/hi",
  5695. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5696. res.status = StatusCode::OK_200;
  5697. });
  5698. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5699. svr.wait_until_ready();
  5700. Client cli(HOST, PORT);
  5701. auto res = cli.Post("/hi", "data", "text/plain");
  5702. ASSERT_TRUE(res);
  5703. EXPECT_EQ(StatusCode::OK_200, res->status);
  5704. svr.stop();
  5705. thread.join();
  5706. ASSERT_FALSE(svr.is_running());
  5707. res = cli.Post("/hi", "data", "text/plain");
  5708. ASSERT_FALSE(res);
  5709. }
  5710. TEST(ServerStopTest, ListenFailure) {
  5711. Server svr;
  5712. auto t = thread([&]() {
  5713. auto ret = svr.listen("????", PORT);
  5714. EXPECT_FALSE(ret);
  5715. });
  5716. svr.wait_until_ready();
  5717. svr.stop();
  5718. t.join();
  5719. }
  5720. TEST(ServerStopTest, Decommision) {
  5721. Server svr;
  5722. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5723. for (int i = 0; i < 4; i++) {
  5724. auto is_even = !(i % 2);
  5725. std::thread t{[&] {
  5726. try {
  5727. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5728. if (is_even) {
  5729. throw std::runtime_error("Some thing that happens to go wrong.");
  5730. }
  5731. svr.listen(HOST, PORT);
  5732. } catch (...) { svr.decommission(); }
  5733. }};
  5734. svr.wait_until_ready();
  5735. // Server is up
  5736. {
  5737. Client cli(HOST, PORT);
  5738. auto res = cli.Get("/hi");
  5739. if (is_even) {
  5740. EXPECT_FALSE(res);
  5741. } else {
  5742. EXPECT_TRUE(res);
  5743. EXPECT_EQ("hi...", res->body);
  5744. }
  5745. }
  5746. svr.stop();
  5747. t.join();
  5748. // Server is down...
  5749. {
  5750. Client cli(HOST, PORT);
  5751. auto res = cli.Get("/hi");
  5752. EXPECT_FALSE(res);
  5753. }
  5754. }
  5755. }
  5756. // Helper function for string body upload progress tests
  5757. template <typename SetupHandler, typename ClientCall>
  5758. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5759. ClientCall &&client_call,
  5760. const string &body) {
  5761. Server svr;
  5762. setup_handler(svr);
  5763. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5764. auto se = detail::scope_exit([&] {
  5765. svr.stop();
  5766. t.join();
  5767. });
  5768. svr.wait_until_ready();
  5769. Client cli(HOST, PORT);
  5770. vector<uint64_t> progress_values;
  5771. bool progress_called = false;
  5772. auto res =
  5773. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5774. progress_values.push_back(current);
  5775. progress_called = true;
  5776. return true;
  5777. });
  5778. ASSERT_TRUE(res);
  5779. EXPECT_EQ(200, res->status);
  5780. EXPECT_TRUE(progress_called);
  5781. }
  5782. TEST(UploadProgressTest, PostStringBodyBasic) {
  5783. TestStringBodyUploadProgress(
  5784. [](Server &svr) {
  5785. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5786. res.set_content("received", "text/plain");
  5787. });
  5788. },
  5789. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5790. return cli.Post("/test", body, "text/plain", progress_callback);
  5791. },
  5792. "test data for upload progress");
  5793. }
  5794. TEST(UploadProgressTest, PutStringBodyBasic) {
  5795. TestStringBodyUploadProgress(
  5796. [](Server &svr) {
  5797. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5798. res.set_content("put received", "text/plain");
  5799. });
  5800. },
  5801. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5802. return cli.Put("/test", body, "text/plain", progress_callback);
  5803. },
  5804. "put test data for upload progress");
  5805. }
  5806. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5807. TestStringBodyUploadProgress(
  5808. [](Server &svr) {
  5809. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5810. res.set_content("patch received", "text/plain");
  5811. });
  5812. },
  5813. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5814. return cli.Patch("/test", body, "text/plain", progress_callback);
  5815. },
  5816. "patch test data for upload progress");
  5817. }
  5818. // Helper function for content provider upload progress tests
  5819. template <typename SetupHandler, typename ClientCall>
  5820. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5821. ClientCall &&client_call) {
  5822. Server svr;
  5823. setup_handler(svr);
  5824. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5825. auto se = detail::scope_exit([&] {
  5826. svr.stop();
  5827. t.join();
  5828. });
  5829. svr.wait_until_ready();
  5830. Client cli(HOST, PORT);
  5831. vector<uint64_t> progress_values;
  5832. auto res =
  5833. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5834. progress_values.push_back(current);
  5835. return true;
  5836. });
  5837. ASSERT_TRUE(res);
  5838. EXPECT_EQ(200, res->status);
  5839. EXPECT_FALSE(progress_values.empty());
  5840. }
  5841. TEST(UploadProgressTest, PostContentProviderProgress) {
  5842. TestContentProviderUploadProgress(
  5843. [](Server &svr) {
  5844. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5845. res.set_content("provider received", "text/plain");
  5846. });
  5847. },
  5848. [](Client &cli, UploadProgress progress_callback) {
  5849. return cli.Post(
  5850. "/test", 10,
  5851. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5852. sink.os << "test data";
  5853. return true;
  5854. },
  5855. "text/plain", progress_callback);
  5856. });
  5857. }
  5858. // Helper function for multipart upload progress tests
  5859. template <typename SetupHandler, typename ClientCall>
  5860. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5861. ClientCall &&client_call,
  5862. const string &endpoint) {
  5863. Server svr;
  5864. setup_handler(svr);
  5865. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5866. auto se = detail::scope_exit([&] {
  5867. svr.stop();
  5868. t.join();
  5869. });
  5870. svr.wait_until_ready();
  5871. Client cli(HOST, PORT);
  5872. vector<uint64_t> progress_values;
  5873. UploadFormDataItems items = {
  5874. {"field1", "value1", "", ""},
  5875. {"field2", "longer value for progress tracking test", "", ""},
  5876. {"file1", "file content data for upload progress", "test.txt",
  5877. "text/plain"}};
  5878. auto res = client_call(cli, endpoint, items,
  5879. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5880. progress_values.push_back(current);
  5881. return true;
  5882. });
  5883. ASSERT_TRUE(res);
  5884. EXPECT_EQ(200, res->status);
  5885. EXPECT_FALSE(progress_values.empty());
  5886. }
  5887. TEST(UploadProgressTest, PostMultipartProgress) {
  5888. TestMultipartUploadProgress(
  5889. [](Server &svr) {
  5890. svr.Post("/multipart", [](const Request &req, Response &res) {
  5891. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  5892. res.set_content("multipart received", "text/plain");
  5893. });
  5894. },
  5895. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  5896. UploadProgress progress_callback) {
  5897. return cli.Post(endpoint, items, progress_callback);
  5898. },
  5899. "/multipart");
  5900. }
  5901. // Helper function for basic download progress tests
  5902. template <typename SetupHandler, typename ClientCall>
  5903. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  5904. ClientCall &&client_call, const string &endpoint,
  5905. size_t expected_content_size) {
  5906. Server svr;
  5907. setup_handler(svr);
  5908. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5909. auto se = detail::scope_exit([&] {
  5910. svr.stop();
  5911. t.join();
  5912. });
  5913. svr.wait_until_ready();
  5914. Client cli(HOST, PORT);
  5915. vector<uint64_t> progress_values;
  5916. auto res = client_call(cli, endpoint,
  5917. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5918. progress_values.push_back(current);
  5919. return true;
  5920. });
  5921. ASSERT_TRUE(res);
  5922. EXPECT_EQ(200, res->status);
  5923. EXPECT_FALSE(progress_values.empty());
  5924. EXPECT_EQ(expected_content_size, res->body.size());
  5925. }
  5926. TEST(DownloadProgressTest, GetBasic) {
  5927. TestBasicDownloadProgress(
  5928. [](Server &svr) {
  5929. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  5930. string content(1000, 'D');
  5931. res.set_content(content, "text/plain");
  5932. });
  5933. },
  5934. [](Client &cli, const string &endpoint,
  5935. DownloadProgress progress_callback) {
  5936. return cli.Get(endpoint, progress_callback);
  5937. },
  5938. "/download", 1000u);
  5939. }
  5940. // Helper function for content receiver download progress tests
  5941. template <typename SetupHandler, typename ClientCall>
  5942. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  5943. ClientCall &&client_call,
  5944. const string &endpoint,
  5945. size_t expected_content_size) {
  5946. Server svr;
  5947. setup_handler(svr);
  5948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5949. auto se = detail::scope_exit([&] {
  5950. svr.stop();
  5951. t.join();
  5952. });
  5953. svr.wait_until_ready();
  5954. Client cli(HOST, PORT);
  5955. vector<uint64_t> progress_values;
  5956. string received_body;
  5957. auto res = client_call(
  5958. cli, endpoint,
  5959. [&](const char *data, size_t data_length) -> bool {
  5960. received_body.append(data, data_length);
  5961. return true;
  5962. },
  5963. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5964. progress_values.push_back(current);
  5965. return true;
  5966. });
  5967. ASSERT_TRUE(res);
  5968. EXPECT_EQ(200, res->status);
  5969. EXPECT_FALSE(progress_values.empty());
  5970. EXPECT_EQ(expected_content_size, received_body.size());
  5971. EXPECT_TRUE(res->body.empty());
  5972. }
  5973. TEST(DownloadProgressTest, GetWithContentReceiver) {
  5974. TestContentReceiverDownloadProgress(
  5975. [](Server &svr) {
  5976. svr.Get("/download-receiver",
  5977. [](const Request & /*req*/, Response &res) {
  5978. string content(2000, 'R');
  5979. res.set_content(content, "text/plain");
  5980. });
  5981. },
  5982. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  5983. DownloadProgress progress_callback) {
  5984. return cli.Get(endpoint, content_receiver, progress_callback);
  5985. },
  5986. "/download-receiver", 2000u);
  5987. }
  5988. TEST(StreamingTest, NoContentLengthStreaming) {
  5989. Server svr;
  5990. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  5991. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  5992. if (offset < 6) {
  5993. sink.os << (offset < 3 ? "a" : "b");
  5994. } else {
  5995. sink.done();
  5996. }
  5997. return true;
  5998. });
  5999. });
  6000. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6001. auto listen_se = detail::scope_exit([&] {
  6002. svr.stop();
  6003. listen_thread.join();
  6004. ASSERT_FALSE(svr.is_running());
  6005. });
  6006. svr.wait_until_ready();
  6007. Client client(HOST, PORT);
  6008. auto get_thread = std::thread([&client]() {
  6009. std::string s;
  6010. auto res =
  6011. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6012. s += std::string(data, len);
  6013. return true;
  6014. });
  6015. ASSERT_TRUE(res);
  6016. EXPECT_EQ(StatusCode::OK_200, res->status);
  6017. EXPECT_EQ("aaabbb", s);
  6018. });
  6019. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6020. // Give GET time to get a few messages.
  6021. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6022. }
  6023. TEST(MountTest, Unmount) {
  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.wait_until_ready();
  6032. Client cli("localhost", PORT);
  6033. svr.set_mount_point("/mount2", "./www2");
  6034. auto res = cli.Get("/");
  6035. ASSERT_TRUE(res);
  6036. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6037. res = cli.Get("/mount2/dir/test.html");
  6038. ASSERT_TRUE(res);
  6039. EXPECT_EQ(StatusCode::OK_200, res->status);
  6040. svr.set_mount_point("/", "./www");
  6041. res = cli.Get("/dir/");
  6042. ASSERT_TRUE(res);
  6043. EXPECT_EQ(StatusCode::OK_200, res->status);
  6044. svr.remove_mount_point("/");
  6045. res = cli.Get("/dir/");
  6046. ASSERT_TRUE(res);
  6047. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6048. svr.remove_mount_point("/mount2");
  6049. res = cli.Get("/mount2/dir/test.html");
  6050. ASSERT_TRUE(res);
  6051. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6052. }
  6053. TEST(MountTest, Redicect) {
  6054. Server svr;
  6055. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6056. auto se = detail::scope_exit([&] {
  6057. svr.stop();
  6058. listen_thread.join();
  6059. ASSERT_FALSE(svr.is_running());
  6060. });
  6061. svr.set_mount_point("/", "./www");
  6062. svr.wait_until_ready();
  6063. Client cli("localhost", PORT);
  6064. auto res = cli.Get("/dir/");
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(StatusCode::OK_200, res->status);
  6067. res = cli.Get("/dir");
  6068. ASSERT_TRUE(res);
  6069. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6070. res = cli.Get("/file");
  6071. ASSERT_TRUE(res);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. res = cli.Get("/file/");
  6074. ASSERT_TRUE(res);
  6075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6076. cli.set_follow_location(true);
  6077. res = cli.Get("/dir");
  6078. ASSERT_TRUE(res);
  6079. EXPECT_EQ(StatusCode::OK_200, res->status);
  6080. }
  6081. TEST(MountTest, MultibytesPathName) {
  6082. Server svr;
  6083. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6084. auto se = detail::scope_exit([&] {
  6085. svr.stop();
  6086. listen_thread.join();
  6087. ASSERT_FALSE(svr.is_running());
  6088. });
  6089. svr.set_mount_point("/", "./www");
  6090. svr.wait_until_ready();
  6091. Client cli("localhost", PORT);
  6092. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6093. ASSERT_TRUE(res);
  6094. EXPECT_EQ(StatusCode::OK_200, res->status);
  6095. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6096. }
  6097. TEST(KeepAliveTest, ReadTimeout) {
  6098. Server svr;
  6099. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6100. std::this_thread::sleep_for(std::chrono::seconds(2));
  6101. res.set_content("a", "text/plain");
  6102. });
  6103. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6104. res.set_content("b", "text/plain");
  6105. });
  6106. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6107. auto se = detail::scope_exit([&] {
  6108. svr.stop();
  6109. listen_thread.join();
  6110. ASSERT_FALSE(svr.is_running());
  6111. });
  6112. svr.wait_until_ready();
  6113. Client cli("localhost", PORT);
  6114. cli.set_keep_alive(true);
  6115. cli.set_read_timeout(std::chrono::seconds(1));
  6116. auto resa = cli.Get("/a");
  6117. ASSERT_FALSE(resa);
  6118. EXPECT_EQ(Error::Read, resa.error());
  6119. auto resb = cli.Get("/b");
  6120. ASSERT_TRUE(resb);
  6121. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6122. EXPECT_EQ("b", resb->body);
  6123. }
  6124. TEST(KeepAliveTest, MaxCount) {
  6125. size_t keep_alive_max_count = 3;
  6126. Server svr;
  6127. svr.set_keep_alive_max_count(keep_alive_max_count);
  6128. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6129. res.set_content("Hello World!", "text/plain");
  6130. });
  6131. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6132. auto se = detail::scope_exit([&] {
  6133. svr.stop();
  6134. listen_thread.join();
  6135. ASSERT_FALSE(svr.is_running());
  6136. });
  6137. svr.wait_until_ready();
  6138. Client cli(HOST, PORT);
  6139. cli.set_keep_alive(true);
  6140. for (size_t i = 0; i < 5; i++) {
  6141. auto result = cli.Get("/hi");
  6142. ASSERT_TRUE(result);
  6143. EXPECT_EQ(StatusCode::OK_200, result->status);
  6144. if (i == keep_alive_max_count - 1) {
  6145. EXPECT_EQ("close", result->get_header_value("Connection"));
  6146. } else {
  6147. EXPECT_FALSE(result->has_header("Connection"));
  6148. }
  6149. }
  6150. }
  6151. TEST(KeepAliveTest, Issue1041) {
  6152. Server svr;
  6153. svr.set_keep_alive_timeout(3);
  6154. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6155. res.set_content("Hello World!", "text/plain");
  6156. });
  6157. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6158. auto se = detail::scope_exit([&] {
  6159. svr.stop();
  6160. listen_thread.join();
  6161. ASSERT_FALSE(svr.is_running());
  6162. });
  6163. svr.wait_until_ready();
  6164. Client cli(HOST, PORT);
  6165. cli.set_keep_alive(true);
  6166. auto result = cli.Get("/hi");
  6167. ASSERT_TRUE(result);
  6168. EXPECT_EQ(StatusCode::OK_200, result->status);
  6169. std::this_thread::sleep_for(std::chrono::seconds(5));
  6170. result = cli.Get("/hi");
  6171. ASSERT_TRUE(result);
  6172. EXPECT_EQ(StatusCode::OK_200, result->status);
  6173. }
  6174. TEST(KeepAliveTest, Issue1959) {
  6175. Server svr;
  6176. svr.set_keep_alive_timeout(5);
  6177. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6178. res.set_content("a", "text/plain");
  6179. });
  6180. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6181. auto se = detail::scope_exit([&] {
  6182. if (!svr.is_running()) return;
  6183. svr.stop();
  6184. listen_thread.join();
  6185. ASSERT_FALSE(svr.is_running());
  6186. });
  6187. svr.wait_until_ready();
  6188. Client cli("localhost", PORT);
  6189. cli.set_keep_alive(true);
  6190. using namespace std::chrono;
  6191. auto start = steady_clock::now();
  6192. cli.Get("/a");
  6193. svr.stop();
  6194. listen_thread.join();
  6195. auto end = steady_clock::now();
  6196. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6197. EXPECT_LT(elapsed, 5000);
  6198. }
  6199. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6200. TEST(KeepAliveTest, SSLClientReconnection) {
  6201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6202. ASSERT_TRUE(svr.is_valid());
  6203. svr.set_keep_alive_timeout(1);
  6204. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6205. res.set_content("Hello World!", "text/plain");
  6206. });
  6207. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6208. auto se = detail::scope_exit([&] {
  6209. svr.stop();
  6210. listen_thread.join();
  6211. ASSERT_FALSE(svr.is_running());
  6212. });
  6213. svr.wait_until_ready();
  6214. SSLClient cli(HOST, PORT);
  6215. cli.enable_server_certificate_verification(false);
  6216. cli.set_keep_alive(true);
  6217. auto result = cli.Get("/hi");
  6218. ASSERT_TRUE(result);
  6219. EXPECT_EQ(StatusCode::OK_200, result->status);
  6220. result = cli.Get("/hi");
  6221. ASSERT_TRUE(result);
  6222. EXPECT_EQ(StatusCode::OK_200, result->status);
  6223. std::this_thread::sleep_for(std::chrono::seconds(2));
  6224. // Recoonect
  6225. result = cli.Get("/hi");
  6226. ASSERT_TRUE(result);
  6227. EXPECT_EQ(StatusCode::OK_200, result->status);
  6228. result = cli.Get("/hi");
  6229. ASSERT_TRUE(result);
  6230. EXPECT_EQ(StatusCode::OK_200, result->status);
  6231. }
  6232. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6234. ASSERT_TRUE(svr.is_valid());
  6235. svr.set_keep_alive_timeout(1);
  6236. std::string content = "reconnect";
  6237. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6238. res.set_content("Hello World!", "text/plain");
  6239. });
  6240. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6241. auto se = detail::scope_exit([&] {
  6242. svr.stop();
  6243. listen_thread.join();
  6244. ASSERT_FALSE(svr.is_running());
  6245. });
  6246. svr.wait_until_ready();
  6247. SSLClient cli(HOST, PORT);
  6248. cli.enable_server_certificate_verification(false);
  6249. cli.set_keep_alive(true);
  6250. auto result = cli.Post(
  6251. "/hi", content.size(),
  6252. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6253. sink.write(content.c_str(), content.size());
  6254. return true;
  6255. },
  6256. "text/plain");
  6257. ASSERT_TRUE(result);
  6258. EXPECT_EQ(200, result->status);
  6259. std::this_thread::sleep_for(std::chrono::seconds(2));
  6260. // Recoonect
  6261. result = cli.Post(
  6262. "/hi", content.size(),
  6263. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6264. sink.write(content.c_str(), content.size());
  6265. return true;
  6266. },
  6267. "text/plain");
  6268. ASSERT_TRUE(result);
  6269. EXPECT_EQ(200, result->status);
  6270. result = cli.Post(
  6271. "/hi", content.size(),
  6272. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6273. sink.write(content.c_str(), content.size());
  6274. return true;
  6275. },
  6276. "text/plain");
  6277. ASSERT_TRUE(result);
  6278. EXPECT_EQ(200, result->status);
  6279. }
  6280. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6281. {
  6282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6283. ASSERT_TRUE(svr.is_valid());
  6284. svr.Get("/sni", [&](const Request &req, Response &res) {
  6285. std::string expected;
  6286. if (req.ssl) {
  6287. if (const char *sni =
  6288. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6289. expected = sni;
  6290. }
  6291. }
  6292. EXPECT_EQ(expected, req.get_param_value("expected"));
  6293. res.set_content("ok", "text/plain");
  6294. });
  6295. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6296. auto se = detail::scope_exit([&] {
  6297. svr.stop();
  6298. listen_thread.join();
  6299. ASSERT_FALSE(svr.is_running());
  6300. });
  6301. svr.wait_until_ready();
  6302. {
  6303. SSLClient cli("localhost", PORT);
  6304. cli.enable_server_certificate_verification(false);
  6305. auto res = cli.Get("/sni?expected=localhost");
  6306. ASSERT_TRUE(res);
  6307. }
  6308. {
  6309. SSLClient cli("::1", PORT);
  6310. cli.enable_server_certificate_verification(false);
  6311. auto res = cli.Get("/sni?expected=");
  6312. ASSERT_TRUE(res);
  6313. }
  6314. }
  6315. }
  6316. #endif
  6317. TEST(ClientProblemDetectionTest, ContentProvider) {
  6318. Server svr;
  6319. size_t content_length = 1024 * 1024;
  6320. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6321. res.set_content_provider(
  6322. content_length, "text/plain",
  6323. [&](size_t offset, size_t length, DataSink &sink) {
  6324. auto out_len = std::min(length, static_cast<size_t>(1024));
  6325. std::string out(out_len, '@');
  6326. sink.write(out.data(), out_len);
  6327. return offset < 4096;
  6328. },
  6329. [](bool success) { ASSERT_FALSE(success); });
  6330. });
  6331. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6332. res.set_content_provider(
  6333. 0, "text/plain",
  6334. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6335. EXPECT_TRUE(false);
  6336. return true;
  6337. },
  6338. [](bool success) { ASSERT_FALSE(success); });
  6339. });
  6340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. listen_thread.join();
  6344. ASSERT_FALSE(svr.is_running());
  6345. });
  6346. svr.wait_until_ready();
  6347. Client cli("localhost", PORT);
  6348. {
  6349. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6350. size_t /*data_length*/) { return false; });
  6351. ASSERT_FALSE(res);
  6352. }
  6353. {
  6354. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6355. size_t /*data_length*/) { return false; });
  6356. ASSERT_TRUE(res);
  6357. }
  6358. }
  6359. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6360. Server svr;
  6361. svr.set_error_handler([](Request const &, Response &res) -> void {
  6362. res.set_chunked_content_provider(
  6363. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6364. sink.os << "hello";
  6365. sink.os << "world";
  6366. sink.done();
  6367. return true;
  6368. });
  6369. });
  6370. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6371. auto se = detail::scope_exit([&] {
  6372. svr.stop();
  6373. listen_thread.join();
  6374. ASSERT_FALSE(svr.is_running());
  6375. });
  6376. svr.wait_until_ready();
  6377. Client cli("localhost", PORT);
  6378. auto res = cli.Get("/");
  6379. ASSERT_TRUE(res);
  6380. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6381. EXPECT_EQ("helloworld", res->body);
  6382. }
  6383. TEST(LongPollingTest, ClientCloseDetection) {
  6384. Server svr;
  6385. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6386. res.set_chunked_content_provider(
  6387. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6388. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6389. sink.os << "hello";
  6390. auto count = 10;
  6391. while (count > 0 && sink.is_writable()) {
  6392. this_thread::sleep_for(chrono::milliseconds(10));
  6393. count--;
  6394. }
  6395. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6396. return true;
  6397. });
  6398. });
  6399. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6400. auto se = detail::scope_exit([&] {
  6401. svr.stop();
  6402. listen_thread.join();
  6403. ASSERT_FALSE(svr.is_running());
  6404. });
  6405. svr.wait_until_ready();
  6406. Client cli("localhost", PORT);
  6407. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6408. EXPECT_EQ("hello", string(data, data_length));
  6409. return false; // close the socket immediately.
  6410. });
  6411. ASSERT_FALSE(res);
  6412. }
  6413. TEST(GetWithParametersTest, GetWithParameters) {
  6414. Server svr;
  6415. svr.Get("/", [&](const Request &req, Response &) {
  6416. EXPECT_EQ("world", req.get_param_value("hello"));
  6417. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6418. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6419. });
  6420. svr.Get("/params", [&](const Request &req, Response &) {
  6421. EXPECT_EQ("world", req.get_param_value("hello"));
  6422. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6423. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6424. });
  6425. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6426. EXPECT_EQ("resource-id", req.matches[1]);
  6427. EXPECT_EQ("foo", req.get_param_value("param1"));
  6428. EXPECT_EQ("bar", req.get_param_value("param2"));
  6429. });
  6430. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6431. EXPECT_EQ("user-id", req.path_params.at("id"));
  6432. EXPECT_EQ("foo", req.get_param_value("param1"));
  6433. EXPECT_EQ("bar", req.get_param_value("param2"));
  6434. });
  6435. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6436. auto se = detail::scope_exit([&] {
  6437. svr.stop();
  6438. listen_thread.join();
  6439. ASSERT_FALSE(svr.is_running());
  6440. });
  6441. svr.wait_until_ready();
  6442. {
  6443. Client cli(HOST, PORT);
  6444. Params params;
  6445. params.emplace("hello", "world");
  6446. params.emplace("hello2", "world2");
  6447. params.emplace("hello3", "world3");
  6448. auto res = cli.Get("/", params, Headers{});
  6449. ASSERT_TRUE(res);
  6450. EXPECT_EQ(StatusCode::OK_200, res->status);
  6451. }
  6452. {
  6453. Client cli(HOST, PORT);
  6454. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6455. ASSERT_TRUE(res);
  6456. EXPECT_EQ(StatusCode::OK_200, res->status);
  6457. }
  6458. {
  6459. Client cli(HOST, PORT);
  6460. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6461. ASSERT_TRUE(res);
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. }
  6464. {
  6465. Client cli(HOST, PORT);
  6466. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6467. ASSERT_TRUE(res);
  6468. EXPECT_EQ(StatusCode::OK_200, res->status);
  6469. }
  6470. }
  6471. TEST(GetWithParametersTest, GetWithParameters2) {
  6472. Server svr;
  6473. svr.Get("/", [&](const Request &req, Response &res) {
  6474. auto text = req.get_param_value("hello");
  6475. res.set_content(text, "text/plain");
  6476. });
  6477. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6478. auto se = detail::scope_exit([&] {
  6479. svr.stop();
  6480. listen_thread.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. svr.wait_until_ready();
  6484. Client cli("localhost", PORT);
  6485. Params params;
  6486. params.emplace("hello", "world");
  6487. std::string body;
  6488. auto res = cli.Get("/", params, Headers{},
  6489. [&](const char *data, size_t data_length) {
  6490. body.append(data, data_length);
  6491. return true;
  6492. });
  6493. ASSERT_TRUE(res);
  6494. EXPECT_EQ(StatusCode::OK_200, res->status);
  6495. EXPECT_EQ("world", body);
  6496. }
  6497. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6498. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6499. auto host = "httpbin.org";
  6500. auto path = std::string{"/range/32"};
  6501. #else
  6502. auto host = "nghttp2.org";
  6503. auto path = std::string{"/httpbin/range/32"};
  6504. #endif
  6505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6506. SSLClient cli(host);
  6507. #else
  6508. Client cli(host);
  6509. #endif
  6510. cli.set_default_headers({make_range_header({{1, 10}})});
  6511. cli.set_connection_timeout(5);
  6512. {
  6513. auto res = cli.Get(path);
  6514. ASSERT_TRUE(res);
  6515. EXPECT_EQ("bcdefghijk", res->body);
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. }
  6518. {
  6519. auto res = cli.Get(path);
  6520. ASSERT_TRUE(res);
  6521. EXPECT_EQ("bcdefghijk", res->body);
  6522. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6523. }
  6524. }
  6525. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6526. Server svr;
  6527. svr.set_default_headers({{"Hello", "World"}});
  6528. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6529. res.set_content("ok", "text/plain");
  6530. });
  6531. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6532. auto se = detail::scope_exit([&] {
  6533. svr.stop();
  6534. listen_thread.join();
  6535. ASSERT_FALSE(svr.is_running());
  6536. });
  6537. svr.wait_until_ready();
  6538. Client cli("localhost", PORT);
  6539. auto res = cli.Get("/");
  6540. ASSERT_TRUE(res);
  6541. EXPECT_EQ(StatusCode::OK_200, res->status);
  6542. EXPECT_EQ("ok", res->body);
  6543. EXPECT_EQ("World", res->get_header_value("Hello"));
  6544. }
  6545. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6546. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6548. ASSERT_TRUE(svr.is_valid());
  6549. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6550. std::this_thread::sleep_for(std::chrono::seconds(2));
  6551. res.set_content("a", "text/plain");
  6552. });
  6553. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6554. res.set_content("b", "text/plain");
  6555. });
  6556. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6557. auto se = detail::scope_exit([&] {
  6558. svr.stop();
  6559. listen_thread.join();
  6560. ASSERT_FALSE(svr.is_running());
  6561. });
  6562. svr.wait_until_ready();
  6563. SSLClient cli("localhost", PORT);
  6564. cli.enable_server_certificate_verification(false);
  6565. cli.set_keep_alive(true);
  6566. cli.set_read_timeout(std::chrono::seconds(1));
  6567. auto resa = cli.Get("/a");
  6568. ASSERT_TRUE(!resa);
  6569. EXPECT_EQ(Error::Read, resa.error());
  6570. auto resb = cli.Get("/b");
  6571. ASSERT_TRUE(resb);
  6572. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6573. EXPECT_EQ("b", resb->body);
  6574. }
  6575. #endif
  6576. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6577. protected:
  6578. ServerTestWithAI_PASSIVE()
  6579. : cli_(HOST, PORT)
  6580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6581. ,
  6582. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6583. #endif
  6584. {
  6585. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6586. cli_.enable_server_certificate_verification(false);
  6587. #endif
  6588. }
  6589. virtual void SetUp() {
  6590. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6591. res.set_content("Hello World!", "text/plain");
  6592. });
  6593. t_ = thread(
  6594. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6595. svr_.wait_until_ready();
  6596. }
  6597. virtual void TearDown() {
  6598. svr_.stop();
  6599. t_.join();
  6600. }
  6601. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6602. SSLClient cli_;
  6603. SSLServer svr_;
  6604. #else
  6605. Client cli_;
  6606. Server svr_;
  6607. #endif
  6608. thread t_;
  6609. };
  6610. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6611. auto res = cli_.Get("/hi");
  6612. ASSERT_TRUE(res);
  6613. EXPECT_EQ(StatusCode::OK_200, res->status);
  6614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6615. EXPECT_EQ("Hello World!", res->body);
  6616. }
  6617. class ServerUpDownTest : public ::testing::Test {
  6618. protected:
  6619. ServerUpDownTest() : cli_(HOST, PORT) {}
  6620. virtual void SetUp() {
  6621. t_ = thread([&]() {
  6622. svr_.bind_to_any_port(HOST);
  6623. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6624. ASSERT_TRUE(svr_.listen_after_bind());
  6625. });
  6626. svr_.wait_until_ready();
  6627. }
  6628. virtual void TearDown() {
  6629. svr_.stop();
  6630. t_.join();
  6631. }
  6632. Client cli_;
  6633. Server svr_;
  6634. thread t_;
  6635. };
  6636. TEST_F(ServerUpDownTest, QuickStartStop) {
  6637. // Should not crash, especially when run with
  6638. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6639. }
  6640. class PayloadMaxLengthTest : public ::testing::Test {
  6641. protected:
  6642. PayloadMaxLengthTest()
  6643. : cli_(HOST, PORT)
  6644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6645. ,
  6646. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6647. #endif
  6648. {
  6649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6650. cli_.enable_server_certificate_verification(false);
  6651. #endif
  6652. }
  6653. virtual void SetUp() {
  6654. svr_.set_payload_max_length(8);
  6655. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6656. res.set_content("test", "text/plain");
  6657. });
  6658. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6659. svr_.wait_until_ready();
  6660. }
  6661. virtual void TearDown() {
  6662. svr_.stop();
  6663. t_.join();
  6664. }
  6665. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6666. SSLClient cli_;
  6667. SSLServer svr_;
  6668. #else
  6669. Client cli_;
  6670. Server svr_;
  6671. #endif
  6672. thread t_;
  6673. };
  6674. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6675. auto res = cli_.Post("/test", "123456789", "text/plain");
  6676. ASSERT_TRUE(res);
  6677. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6678. res = cli_.Post("/test", "12345678", "text/plain");
  6679. ASSERT_TRUE(res);
  6680. EXPECT_EQ(StatusCode::OK_200, res->status);
  6681. }
  6682. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6683. // Test chunked encoding with payload exceeding the 8-byte limit
  6684. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6685. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6686. ASSERT_TRUE(res);
  6687. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6688. }
  6689. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6690. // Test chunked encoding with payload within the 8-byte limit
  6691. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6692. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6693. ASSERT_TRUE(res);
  6694. EXPECT_EQ(StatusCode::OK_200, res->status);
  6695. }
  6696. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6697. // Test using send_request to send chunked data exceeding payload limit
  6698. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6699. "Host: " +
  6700. std::string(HOST) + ":" + std::to_string(PORT) +
  6701. "\r\n"
  6702. "Transfer-Encoding: chunked\r\n"
  6703. "Connection: close\r\n"
  6704. "\r\n"
  6705. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6706. "0123456789\r\n"
  6707. "0\r\n" // End chunk
  6708. "\r\n";
  6709. std::string response;
  6710. bool result = send_request(1, chunked_request, &response);
  6711. if (!result) {
  6712. // If send_request fails, it might be because the server closed the
  6713. // connection due to payload limit enforcement, which is acceptable
  6714. SUCCEED()
  6715. << "Server rejected oversized chunked request (connection closed)";
  6716. } else {
  6717. // If we got a response, check if it's an error response or connection was
  6718. // closed early Short response length indicates connection was closed due to
  6719. // payload limit
  6720. if (response.length() <= 10) {
  6721. SUCCEED() << "Server closed connection for oversized chunked request";
  6722. } else {
  6723. // Check for error status codes
  6724. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6725. response.find("Payload Too Large") != std::string::npos ||
  6726. response.find("400") != std::string::npos);
  6727. }
  6728. }
  6729. }
  6730. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6731. // Test request without Content-Length header exceeding payload limit
  6732. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6733. "Host: " +
  6734. std::string(HOST) + ":" +
  6735. std::to_string(PORT) +
  6736. "\r\n"
  6737. "Connection: close\r\n"
  6738. "\r\n";
  6739. // Add payload exceeding the 8-byte limit
  6740. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6741. request_without_content_length += large_payload;
  6742. std::string response;
  6743. bool result = send_request(1, request_without_content_length, &response);
  6744. if (!result) {
  6745. // If send_request fails, server likely closed connection due to payload
  6746. // limit
  6747. SUCCEED() << "Server rejected oversized request without Content-Length "
  6748. "(connection closed)";
  6749. } else {
  6750. // Check if server responded with error or closed connection early
  6751. if (response.length() <= 10) {
  6752. SUCCEED() << "Server closed connection for oversized request without "
  6753. "Content-Length";
  6754. } else {
  6755. // Check for error status codes
  6756. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6757. response.find("Payload Too Large") != std::string::npos ||
  6758. response.find("400") != std::string::npos);
  6759. }
  6760. }
  6761. }
  6762. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6763. // Test request without Content-Length header within payload limit
  6764. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6765. "Host: " +
  6766. std::string(HOST) + ":" +
  6767. std::to_string(PORT) +
  6768. "\r\n"
  6769. "Connection: close\r\n"
  6770. "\r\n";
  6771. // Add payload within the 8-byte limit
  6772. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6773. request_without_content_length += small_payload;
  6774. std::string response;
  6775. bool result = send_request(1, request_without_content_length, &response);
  6776. // For requests without Content-Length, the server may have different behavior
  6777. // The key is that it should not reject due to payload limit for small
  6778. // payloads
  6779. if (result) {
  6780. // Check for any HTTP response (success or error, but not connection closed)
  6781. if (response.length() > 10) {
  6782. SUCCEED()
  6783. << "Server processed request without Content-Length within limit";
  6784. } else {
  6785. // Short response might indicate connection closed, which is acceptable
  6786. SUCCEED() << "Server closed connection for request without "
  6787. "Content-Length (acceptable behavior)";
  6788. }
  6789. } else {
  6790. // Connection failure might be due to protocol requirements
  6791. SUCCEED() << "Connection issue with request without Content-Length "
  6792. "(environment-specific)";
  6793. }
  6794. }
  6795. class LargePayloadMaxLengthTest : public ::testing::Test {
  6796. protected:
  6797. LargePayloadMaxLengthTest()
  6798. : cli_(HOST, PORT)
  6799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6800. ,
  6801. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6802. #endif
  6803. {
  6804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6805. cli_.enable_server_certificate_verification(false);
  6806. #endif
  6807. }
  6808. virtual void SetUp() {
  6809. // Set 10MB payload limit
  6810. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6811. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6812. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6813. res.set_content("Large payload test", "text/plain");
  6814. });
  6815. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6816. svr_.wait_until_ready();
  6817. }
  6818. virtual void TearDown() {
  6819. svr_.stop();
  6820. t_.join();
  6821. }
  6822. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6823. SSLClient cli_;
  6824. SSLServer svr_;
  6825. #else
  6826. Client cli_;
  6827. Server svr_;
  6828. #endif
  6829. thread t_;
  6830. };
  6831. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6832. // Test chunked encoding with payload within 10MB limit
  6833. std::string medium_payload(5 * 1024 * 1024,
  6834. 'A'); // 5MB payload, within 10MB limit
  6835. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6836. ASSERT_TRUE(res);
  6837. EXPECT_EQ(StatusCode::OK_200, res->status);
  6838. }
  6839. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6840. // Test chunked encoding with payload exceeding 10MB limit
  6841. std::string large_payload(12 * 1024 * 1024,
  6842. 'B'); // 12MB payload, exceeds 10MB limit
  6843. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6844. ASSERT_TRUE(res);
  6845. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6846. }
  6847. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6848. // Test request without Content-Length header within 10MB limit
  6849. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6850. "Host: " +
  6851. std::string(HOST) + ":" +
  6852. std::to_string(PORT) +
  6853. "\r\n"
  6854. "Connection: close\r\n"
  6855. "\r\n";
  6856. // Add 1MB payload (within 10MB limit)
  6857. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6858. request_without_content_length += medium_payload;
  6859. std::string response;
  6860. bool result = send_request(5, request_without_content_length, &response);
  6861. if (result) {
  6862. // Should get a proper HTTP response for payloads within limit
  6863. if (response.length() > 10) {
  6864. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6865. "10MB limit";
  6866. } else {
  6867. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6868. "Content-Length)";
  6869. }
  6870. } else {
  6871. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6872. }
  6873. }
  6874. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6875. // Test request without Content-Length header exceeding 10MB limit
  6876. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6877. "Host: " +
  6878. std::string(HOST) + ":" +
  6879. std::to_string(PORT) +
  6880. "\r\n"
  6881. "Connection: close\r\n"
  6882. "\r\n";
  6883. // Add 12MB payload (exceeds 10MB limit)
  6884. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  6885. request_without_content_length += large_payload;
  6886. std::string response;
  6887. bool result = send_request(10, request_without_content_length, &response);
  6888. if (!result) {
  6889. // Server should close connection due to payload limit
  6890. SUCCEED() << "Server rejected 12MB request without Content-Length "
  6891. "(connection closed)";
  6892. } else {
  6893. // Check for error response
  6894. if (response.length() <= 10) {
  6895. SUCCEED()
  6896. << "Server closed connection for 12MB request exceeding 10MB limit";
  6897. } else {
  6898. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6899. response.find("Payload Too Large") != std::string::npos ||
  6900. response.find("400") != std::string::npos);
  6901. }
  6902. }
  6903. }
  6904. TEST(HostAndPortPropertiesTest, NoSSL) {
  6905. httplib::Client cli("www.google.com", 1234);
  6906. ASSERT_EQ("www.google.com", cli.host());
  6907. ASSERT_EQ(1234, cli.port());
  6908. }
  6909. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  6910. httplib::Client cli("www.google.com:1234");
  6911. ASSERT_EQ("www.google.com", cli.host());
  6912. ASSERT_EQ(1234, cli.port());
  6913. }
  6914. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6915. TEST(HostAndPortPropertiesTest, SSL) {
  6916. httplib::SSLClient cli("www.google.com");
  6917. ASSERT_EQ("www.google.com", cli.host());
  6918. ASSERT_EQ(443, cli.port());
  6919. }
  6920. #endif
  6921. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6922. TEST(SSLClientTest, UpdateCAStore) {
  6923. httplib::SSLClient httplib_client("www.google.com");
  6924. auto ca_store_1 = X509_STORE_new();
  6925. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  6926. nullptr);
  6927. httplib_client.set_ca_cert_store(ca_store_1);
  6928. auto ca_store_2 = X509_STORE_new();
  6929. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  6930. nullptr);
  6931. httplib_client.set_ca_cert_store(ca_store_2);
  6932. }
  6933. TEST(SSLClientTest, ServerNameIndication_Online) {
  6934. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6935. auto host = "httpbin.org";
  6936. auto path = std::string{"/get"};
  6937. #else
  6938. auto host = "nghttp2.org";
  6939. auto path = std::string{"/httpbin/get"};
  6940. #endif
  6941. SSLClient cli(host, 443);
  6942. auto res = cli.Get(path);
  6943. ASSERT_TRUE(res);
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  6947. // Use a site that will cause SSL verification failure due to self-signed cert
  6948. SSLClient cli("self-signed.badssl.com", 443);
  6949. cli.enable_server_certificate_verification(true);
  6950. auto res = cli.Get("/");
  6951. ASSERT_TRUE(!res);
  6952. EXPECT_EQ(Error::SSLServerVerification, res.error());
  6953. // For SSL server verification errors, ssl_error should be 0, only
  6954. // ssl_openssl_error should be set
  6955. EXPECT_EQ(0, res.ssl_error());
  6956. // Verify OpenSSL error is captured for SSLServerVerification
  6957. // This occurs when SSL_get_verify_result() returns a verification failure
  6958. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  6959. res.ssl_openssl_error());
  6960. }
  6961. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  6962. // Use a site where hostname doesn't match the certificate
  6963. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  6964. SSLClient cli("wrong.host.badssl.com", 443);
  6965. cli.enable_server_certificate_verification(true);
  6966. cli.enable_server_hostname_verification(true);
  6967. auto res = cli.Get("/");
  6968. ASSERT_TRUE(!res);
  6969. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  6970. // For SSL hostname verification errors, ssl_error should be 0, only
  6971. // ssl_openssl_error should be set
  6972. EXPECT_EQ(0, res.ssl_error());
  6973. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  6974. // This occurs when verify_host() fails due to hostname mismatch
  6975. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  6976. res.ssl_openssl_error());
  6977. }
  6978. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  6979. Client cli("https://google.com");
  6980. auto res = cli.Get("/");
  6981. ASSERT_TRUE(res);
  6982. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6983. }
  6984. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  6985. SSLClient cli("google.com");
  6986. cli.set_ca_cert_path(CA_CERT_FILE);
  6987. auto res = cli.Get("/");
  6988. ASSERT_TRUE(res);
  6989. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  6990. }
  6991. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  6992. SSLClient cli("google.com");
  6993. cli.enable_server_certificate_verification(true);
  6994. cli.set_ca_cert_path("hello");
  6995. auto res = cli.Get("/");
  6996. ASSERT_TRUE(!res);
  6997. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  6998. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  6999. // should be set
  7000. EXPECT_EQ(0, res.ssl_error());
  7001. // Verify OpenSSL error is captured for SSLLoadingCerts
  7002. // This error occurs when SSL_CTX_load_verify_locations() fails
  7003. // > openssl errstr 0x80000002
  7004. // error:80000002:system library::No such file or directory
  7005. // > openssl errstr 0xA000126
  7006. // error:0A000126:SSL routines::unexpected eof while reading
  7007. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7008. res.ssl_openssl_error() == 0xA000126);
  7009. }
  7010. TEST(SSLClientTest, ServerCertificateVerification4) {
  7011. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7012. ASSERT_TRUE(svr.is_valid());
  7013. svr.Get("/test", [&](const Request &, Response &res) {
  7014. res.set_content("test", "text/plain");
  7015. svr.stop();
  7016. ASSERT_TRUE(true);
  7017. });
  7018. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7019. auto se = detail::scope_exit([&] {
  7020. t.join();
  7021. ASSERT_FALSE(svr.is_running());
  7022. });
  7023. svr.wait_until_ready();
  7024. SSLClient cli("127.0.0.1", PORT);
  7025. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7026. cli.enable_server_certificate_verification(true);
  7027. cli.set_connection_timeout(30);
  7028. auto res = cli.Get("/test");
  7029. ASSERT_TRUE(res);
  7030. ASSERT_EQ(StatusCode::OK_200, res->status);
  7031. }
  7032. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7033. std::string cert;
  7034. read_file(CA_CERT_FILE, cert);
  7035. SSLClient cli("google.com");
  7036. cli.load_ca_cert_store(cert.data(), cert.size());
  7037. const auto res = cli.Get("/");
  7038. ASSERT_TRUE(res);
  7039. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7040. }
  7041. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7042. // clang-format off
  7043. static constexpr char cert[] =
  7044. "GlobalSign Root CA\n"
  7045. "==================\n"
  7046. "-----BEGIN CERTIFICATE-----\n"
  7047. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7048. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7049. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7050. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7051. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7052. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7053. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7054. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7055. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7056. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7057. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7058. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7059. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7060. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7061. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7062. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7063. "-----END CERTIFICATE-----\n";
  7064. // clang-format on
  7065. SSLClient cli("google.com");
  7066. cli.load_ca_cert_store(cert, sizeof(cert));
  7067. const auto res = cli.Get("/");
  7068. ASSERT_TRUE(res);
  7069. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7070. }
  7071. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7072. SSLClient cli("www.youtube.com");
  7073. cli.set_ca_cert_path(CA_CERT_FILE);
  7074. cli.enable_server_certificate_verification(true);
  7075. cli.set_follow_location(true);
  7076. auto res = cli.Get("/");
  7077. ASSERT_TRUE(res);
  7078. ASSERT_EQ(StatusCode::OK_200, res->status);
  7079. }
  7080. TEST(SSLClientTest, Issue2004_Online) {
  7081. Client client("https://google.com");
  7082. client.set_follow_location(true);
  7083. auto res = client.Get("/");
  7084. ASSERT_TRUE(res);
  7085. ASSERT_EQ(StatusCode::OK_200, res->status);
  7086. auto body = res->body;
  7087. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7088. }
  7089. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7090. // Create SSLClient with invalid cert/key to make is_valid() return false
  7091. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7092. "nonexistent_key.pem");
  7093. // is_valid() should be false due to cert loading failure
  7094. ASSERT_FALSE(cli.is_valid());
  7095. auto res = cli.Get("/");
  7096. ASSERT_FALSE(res);
  7097. EXPECT_EQ(Error::SSLConnection, res.error());
  7098. }
  7099. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7100. // Test for Issue #2251: SSL error not properly reported when client cert
  7101. // and key paths are swapped or mismatched
  7102. // This simulates the scenario where user accidentally swaps the cert and key
  7103. // files
  7104. // Using client cert file as private key and vice versa (completely wrong)
  7105. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7106. // Should fail validation due to cert/key mismatch
  7107. ASSERT_FALSE(cli.is_valid());
  7108. // Attempt to make a request should fail with proper error
  7109. auto res = cli.Get("/");
  7110. ASSERT_FALSE(res);
  7111. EXPECT_EQ(Error::SSLConnection, res.error());
  7112. // SSL error should be recorded in the Result object (this is the key fix for
  7113. // Issue #2251)
  7114. auto openssl_error = res.ssl_openssl_error();
  7115. EXPECT_NE(0u, openssl_error);
  7116. }
  7117. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7118. // Another variant: using valid file paths but with mismatched cert/key pair
  7119. // This tests the case where files exist but contain incompatible key material
  7120. // Using client cert with wrong key (cert2 key)
  7121. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7122. // Should fail validation
  7123. ASSERT_FALSE(cli.is_valid());
  7124. auto res = cli.Get("/");
  7125. ASSERT_FALSE(res);
  7126. // Must report error properly, not appear as success
  7127. EXPECT_EQ(Error::SSLConnection, res.error());
  7128. // OpenSSL error should be captured in Result
  7129. EXPECT_NE(0u, res.ssl_openssl_error());
  7130. }
  7131. #if 0
  7132. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7133. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7134. ASSERT_TRUE(cli != nullptr);
  7135. cli->set_address_family(AF_INET6);
  7136. cli->set_interface("en0");
  7137. auto res = cli->Get("/get");
  7138. ASSERT_TRUE(res);
  7139. ASSERT_EQ(StatusCode::OK_200, res->status);
  7140. }
  7141. #endif
  7142. void ClientCertPresent(
  7143. const std::string &client_cert_file,
  7144. const std::string &client_private_key_file,
  7145. const std::string &client_encrypted_private_key_pass = std::string()) {
  7146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7147. CLIENT_CA_CERT_DIR);
  7148. ASSERT_TRUE(svr.is_valid());
  7149. svr.Get("/test", [&](const Request &req, Response &res) {
  7150. res.set_content("test", "text/plain");
  7151. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7152. ASSERT_TRUE(peer_cert != nullptr);
  7153. auto subject_name = X509_get_subject_name(peer_cert);
  7154. ASSERT_TRUE(subject_name != nullptr);
  7155. std::string common_name;
  7156. {
  7157. char name[BUFSIZ];
  7158. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7159. name, sizeof(name));
  7160. common_name.assign(name, static_cast<size_t>(name_len));
  7161. }
  7162. EXPECT_EQ("Common Name", common_name);
  7163. X509_free(peer_cert);
  7164. });
  7165. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7166. auto se = detail::scope_exit([&] {
  7167. svr.stop();
  7168. t.join();
  7169. ASSERT_FALSE(svr.is_running());
  7170. });
  7171. svr.wait_until_ready();
  7172. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7173. client_encrypted_private_key_pass);
  7174. cli.enable_server_certificate_verification(false);
  7175. cli.set_connection_timeout(30);
  7176. auto res = cli.Get("/test");
  7177. ASSERT_TRUE(res);
  7178. ASSERT_EQ(StatusCode::OK_200, res->status);
  7179. }
  7180. TEST(SSLClientServerTest, ClientCertPresent) {
  7181. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7182. }
  7183. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7184. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7185. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7186. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7187. }
  7188. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7189. void MemoryClientCertPresent(
  7190. const std::string &client_cert_file,
  7191. const std::string &client_private_key_file,
  7192. const std::string &client_encrypted_private_key_pass = std::string()) {
  7193. auto f = fopen(SERVER_CERT_FILE, "r+");
  7194. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7195. fclose(f);
  7196. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7197. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7198. fclose(f);
  7199. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7200. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7201. auto client_ca_cert_store = X509_STORE_new();
  7202. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7203. X509_free(client_cert);
  7204. fclose(f);
  7205. f = fopen(client_cert_file.c_str(), "r+");
  7206. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7207. fclose(f);
  7208. f = fopen(client_private_key_file.c_str(), "r+");
  7209. auto client_private_key = PEM_read_PrivateKey(
  7210. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7211. fclose(f);
  7212. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7213. ASSERT_TRUE(svr.is_valid());
  7214. svr.Get("/test", [&](const Request &req, Response &res) {
  7215. res.set_content("test", "text/plain");
  7216. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7217. ASSERT_TRUE(peer_cert != nullptr);
  7218. auto subject_name = X509_get_subject_name(peer_cert);
  7219. ASSERT_TRUE(subject_name != nullptr);
  7220. std::string common_name;
  7221. {
  7222. char name[BUFSIZ];
  7223. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7224. name, sizeof(name));
  7225. common_name.assign(name, static_cast<size_t>(name_len));
  7226. }
  7227. EXPECT_EQ("Common Name", common_name);
  7228. X509_free(peer_cert);
  7229. });
  7230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7231. auto se = detail::scope_exit([&] {
  7232. svr.stop();
  7233. t.join();
  7234. ASSERT_FALSE(svr.is_running());
  7235. });
  7236. svr.wait_until_ready();
  7237. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7238. client_encrypted_private_key_pass);
  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. X509_free(server_cert);
  7245. EVP_PKEY_free(server_private_key);
  7246. X509_free(client_cert);
  7247. EVP_PKEY_free(client_private_key);
  7248. }
  7249. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7250. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7251. }
  7252. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7253. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7254. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7255. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7256. }
  7257. #endif
  7258. TEST(SSLClientServerTest, ClientCertMissing) {
  7259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7260. CLIENT_CA_CERT_DIR);
  7261. ASSERT_TRUE(svr.is_valid());
  7262. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7263. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7264. auto se = detail::scope_exit([&] {
  7265. svr.stop();
  7266. t.join();
  7267. ASSERT_FALSE(svr.is_running());
  7268. });
  7269. svr.wait_until_ready();
  7270. SSLClient cli(HOST, PORT);
  7271. cli.set_connection_timeout(30);
  7272. auto res = cli.Get("/test");
  7273. ASSERT_TRUE(!res);
  7274. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7275. // For SSL server verification errors, ssl_error should be 0, only
  7276. // ssl_openssl_error should be set
  7277. EXPECT_EQ(0, res.ssl_error());
  7278. // Verify OpenSSL error is captured for SSLServerVerification
  7279. // Note: This test may have different error codes depending on the exact
  7280. // verification failure
  7281. EXPECT_NE(0UL, res.ssl_openssl_error());
  7282. }
  7283. TEST(SSLClientServerTest, TrustDirOptional) {
  7284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7285. ASSERT_TRUE(svr.is_valid());
  7286. svr.Get("/test", [&](const Request &, Response &res) {
  7287. res.set_content("test", "text/plain");
  7288. });
  7289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7290. auto se = detail::scope_exit([&] {
  7291. svr.stop();
  7292. t.join();
  7293. ASSERT_FALSE(svr.is_running());
  7294. });
  7295. svr.wait_until_ready();
  7296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7297. cli.enable_server_certificate_verification(false);
  7298. cli.set_connection_timeout(30);
  7299. auto res = cli.Get("/test");
  7300. ASSERT_TRUE(res);
  7301. ASSERT_EQ(StatusCode::OK_200, res->status);
  7302. }
  7303. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7304. class NoListenSSLServer : public SSLServer {
  7305. public:
  7306. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7307. const char *client_ca_cert_file_path,
  7308. const char *client_ca_cert_dir_path = nullptr)
  7309. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7310. client_ca_cert_dir_path),
  7311. stop_(false) {}
  7312. std::atomic_bool stop_;
  7313. private:
  7314. bool process_and_close_socket(socket_t /*sock*/) override {
  7315. // Don't create SSL context
  7316. while (!stop_.load()) {
  7317. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7318. }
  7319. return true;
  7320. }
  7321. };
  7322. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7323. CLIENT_CA_CERT_FILE);
  7324. ASSERT_TRUE(svr.is_valid());
  7325. svr.Get("/test", [&](const Request &, Response &res) {
  7326. res.set_content("test", "text/plain");
  7327. });
  7328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7329. auto se = detail::scope_exit([&] {
  7330. svr.stop_ = true;
  7331. svr.stop();
  7332. t.join();
  7333. ASSERT_FALSE(svr.is_running());
  7334. });
  7335. svr.wait_until_ready();
  7336. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7337. cli.enable_server_certificate_verification(false);
  7338. cli.set_connection_timeout(1);
  7339. auto res = cli.Get("/test");
  7340. ASSERT_TRUE(!res);
  7341. EXPECT_EQ(Error::SSLConnection, res.error());
  7342. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7343. }
  7344. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7345. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7346. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7347. SSL_CTX_set_options(&ssl_ctx,
  7348. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7349. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7350. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7351. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7352. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7353. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7354. "ECDHE-DSS-AES128-SHA256:"
  7355. "ECDHE-RSA-AES256-SHA256:"
  7356. "ECDHE-DSS-AES256-SHA256:";
  7357. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7358. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7359. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7360. SSL_FILETYPE_PEM) != 1) {
  7361. return false;
  7362. }
  7363. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7364. CLIENT_CA_CERT_DIR);
  7365. SSL_CTX_set_verify(
  7366. &ssl_ctx,
  7367. SSL_VERIFY_PEER |
  7368. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7369. nullptr);
  7370. return true;
  7371. };
  7372. SSLServer svr(setup_ssl_ctx_callback);
  7373. ASSERT_TRUE(svr.is_valid());
  7374. svr.Get("/test", [&](const Request &req, Response &res) {
  7375. res.set_content("test", "text/plain");
  7376. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7377. ASSERT_TRUE(peer_cert != nullptr);
  7378. auto subject_name = X509_get_subject_name(peer_cert);
  7379. ASSERT_TRUE(subject_name != nullptr);
  7380. std::string common_name;
  7381. {
  7382. char name[BUFSIZ];
  7383. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7384. name, sizeof(name));
  7385. common_name.assign(name, static_cast<size_t>(name_len));
  7386. }
  7387. EXPECT_EQ("Common Name", common_name);
  7388. X509_free(peer_cert);
  7389. });
  7390. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7391. auto se = detail::scope_exit([&] {
  7392. svr.stop();
  7393. t.join();
  7394. ASSERT_FALSE(svr.is_running());
  7395. });
  7396. svr.wait_until_ready();
  7397. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7398. cli.enable_server_certificate_verification(false);
  7399. cli.set_connection_timeout(30);
  7400. auto res = cli.Get("/test");
  7401. ASSERT_TRUE(res);
  7402. ASSERT_EQ(StatusCode::OK_200, res->status);
  7403. }
  7404. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7405. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7406. ASSERT_TRUE(svr.is_valid());
  7407. // Set up a handler to verify client certificate is present
  7408. bool client_cert_verified = false;
  7409. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7410. // Verify that client certificate was provided
  7411. client_cert_verified = true;
  7412. res.set_content("success", "text/plain");
  7413. });
  7414. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7415. auto se = detail::scope_exit([&] {
  7416. svr.stop();
  7417. t.join();
  7418. ASSERT_FALSE(svr.is_running());
  7419. });
  7420. svr.wait_until_ready();
  7421. // Client with certificate
  7422. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7423. cli.enable_server_certificate_verification(false);
  7424. cli.set_connection_timeout(30);
  7425. auto res = cli.Get("/test");
  7426. ASSERT_TRUE(res);
  7427. ASSERT_EQ(StatusCode::OK_200, res->status);
  7428. ASSERT_TRUE(client_cert_verified);
  7429. EXPECT_EQ("success", res->body);
  7430. }
  7431. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7432. // Test that when client CA cert file is provided,
  7433. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7434. // Create a server with client authentication
  7435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7436. ASSERT_TRUE(svr.is_valid());
  7437. // We can't directly access the SSL_CTX from SSLServer to verify,
  7438. // but we can test that the server properly requests client certificates
  7439. // and accepts valid ones from the specified CA
  7440. bool handler_called = false;
  7441. svr.Get("/test", [&](const Request &req, Response &res) {
  7442. handler_called = true;
  7443. // Verify that a client certificate was provided
  7444. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7445. ASSERT_TRUE(peer_cert != nullptr);
  7446. // Get the issuer name
  7447. auto issuer_name = X509_get_issuer_name(peer_cert);
  7448. ASSERT_TRUE(issuer_name != nullptr);
  7449. char issuer_buf[256];
  7450. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7451. // The client certificate should be issued by our test CA
  7452. std::string issuer_str(issuer_buf);
  7453. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7454. X509_free(peer_cert);
  7455. res.set_content("authenticated", "text/plain");
  7456. });
  7457. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7458. auto se = detail::scope_exit([&] {
  7459. svr.stop();
  7460. t.join();
  7461. ASSERT_FALSE(svr.is_running());
  7462. });
  7463. svr.wait_until_ready();
  7464. // Connect with a client certificate issued by the CA
  7465. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7466. cli.enable_server_certificate_verification(false);
  7467. cli.set_connection_timeout(30);
  7468. auto res = cli.Get("/test");
  7469. ASSERT_TRUE(res);
  7470. ASSERT_EQ(StatusCode::OK_200, res->status);
  7471. ASSERT_TRUE(handler_called);
  7472. EXPECT_EQ("authenticated", res->body);
  7473. }
  7474. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7475. // Test 1: Valid CA file - no error should be recorded
  7476. {
  7477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7478. CLIENT_CA_CERT_FILE);
  7479. ASSERT_TRUE(svr.is_valid());
  7480. // With valid setup, last_ssl_error should be 0
  7481. EXPECT_EQ(0, svr.ssl_last_error());
  7482. }
  7483. // Test 2: Invalid CA file content
  7484. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7485. {
  7486. // Create a temporary file with completely invalid content
  7487. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7488. {
  7489. std::ofstream ofs(temp_invalid_ca);
  7490. ofs << "This is not a certificate file at all\n";
  7491. ofs << "Just plain text content\n";
  7492. }
  7493. // Create server with invalid CA file
  7494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7495. // Clean up temporary file
  7496. std::remove(temp_invalid_ca);
  7497. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7498. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7499. // Note: SSL_CTX_load_verify_locations typically fails first,
  7500. // but our error handling code path is still exercised
  7501. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7502. }
  7503. }
  7504. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7505. // Test SSL server using X509_STORE constructor with client CA certificates
  7506. // This test verifies that Phase 2 implementation correctly extracts CA names
  7507. // from an X509_STORE and sets them in the SSL context
  7508. // Load the CA certificate into memory
  7509. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7510. ASSERT_NE(nullptr, bio);
  7511. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7512. BIO_free(bio);
  7513. ASSERT_NE(nullptr, ca_cert);
  7514. // Create an X509_STORE and add the CA certificate
  7515. auto store = X509_STORE_new();
  7516. ASSERT_NE(nullptr, store);
  7517. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7518. // Load server certificate and private key
  7519. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7520. ASSERT_NE(nullptr, cert_bio);
  7521. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7522. BIO_free(cert_bio);
  7523. ASSERT_NE(nullptr, server_cert);
  7524. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7525. ASSERT_NE(nullptr, key_bio);
  7526. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7527. BIO_free(key_bio);
  7528. ASSERT_NE(nullptr, server_key);
  7529. // Create SSLServer with X509_STORE constructor
  7530. // Note: X509_STORE ownership is transferred to SSL_CTX
  7531. SSLServer svr(server_cert, server_key, store);
  7532. ASSERT_TRUE(svr.is_valid());
  7533. // No SSL error should be recorded for valid setup
  7534. EXPECT_EQ(0, svr.ssl_last_error());
  7535. // Set up server endpoints
  7536. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7537. res.set_content("ok", "text/plain");
  7538. });
  7539. // Start server in a thread
  7540. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7541. svr.wait_until_ready();
  7542. // Connect with client certificate (using constructor with paths)
  7543. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7544. cli.enable_server_certificate_verification(false);
  7545. auto res = cli.Get("/test-x509store");
  7546. ASSERT_TRUE(res);
  7547. EXPECT_EQ(200, res->status);
  7548. EXPECT_EQ("ok", res->body);
  7549. // Clean up
  7550. X509_free(server_cert);
  7551. EVP_PKEY_free(server_key);
  7552. X509_free(ca_cert);
  7553. svr.stop();
  7554. server_thread.join();
  7555. }
  7556. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7557. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7558. // prepare large data
  7559. std::random_device seed_gen;
  7560. std::mt19937 random(seed_gen());
  7561. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7562. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7563. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7564. // server
  7565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7566. ASSERT_TRUE(svr.is_valid());
  7567. svr.Post("/binary", [&](const Request &req, Response &res) {
  7568. EXPECT_EQ(large_size_byte, req.body.size());
  7569. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7570. res.set_content(req.body, "application/octet-stream");
  7571. });
  7572. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7573. auto se = detail::scope_exit([&] {
  7574. svr.stop();
  7575. listen_thread.join();
  7576. ASSERT_FALSE(svr.is_running());
  7577. });
  7578. svr.wait_until_ready();
  7579. // client POST
  7580. SSLClient cli("localhost", PORT);
  7581. cli.enable_server_certificate_verification(false);
  7582. cli.set_read_timeout(std::chrono::seconds(100));
  7583. cli.set_write_timeout(std::chrono::seconds(100));
  7584. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7585. large_size_byte, "application/octet-stream");
  7586. // compare
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. EXPECT_EQ(large_size_byte, res->body.size());
  7589. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7590. }
  7591. #endif
  7592. #ifdef _WIN32
  7593. TEST(CleanupTest, WSACleanup) {
  7594. int ret = WSACleanup();
  7595. ASSERT_EQ(0, ret);
  7596. }
  7597. #endif
  7598. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7599. TEST(NoSSLSupport, SimpleInterface) {
  7600. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7601. }
  7602. #endif
  7603. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7604. TEST(InvalidScheme, SimpleInterface) {
  7605. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7606. }
  7607. #endif
  7608. TEST(NoScheme, SimpleInterface) {
  7609. Client cli("yahoo.com:80");
  7610. ASSERT_TRUE(cli.is_valid());
  7611. }
  7612. TEST(SendAPI, SimpleInterface_Online) {
  7613. Client cli("http://yahoo.com");
  7614. Request req;
  7615. req.method = "GET";
  7616. req.path = "/";
  7617. auto res = cli.send(req);
  7618. ASSERT_TRUE(res);
  7619. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7620. }
  7621. TEST(SendAPI, WithParamsInRequest) {
  7622. Server svr;
  7623. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7624. EXPECT_TRUE(req.has_param("test"));
  7625. EXPECT_EQ("test_value", req.get_param_value("test"));
  7626. });
  7627. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7628. auto se = detail::scope_exit([&] {
  7629. svr.stop();
  7630. t.join();
  7631. ASSERT_FALSE(svr.is_running());
  7632. });
  7633. svr.wait_until_ready();
  7634. Client cli(HOST, PORT);
  7635. {
  7636. Request req;
  7637. req.method = "GET";
  7638. req.path = "/";
  7639. req.params.emplace("test", "test_value");
  7640. auto res = cli.send(req);
  7641. ASSERT_TRUE(res);
  7642. }
  7643. {
  7644. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7645. ASSERT_TRUE(res);
  7646. }
  7647. }
  7648. TEST(ClientImplMethods, GetSocketTest) {
  7649. httplib::Server svr;
  7650. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7651. res.status = StatusCode::OK_200;
  7652. });
  7653. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7654. auto se = detail::scope_exit([&] {
  7655. svr.stop();
  7656. thread.join();
  7657. ASSERT_FALSE(svr.is_running());
  7658. });
  7659. svr.wait_until_ready();
  7660. {
  7661. httplib::Client cli("http://127.0.0.1:3333");
  7662. cli.set_keep_alive(true);
  7663. // Use the behavior of cpp-httplib of opening the connection
  7664. // only when the first request happens. If that changes,
  7665. // this test would be obsolete.
  7666. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7667. // This also implicitly tests the server. But other tests would fail much
  7668. // earlier than this one to be considered.
  7669. auto res = cli.Get("/");
  7670. ASSERT_TRUE(res);
  7671. EXPECT_EQ(StatusCode::OK_200, res->status);
  7672. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7673. }
  7674. }
  7675. // Disabled due to out-of-memory problem on GitHub Actions
  7676. #ifdef _WIN64
  7677. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7678. // allocate content size larger than 2GB in memory
  7679. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7680. char *content = (char *)malloc(content_size);
  7681. ASSERT_TRUE(content);
  7682. Server svr;
  7683. svr.Get("/foo",
  7684. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7685. res.set_content(content, content_size, "application/octet-stream");
  7686. });
  7687. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7688. auto se = detail::scope_exit([&] {
  7689. svr.stop();
  7690. listen_thread.join();
  7691. if (content) free(content);
  7692. ASSERT_FALSE(svr.is_running());
  7693. });
  7694. svr.wait_until_ready();
  7695. Client cli(HOST, PORT);
  7696. auto res = cli.Get("/foo");
  7697. ASSERT_TRUE(res);
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. EXPECT_EQ(content_size, res->body.length());
  7700. }
  7701. #endif
  7702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7703. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7704. Client cli("http://yahoo.com");
  7705. auto res = cli.Get("/");
  7706. ASSERT_TRUE(res);
  7707. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7708. cli.set_follow_location(true);
  7709. res = cli.Get("/");
  7710. ASSERT_TRUE(res);
  7711. EXPECT_EQ(StatusCode::OK_200, res->status);
  7712. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7713. }
  7714. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7715. Client cli("https://yahoo.com");
  7716. auto res = cli.Get("/");
  7717. ASSERT_TRUE(res);
  7718. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7719. cli.set_follow_location(true);
  7720. res = cli.Get("/");
  7721. ASSERT_TRUE(res);
  7722. EXPECT_EQ(StatusCode::OK_200, res->status);
  7723. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7724. }
  7725. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7726. Client cli("https://yahoo.com");
  7727. auto res = cli.Get("/");
  7728. ASSERT_TRUE(res);
  7729. ASSERT_FALSE(!res);
  7730. ASSERT_TRUE(res);
  7731. ASSERT_FALSE(res == nullptr);
  7732. ASSERT_TRUE(res != nullptr);
  7733. EXPECT_EQ(Error::Success, res.error());
  7734. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7735. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7736. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7737. cli.set_follow_location(true);
  7738. res = cli.Get("/");
  7739. ASSERT_TRUE(res);
  7740. EXPECT_EQ(Error::Success, res.error());
  7741. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7742. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7743. EXPECT_EQ(StatusCode::OK_200, res->status);
  7744. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7745. }
  7746. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7747. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7748. Client cli("https://cdnjs.cloudflare.com");
  7749. auto res =
  7750. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7751. ASSERT_TRUE(res);
  7752. EXPECT_EQ(StatusCode::OK_200, res->status);
  7753. EXPECT_EQ(287630U, res->body.size());
  7754. EXPECT_EQ("application/javascript; charset=utf-8",
  7755. res->get_header_value("Content-Type"));
  7756. }
  7757. #endif
  7758. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7759. #undef REDIR_HOST // Silence compiler warning
  7760. #define REDIR_HOST "https://httpbingo.org"
  7761. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7762. Client cli(REDIR_HOST);
  7763. cli.set_follow_location(true);
  7764. auto res =
  7765. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7766. ASSERT_TRUE(res);
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. }
  7769. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7770. Client cli(REDIR_HOST);
  7771. cli.set_follow_location(true);
  7772. Params params;
  7773. params.emplace("url", "http://example.com");
  7774. params.emplace("status_code", "302");
  7775. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7776. ASSERT_TRUE(res);
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. }
  7779. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7780. Client cli(REDIR_HOST);
  7781. cli.set_follow_location(true);
  7782. Params params;
  7783. params.emplace("url", "http://example.com");
  7784. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7785. ASSERT_TRUE(res);
  7786. EXPECT_EQ(StatusCode::OK_200, res->status);
  7787. }
  7788. TEST(HttpToHttpsRedirectTest, CertFile) {
  7789. Server svr;
  7790. ASSERT_TRUE(svr.is_valid());
  7791. svr.Get("/index", [&](const Request &, Response &res) {
  7792. res.set_redirect("https://127.0.0.1:1235/index");
  7793. svr.stop();
  7794. });
  7795. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7796. ASSERT_TRUE(ssl_svr.is_valid());
  7797. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7798. res.set_content("test", "text/plain");
  7799. ssl_svr.stop();
  7800. });
  7801. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7802. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7803. auto se = detail::scope_exit([&] {
  7804. t2.join();
  7805. t.join();
  7806. ASSERT_FALSE(svr.is_running());
  7807. });
  7808. svr.wait_until_ready();
  7809. ssl_svr.wait_until_ready();
  7810. Client cli("127.0.0.1", PORT);
  7811. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7812. cli.enable_server_certificate_verification(true);
  7813. cli.set_follow_location(true);
  7814. cli.set_connection_timeout(30);
  7815. auto res = cli.Get("/index");
  7816. ASSERT_TRUE(res);
  7817. ASSERT_EQ(StatusCode::OK_200, res->status);
  7818. }
  7819. TEST(SSLClientRedirectTest, CertFile) {
  7820. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7821. ASSERT_TRUE(ssl_svr1.is_valid());
  7822. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7823. res.set_redirect("https://127.0.0.1:1235/index");
  7824. ssl_svr1.stop();
  7825. });
  7826. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7827. ASSERT_TRUE(ssl_svr2.is_valid());
  7828. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7829. res.set_content("test", "text/plain");
  7830. ssl_svr2.stop();
  7831. });
  7832. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7833. thread t2 =
  7834. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7835. auto se = detail::scope_exit([&] {
  7836. t2.join();
  7837. t.join();
  7838. ASSERT_FALSE(ssl_svr1.is_running());
  7839. });
  7840. ssl_svr1.wait_until_ready();
  7841. ssl_svr2.wait_until_ready();
  7842. SSLClient cli("127.0.0.1", PORT);
  7843. std::string cert;
  7844. read_file(SERVER_CERT2_FILE, cert);
  7845. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7846. cli.enable_server_certificate_verification(true);
  7847. cli.set_follow_location(true);
  7848. cli.set_connection_timeout(30);
  7849. auto res = cli.Get("/index");
  7850. ASSERT_TRUE(res);
  7851. ASSERT_EQ(StatusCode::OK_200, res->status);
  7852. }
  7853. TEST(MultipartFormDataTest, LargeData) {
  7854. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7855. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7856. const ContentReader &content_reader) {
  7857. if (req.is_multipart_form_data()) {
  7858. std::vector<FormData> items;
  7859. content_reader(
  7860. [&](const FormData &file) {
  7861. items.push_back(file);
  7862. return true;
  7863. },
  7864. [&](const char *data, size_t data_length) {
  7865. items.back().content.append(data, data_length);
  7866. return true;
  7867. });
  7868. EXPECT_TRUE(std::string(items[0].name) == "document");
  7869. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7870. EXPECT_TRUE(items[0].filename == "2MB_data");
  7871. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7872. EXPECT_TRUE(items[1].name == "hello");
  7873. EXPECT_TRUE(items[1].content == "world");
  7874. EXPECT_TRUE(items[1].filename == "");
  7875. EXPECT_TRUE(items[1].content_type == "");
  7876. } else {
  7877. std::string body;
  7878. content_reader([&](const char *data, size_t data_length) {
  7879. body.append(data, data_length);
  7880. return true;
  7881. });
  7882. }
  7883. });
  7884. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  7885. auto se = detail::scope_exit([&] {
  7886. svr.stop();
  7887. t.join();
  7888. ASSERT_FALSE(svr.is_running());
  7889. });
  7890. svr.wait_until_ready();
  7891. {
  7892. std::string data(1024 * 1024 * 2, '.');
  7893. std::stringstream buffer;
  7894. buffer << data;
  7895. Client cli("https://localhost:8080");
  7896. cli.enable_server_certificate_verification(false);
  7897. UploadFormDataItems items{
  7898. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  7899. {"hello", "world", "", ""},
  7900. };
  7901. auto res = cli.Post("/post", items);
  7902. ASSERT_TRUE(res);
  7903. ASSERT_EQ(StatusCode::OK_200, res->status);
  7904. }
  7905. }
  7906. TEST(MultipartFormDataTest, DataProviderItems) {
  7907. std::random_device seed_gen;
  7908. std::mt19937 random(seed_gen());
  7909. std::string rand1;
  7910. rand1.resize(1000);
  7911. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  7912. std::string rand2;
  7913. rand2.resize(3000);
  7914. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  7915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7916. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  7917. const ContentReader &content_reader) {
  7918. ASSERT_FALSE(req.is_multipart_form_data());
  7919. std::string body;
  7920. content_reader([&](const char *data, size_t data_length) {
  7921. body.append(data, data_length);
  7922. return true;
  7923. });
  7924. EXPECT_EQ(body, "");
  7925. });
  7926. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  7927. const ContentReader &content_reader) {
  7928. ASSERT_TRUE(req.is_multipart_form_data());
  7929. std::vector<FormData> items;
  7930. content_reader(
  7931. [&](const FormData &file) {
  7932. items.push_back(file);
  7933. return true;
  7934. },
  7935. [&](const char *data, size_t data_length) {
  7936. items.back().content.append(data, data_length);
  7937. return true;
  7938. });
  7939. ASSERT_TRUE(items.size() == 2);
  7940. EXPECT_EQ(std::string(items[0].name), "name1");
  7941. EXPECT_EQ(items[0].content, "Testing123");
  7942. EXPECT_EQ(items[0].filename, "filename1");
  7943. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7944. EXPECT_EQ(items[1].name, "name2");
  7945. EXPECT_EQ(items[1].content, "Testing456");
  7946. EXPECT_EQ(items[1].filename, "");
  7947. EXPECT_EQ(items[1].content_type, "");
  7948. });
  7949. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  7950. const ContentReader &content_reader) {
  7951. ASSERT_TRUE(req.is_multipart_form_data());
  7952. std::vector<FormData> items;
  7953. content_reader(
  7954. [&](const FormData &file) {
  7955. items.push_back(file);
  7956. return true;
  7957. },
  7958. [&](const char *data, size_t data_length) {
  7959. items.back().content.append(data, data_length);
  7960. return true;
  7961. });
  7962. ASSERT_TRUE(items.size() == 2);
  7963. EXPECT_EQ(items[0].name, "name3");
  7964. EXPECT_EQ(items[0].content, rand1);
  7965. EXPECT_EQ(items[0].filename, "filename3");
  7966. EXPECT_EQ(items[0].content_type, "");
  7967. EXPECT_EQ(items[1].name, "name4");
  7968. EXPECT_EQ(items[1].content, rand2);
  7969. EXPECT_EQ(items[1].filename, "filename4");
  7970. EXPECT_EQ(items[1].content_type, "");
  7971. });
  7972. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  7973. const ContentReader &content_reader) {
  7974. ASSERT_TRUE(req.is_multipart_form_data());
  7975. std::vector<FormData> items;
  7976. content_reader(
  7977. [&](const FormData &file) {
  7978. items.push_back(file);
  7979. return true;
  7980. },
  7981. [&](const char *data, size_t data_length) {
  7982. items.back().content.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(items.size() == 4);
  7986. EXPECT_EQ(std::string(items[0].name), "name1");
  7987. EXPECT_EQ(items[0].content, "Testing123");
  7988. EXPECT_EQ(items[0].filename, "filename1");
  7989. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  7990. EXPECT_EQ(items[1].name, "name2");
  7991. EXPECT_EQ(items[1].content, "Testing456");
  7992. EXPECT_EQ(items[1].filename, "");
  7993. EXPECT_EQ(items[1].content_type, "");
  7994. EXPECT_EQ(items[2].name, "name3");
  7995. EXPECT_EQ(items[2].content, rand1);
  7996. EXPECT_EQ(items[2].filename, "filename3");
  7997. EXPECT_EQ(items[2].content_type, "");
  7998. EXPECT_EQ(items[3].name, "name4");
  7999. EXPECT_EQ(items[3].content, rand2);
  8000. EXPECT_EQ(items[3].filename, "filename4");
  8001. EXPECT_EQ(items[3].content_type, "");
  8002. });
  8003. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8004. auto se = detail::scope_exit([&] {
  8005. svr.stop();
  8006. t.join();
  8007. ASSERT_FALSE(svr.is_running());
  8008. });
  8009. svr.wait_until_ready();
  8010. {
  8011. Client cli("https://localhost:8080");
  8012. cli.enable_server_certificate_verification(false);
  8013. UploadFormDataItems items{
  8014. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8015. {"name2", "Testing456", "", ""}, // not a file
  8016. };
  8017. {
  8018. auto res = cli.Post("/post-none", {}, {}, {});
  8019. ASSERT_TRUE(res);
  8020. ASSERT_EQ(StatusCode::OK_200, res->status);
  8021. }
  8022. FormDataProviderItems providers;
  8023. {
  8024. auto res =
  8025. cli.Post("/post-items", {}, items, providers); // empty providers
  8026. ASSERT_TRUE(res);
  8027. ASSERT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. providers.push_back({"name3",
  8030. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8031. // test the offset is given correctly at each step
  8032. if (!offset)
  8033. sink.os.write(rand1.data(), 30);
  8034. else if (offset == 30)
  8035. sink.os.write(rand1.data() + 30, 300);
  8036. else if (offset == 330)
  8037. sink.os.write(rand1.data() + 330, 670);
  8038. else if (offset == rand1.size())
  8039. sink.done();
  8040. return true;
  8041. },
  8042. "filename3",
  8043. {}});
  8044. providers.push_back({"name4",
  8045. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8046. // test the offset is given correctly at each step
  8047. if (!offset)
  8048. sink.os.write(rand2.data(), 2000);
  8049. else if (offset == 2000)
  8050. sink.os.write(rand2.data() + 2000, 1);
  8051. else if (offset == 2001)
  8052. sink.os.write(rand2.data() + 2001, 999);
  8053. else if (offset == rand2.size())
  8054. sink.done();
  8055. return true;
  8056. },
  8057. "filename4",
  8058. {}});
  8059. {
  8060. auto res = cli.Post("/post-providers", {}, {}, providers);
  8061. ASSERT_TRUE(res);
  8062. ASSERT_EQ(StatusCode::OK_200, res->status);
  8063. }
  8064. {
  8065. auto res = cli.Post("/post-both", {}, items, providers);
  8066. ASSERT_TRUE(res);
  8067. ASSERT_EQ(StatusCode::OK_200, res->status);
  8068. }
  8069. }
  8070. }
  8071. TEST(MultipartFormDataTest, BadHeader) {
  8072. Server svr;
  8073. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8074. res.set_content("ok", "text/plain");
  8075. });
  8076. thread t = thread([&] { svr.listen(HOST, PORT); });
  8077. auto se = detail::scope_exit([&] {
  8078. svr.stop();
  8079. t.join();
  8080. ASSERT_FALSE(svr.is_running());
  8081. });
  8082. svr.wait_until_ready();
  8083. const std::string body =
  8084. "This is the preamble. It is to be ignored, though it\r\n"
  8085. "is a handy place for composition agents to include an\r\n"
  8086. "explanatory note to non-MIME conformant readers.\r\n"
  8087. "\r\n"
  8088. "\r\n"
  8089. "--simple boundary\r\n"
  8090. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8091. ": BAD...\r\n"
  8092. "\r\n"
  8093. "value1\r\n"
  8094. "--simple boundary\r\n"
  8095. "Content-Disposition: form-data; name=\"field2\"; "
  8096. "filename=\"example.txt\"\r\n"
  8097. "\r\n"
  8098. "value2\r\n"
  8099. "--simple boundary--\r\n"
  8100. "This is the epilogue. It is also to be ignored.\r\n";
  8101. std::string content_type =
  8102. R"(multipart/form-data; boundary="simple boundary")";
  8103. Client cli(HOST, PORT);
  8104. auto res = cli.Post("/post", body, content_type.c_str());
  8105. ASSERT_TRUE(res);
  8106. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8107. }
  8108. TEST(MultipartFormDataTest, WithPreamble) {
  8109. Server svr;
  8110. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8111. res.set_content("ok", "text/plain");
  8112. });
  8113. thread t = thread([&] { svr.listen(HOST, PORT); });
  8114. auto se = detail::scope_exit([&] {
  8115. svr.stop();
  8116. t.join();
  8117. ASSERT_FALSE(svr.is_running());
  8118. });
  8119. svr.wait_until_ready();
  8120. const std::string body =
  8121. "This is the preamble. It is to be ignored, though it\r\n"
  8122. "is a handy place for composition agents to include an\r\n"
  8123. "explanatory note to non-MIME conformant readers.\r\n"
  8124. "\r\n"
  8125. "\r\n"
  8126. "--simple boundary\r\n"
  8127. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8128. "\r\n"
  8129. "value1\r\n"
  8130. "--simple boundary\r\n"
  8131. "Content-Disposition: form-data; name=\"field2\"; "
  8132. "filename=\"example.txt\"\r\n"
  8133. "\r\n"
  8134. "value2\r\n"
  8135. "--simple boundary--\r\n"
  8136. "This is the epilogue. It is also to be ignored.\r\n";
  8137. std::string content_type =
  8138. R"(multipart/form-data; boundary="simple boundary")";
  8139. Client cli(HOST, PORT);
  8140. auto res = cli.Post("/post", body, content_type.c_str());
  8141. ASSERT_TRUE(res);
  8142. EXPECT_EQ(StatusCode::OK_200, res->status);
  8143. }
  8144. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8146. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8147. const ContentReader &content_reader) {
  8148. if (req.is_multipart_form_data()) {
  8149. std::vector<FormData> items;
  8150. content_reader(
  8151. [&](const FormData &file) {
  8152. items.push_back(file);
  8153. return true;
  8154. },
  8155. [&](const char *data, size_t data_length) {
  8156. items.back().content.append(data, data_length);
  8157. return true;
  8158. });
  8159. EXPECT_TRUE(std::string(items[0].name) == "document");
  8160. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8161. EXPECT_TRUE(items[0].filename == "2MB_data");
  8162. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8163. EXPECT_TRUE(items[1].name == "hello");
  8164. EXPECT_TRUE(items[1].content == "world");
  8165. EXPECT_TRUE(items[1].filename == "");
  8166. EXPECT_TRUE(items[1].content_type == "");
  8167. } else {
  8168. std::string body;
  8169. content_reader([&](const char *data, size_t data_length) {
  8170. body.append(data, data_length);
  8171. return true;
  8172. });
  8173. }
  8174. });
  8175. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8176. auto se = detail::scope_exit([&] {
  8177. svr.stop();
  8178. t.join();
  8179. ASSERT_FALSE(svr.is_running());
  8180. });
  8181. svr.wait_until_ready();
  8182. {
  8183. std::string data(1024 * 1024 * 2, '.');
  8184. std::stringstream buffer;
  8185. buffer << data;
  8186. Client cli("https://localhost:8080");
  8187. cli.enable_server_certificate_verification(false);
  8188. UploadFormDataItems items{
  8189. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8190. {"hello", "world", "", ""},
  8191. };
  8192. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8193. ASSERT_TRUE(res);
  8194. ASSERT_EQ(StatusCode::OK_200, res->status);
  8195. }
  8196. }
  8197. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8198. std::string data(1024 * 1024 * 2, '&');
  8199. std::stringstream buffer;
  8200. buffer << data;
  8201. Client cli("https://localhost:8080");
  8202. UploadFormDataItems items{
  8203. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8204. {"hello", "world", "", ""},
  8205. };
  8206. for (const char &c : " \t\r\n") {
  8207. auto res =
  8208. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8209. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8210. ASSERT_FALSE(res);
  8211. }
  8212. }
  8213. TEST(MultipartFormDataTest, PutFormData) {
  8214. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8215. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8216. const ContentReader &content_reader) {
  8217. if (req.is_multipart_form_data()) {
  8218. std::vector<FormData> items;
  8219. content_reader(
  8220. [&](const FormData &file) {
  8221. items.push_back(file);
  8222. return true;
  8223. },
  8224. [&](const char *data, size_t data_length) {
  8225. items.back().content.append(data, data_length);
  8226. return true;
  8227. });
  8228. EXPECT_TRUE(std::string(items[0].name) == "document");
  8229. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8230. EXPECT_TRUE(items[0].filename == "2MB_data");
  8231. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8232. EXPECT_TRUE(items[1].name == "hello");
  8233. EXPECT_TRUE(items[1].content == "world");
  8234. EXPECT_TRUE(items[1].filename == "");
  8235. EXPECT_TRUE(items[1].content_type == "");
  8236. } else {
  8237. std::string body;
  8238. content_reader([&](const char *data, size_t data_length) {
  8239. body.append(data, data_length);
  8240. return true;
  8241. });
  8242. }
  8243. });
  8244. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8245. auto se = detail::scope_exit([&] {
  8246. svr.stop();
  8247. t.join();
  8248. ASSERT_FALSE(svr.is_running());
  8249. });
  8250. svr.wait_until_ready();
  8251. {
  8252. std::string data(1024 * 1024 * 2, '&');
  8253. std::stringstream buffer;
  8254. buffer << data;
  8255. Client cli("https://localhost:8080");
  8256. cli.enable_server_certificate_verification(false);
  8257. UploadFormDataItems items{
  8258. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8259. {"hello", "world", "", ""},
  8260. };
  8261. auto res = cli.Put("/put", items);
  8262. ASSERT_TRUE(res);
  8263. ASSERT_EQ(StatusCode::OK_200, res->status);
  8264. }
  8265. }
  8266. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8268. svr.Put("/put_customboundary",
  8269. [&](const Request &req, const Response & /*res*/,
  8270. const ContentReader &content_reader) {
  8271. if (req.is_multipart_form_data()) {
  8272. std::vector<FormData> items;
  8273. content_reader(
  8274. [&](const FormData &file) {
  8275. items.push_back(file);
  8276. return true;
  8277. },
  8278. [&](const char *data, size_t data_length) {
  8279. items.back().content.append(data, data_length);
  8280. return true;
  8281. });
  8282. EXPECT_TRUE(std::string(items[0].name) == "document");
  8283. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8284. EXPECT_TRUE(items[0].filename == "2MB_data");
  8285. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8286. EXPECT_TRUE(items[1].name == "hello");
  8287. EXPECT_TRUE(items[1].content == "world");
  8288. EXPECT_TRUE(items[1].filename == "");
  8289. EXPECT_TRUE(items[1].content_type == "");
  8290. } else {
  8291. std::string body;
  8292. content_reader([&](const char *data, size_t data_length) {
  8293. body.append(data, data_length);
  8294. return true;
  8295. });
  8296. }
  8297. });
  8298. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8299. auto se = detail::scope_exit([&] {
  8300. svr.stop();
  8301. t.join();
  8302. ASSERT_FALSE(svr.is_running());
  8303. });
  8304. svr.wait_until_ready();
  8305. {
  8306. std::string data(1024 * 1024 * 2, '&');
  8307. std::stringstream buffer;
  8308. buffer << data;
  8309. Client cli("https://localhost:8080");
  8310. cli.enable_server_certificate_verification(false);
  8311. UploadFormDataItems items{
  8312. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8313. {"hello", "world", "", ""},
  8314. };
  8315. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8316. ASSERT_TRUE(res);
  8317. ASSERT_EQ(StatusCode::OK_200, res->status);
  8318. }
  8319. }
  8320. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8321. std::string data(1024 * 1024 * 2, '&');
  8322. std::stringstream buffer;
  8323. buffer << data;
  8324. Client cli("https://localhost:8080");
  8325. cli.enable_server_certificate_verification(false);
  8326. UploadFormDataItems items{
  8327. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8328. {"hello", "world", "", ""},
  8329. };
  8330. for (const char &c : " \t\r\n") {
  8331. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8332. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8333. ASSERT_FALSE(res);
  8334. }
  8335. }
  8336. TEST(MultipartFormDataTest, AlternateFilename) {
  8337. auto handled = false;
  8338. Server svr;
  8339. svr.Post("/test", [&](const Request &req, Response &res) {
  8340. ASSERT_EQ(2u, req.form.files.size());
  8341. ASSERT_EQ(1u, req.form.fields.size());
  8342. // Test files
  8343. const auto &file1 = req.form.get_file("file1");
  8344. ASSERT_EQ("file1", file1.name);
  8345. ASSERT_EQ("A.txt", file1.filename);
  8346. ASSERT_EQ("text/plain", file1.content_type);
  8347. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8348. const auto &file2 = req.form.get_file("file2");
  8349. ASSERT_EQ("file2", file2.name);
  8350. ASSERT_EQ("a.html", file2.filename);
  8351. ASSERT_EQ("text/html", file2.content_type);
  8352. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8353. file2.content);
  8354. // Test text field
  8355. const auto &text = req.form.get_field("text");
  8356. ASSERT_EQ("text default", text);
  8357. res.set_content("ok", "text/plain");
  8358. handled = true;
  8359. });
  8360. thread t = thread([&] { svr.listen(HOST, PORT); });
  8361. auto se = detail::scope_exit([&] {
  8362. svr.stop();
  8363. t.join();
  8364. ASSERT_FALSE(svr.is_running());
  8365. ASSERT_TRUE(handled);
  8366. });
  8367. svr.wait_until_ready();
  8368. auto req = "POST /test HTTP/1.1\r\n"
  8369. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8370. "Content-Length: 399\r\n"
  8371. "\r\n"
  8372. "----------\r\n"
  8373. "Content-Disposition: form-data; name=\"text\"\r\n"
  8374. "\r\n"
  8375. "text default\r\n"
  8376. "----------\r\n"
  8377. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8378. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8379. "Content-Type: text/plain\r\n"
  8380. "\r\n"
  8381. "Content of a.txt.\r\n"
  8382. "\r\n"
  8383. "----------\r\n"
  8384. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8385. "\"a.html\"\r\n"
  8386. "Content-Type: text/html\r\n"
  8387. "\r\n"
  8388. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8389. "\r\n"
  8390. "------------\r\n";
  8391. ASSERT_TRUE(send_request(1, req));
  8392. }
  8393. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8394. auto handled = false;
  8395. Server svr;
  8396. svr.Post("/test", [&](const Request &req, Response &) {
  8397. ASSERT_EQ(2u, req.form.fields.size());
  8398. const auto &text1 = req.form.get_field("text1");
  8399. ASSERT_EQ("text1", text1);
  8400. const auto &text2 = req.form.get_field("text2");
  8401. ASSERT_EQ("text2", text2);
  8402. handled = true;
  8403. });
  8404. thread t = thread([&] { svr.listen(HOST, PORT); });
  8405. auto se = detail::scope_exit([&] {
  8406. svr.stop();
  8407. t.join();
  8408. ASSERT_FALSE(svr.is_running());
  8409. ASSERT_TRUE(handled);
  8410. });
  8411. svr.wait_until_ready();
  8412. auto req = "POST /test HTTP/1.1\r\n"
  8413. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8414. "Content-Length: 146\r\n"
  8415. "\r\n----------\r\n"
  8416. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8417. "\r\n"
  8418. "text1"
  8419. "\r\n----------\r\n"
  8420. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8421. "\r\n"
  8422. "text2"
  8423. "\r\n------------";
  8424. std::string response;
  8425. ASSERT_TRUE(send_request(1, req, &response));
  8426. ASSERT_EQ("200", response.substr(9, 3));
  8427. }
  8428. TEST(MultipartFormDataTest, ContentLength) {
  8429. auto handled = false;
  8430. Server svr;
  8431. svr.Post("/test", [&](const Request &req, Response &) {
  8432. ASSERT_EQ(2u, req.form.fields.size());
  8433. const auto &text1 = req.form.get_field("text1");
  8434. ASSERT_EQ("text1", text1);
  8435. const auto &text2 = req.form.get_field("text2");
  8436. ASSERT_EQ("text2", text2);
  8437. handled = true;
  8438. });
  8439. thread t = thread([&] { svr.listen(HOST, PORT); });
  8440. auto se = detail::scope_exit([&] {
  8441. svr.stop();
  8442. t.join();
  8443. ASSERT_FALSE(svr.is_running());
  8444. ASSERT_TRUE(handled);
  8445. });
  8446. svr.wait_until_ready();
  8447. auto req = "POST /test HTTP/1.1\r\n"
  8448. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8449. "Content-Length: 167\r\n"
  8450. "\r\n----------\r\n"
  8451. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8452. "Content-Length: 5\r\n"
  8453. "\r\n"
  8454. "text1"
  8455. "\r\n----------\r\n"
  8456. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8457. "\r\n"
  8458. "text2"
  8459. "\r\n------------\r\n";
  8460. std::string response;
  8461. ASSERT_TRUE(send_request(1, req, &response));
  8462. ASSERT_EQ("200", response.substr(9, 3));
  8463. }
  8464. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8465. auto handled = false;
  8466. Server svr;
  8467. svr.Post("/test", [&](const Request &req, Response &) {
  8468. ASSERT_EQ(2u, req.form.fields.size());
  8469. const auto &text1 = req.form.get_field("text1");
  8470. ASSERT_EQ("text1", text1);
  8471. // TODO: Add header access for text fields if needed
  8472. const auto &text2 = req.form.get_field("text2");
  8473. ASSERT_EQ("text2", text2);
  8474. // TODO: Header access for text fields needs to be implemented
  8475. // auto &headers = it->second.headers;
  8476. // ASSERT_EQ(3U, headers.size());
  8477. // auto custom_header = headers.find("x-whatever");
  8478. // ASSERT_TRUE(custom_header != headers.end());
  8479. // ASSERT_NE("customvalue", custom_header->second);
  8480. // ASSERT_EQ("CustomValue", custom_header->second);
  8481. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8482. handled = true;
  8483. });
  8484. thread t = thread([&] { svr.listen(HOST, PORT); });
  8485. auto se = detail::scope_exit([&] {
  8486. svr.stop();
  8487. t.join();
  8488. ASSERT_FALSE(svr.is_running());
  8489. ASSERT_TRUE(handled);
  8490. });
  8491. svr.wait_until_ready();
  8492. auto req = "POST /test HTTP/1.1\r\n"
  8493. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8494. "Content-Length: 232\r\n"
  8495. "\r\n----------\r\n"
  8496. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8497. "Content-Length: 5\r\n"
  8498. "X-Test: 1\r\n"
  8499. "\r\n"
  8500. "text1"
  8501. "\r\n----------\r\n"
  8502. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8503. "Content-Type: text/plain\r\n"
  8504. "X-Whatever: CustomValue\r\n"
  8505. "\r\n"
  8506. "text2"
  8507. "\r\n------------\r\n"
  8508. "That should be disregarded. Not even read";
  8509. std::string response;
  8510. ASSERT_TRUE(send_request(1, req, &response));
  8511. ASSERT_EQ("200", response.substr(9, 3));
  8512. }
  8513. #endif
  8514. TEST(MultipartFormDataTest, LargeHeader) {
  8515. auto handled = false;
  8516. Server svr;
  8517. svr.Post("/test", [&](const Request &req, Response &) {
  8518. ASSERT_EQ(1u, req.form.fields.size());
  8519. const auto &text = req.form.get_field("name1");
  8520. ASSERT_EQ("text1", text);
  8521. handled = true;
  8522. });
  8523. thread t = thread([&] { svr.listen(HOST, PORT); });
  8524. auto se = detail::scope_exit([&] {
  8525. svr.stop();
  8526. t.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. ASSERT_TRUE(handled);
  8529. });
  8530. svr.wait_until_ready();
  8531. auto boundary = std::string("cpp-httplib-multipart-data");
  8532. std::string content = "--" + boundary +
  8533. "\r\n"
  8534. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8535. "\r\n"
  8536. "text1\r\n"
  8537. "--" +
  8538. boundary + "--\r\n";
  8539. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8540. "Content-Type: multipart/form-data;boundary=" +
  8541. boundary +
  8542. "\r\n"
  8543. "Content-Length: " +
  8544. std::to_string(content.size()) +
  8545. "\r\n"
  8546. "Dummy-Header: ";
  8547. std::string header_suffix = "\r\n"
  8548. "\r\n";
  8549. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8550. size_t header_dummy_size =
  8551. read_buff_size -
  8552. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8553. auto header_dummy = std::string(header_dummy_size, '@');
  8554. auto req = header_prefix + header_dummy + header_suffix + content;
  8555. std::string response;
  8556. ASSERT_TRUE(send_request(1, req, &response));
  8557. ASSERT_EQ("200", response.substr(9, 3));
  8558. }
  8559. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8560. static constexpr unsigned int number_of_tasks{1000000};
  8561. std::atomic_uint count{0};
  8562. std::unique_ptr<TaskQueue> task_queue{
  8563. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8564. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8565. auto queued = task_queue->enqueue(
  8566. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8567. EXPECT_TRUE(queued);
  8568. }
  8569. EXPECT_NO_THROW(task_queue->shutdown());
  8570. EXPECT_EQ(number_of_tasks, count.load());
  8571. }
  8572. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8573. static constexpr unsigned int number_of_tasks{1000000};
  8574. static constexpr unsigned int qlimit{2};
  8575. unsigned int queued_count{0};
  8576. std::atomic_uint count{0};
  8577. std::unique_ptr<TaskQueue> task_queue{
  8578. new ThreadPool{/*num_threads=*/1, qlimit}};
  8579. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8580. if (task_queue->enqueue(
  8581. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8582. queued_count++;
  8583. }
  8584. }
  8585. EXPECT_NO_THROW(task_queue->shutdown());
  8586. EXPECT_EQ(queued_count, count.load());
  8587. EXPECT_TRUE(queued_count <= number_of_tasks);
  8588. EXPECT_TRUE(queued_count >= qlimit);
  8589. }
  8590. TEST(TaskQueueTest, MaxQueuedRequests) {
  8591. static constexpr unsigned int qlimit{3};
  8592. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8593. std::condition_variable sem_cv;
  8594. std::mutex sem_mtx;
  8595. int credits = 0;
  8596. bool queued;
  8597. /* Fill up the queue with tasks that will block until we give them credits to
  8598. * complete. */
  8599. for (unsigned int n = 0; n <= qlimit;) {
  8600. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8601. std::unique_lock<std::mutex> lock(sem_mtx);
  8602. while (credits <= 0) {
  8603. sem_cv.wait(lock);
  8604. }
  8605. /* Consume the credit and signal the test code if they are all gone. */
  8606. if (--credits == 0) { sem_cv.notify_one(); }
  8607. });
  8608. if (n < qlimit) {
  8609. /* The first qlimit enqueues must succeed. */
  8610. EXPECT_TRUE(queued);
  8611. } else {
  8612. /* The last one will succeed only when the worker thread
  8613. * starts and dequeues the first blocking task. Although
  8614. * not necessary for the correctness of this test, we sleep for
  8615. * a short while to avoid busy waiting. */
  8616. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8617. }
  8618. if (queued) { n++; }
  8619. }
  8620. /* Further enqueues must fail since the queue is full. */
  8621. for (auto i = 0; i < 4; i++) {
  8622. queued = task_queue->enqueue([] {});
  8623. EXPECT_FALSE(queued);
  8624. }
  8625. /* Give the credits to allow the previous tasks to complete. */
  8626. {
  8627. std::unique_lock<std::mutex> lock(sem_mtx);
  8628. credits += qlimit + 1;
  8629. }
  8630. sem_cv.notify_all();
  8631. /* Wait for all the credits to be consumed. */
  8632. {
  8633. std::unique_lock<std::mutex> lock(sem_mtx);
  8634. while (credits > 0) {
  8635. sem_cv.wait(lock);
  8636. }
  8637. }
  8638. /* Check that we are able again to enqueue at least qlimit tasks. */
  8639. for (unsigned int i = 0; i < qlimit; i++) {
  8640. queued = task_queue->enqueue([] {});
  8641. EXPECT_TRUE(queued);
  8642. }
  8643. EXPECT_NO_THROW(task_queue->shutdown());
  8644. }
  8645. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8646. Server svr;
  8647. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8648. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8649. });
  8650. svr.Get("/hello", [](const Request &req, Response &res) {
  8651. res.set_content(req.get_param_value("key"), "text/plain");
  8652. });
  8653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. thread.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. });
  8659. svr.wait_until_ready();
  8660. {
  8661. Client cli(HOST, PORT);
  8662. cli.set_follow_location(true);
  8663. auto res = cli.Get("/");
  8664. ASSERT_TRUE(res);
  8665. EXPECT_EQ(StatusCode::OK_200, res->status);
  8666. EXPECT_EQ("val&key2=val2", res->body);
  8667. }
  8668. }
  8669. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8670. Server svr;
  8671. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8672. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8673. });
  8674. svr.Get("/hello", [](const Request &req, Response &res) {
  8675. res.set_content(req.get_param_value("key"), "text/plain");
  8676. });
  8677. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8678. auto se = detail::scope_exit([&] {
  8679. svr.stop();
  8680. thread.join();
  8681. ASSERT_FALSE(svr.is_running());
  8682. });
  8683. svr.wait_until_ready();
  8684. {
  8685. Client cli(HOST, PORT);
  8686. cli.set_follow_location(true);
  8687. auto res = cli.Get("/");
  8688. ASSERT_TRUE(res);
  8689. EXPECT_EQ(StatusCode::OK_200, res->status);
  8690. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8691. }
  8692. }
  8693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8694. TEST(RedirectTest, Issue2185_Online) {
  8695. SSLClient client("github.com");
  8696. client.set_follow_location(true);
  8697. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8698. "Coollab-Windows.zip");
  8699. ASSERT_TRUE(res);
  8700. EXPECT_EQ(StatusCode::OK_200, res->status);
  8701. EXPECT_EQ(9920427U, res->body.size());
  8702. }
  8703. #endif
  8704. TEST(VulnerabilityTest, CRLFInjection) {
  8705. Server svr;
  8706. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8707. res.set_content("Hello 1", "text/plain");
  8708. });
  8709. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8710. res.set_content("Hello 2", "text/plain");
  8711. });
  8712. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8713. res.set_content("Hello 3", "text/plain");
  8714. });
  8715. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8716. res.set_content("Hello 4", "text/plain");
  8717. });
  8718. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8719. for (const auto &x : req.headers) {
  8720. auto key = x.first;
  8721. EXPECT_STRNE("evil", key.c_str());
  8722. }
  8723. });
  8724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8725. auto se = detail::scope_exit([&] {
  8726. svr.stop();
  8727. thread.join();
  8728. ASSERT_FALSE(svr.is_running());
  8729. });
  8730. svr.wait_until_ready();
  8731. {
  8732. Client cli(HOST, PORT);
  8733. cli.Post("/test1", "A=B",
  8734. "application/x-www-form-urlencoded\r\nevil: hello1");
  8735. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8736. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8737. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8738. }
  8739. }
  8740. TEST(PathParamsTest, StaticMatch) {
  8741. const auto pattern = "/users/all";
  8742. detail::PathParamsMatcher matcher(pattern);
  8743. Request request;
  8744. request.path = "/users/all";
  8745. ASSERT_TRUE(matcher.match(request));
  8746. std::unordered_map<std::string, std::string> expected_params = {};
  8747. EXPECT_EQ(request.path_params, expected_params);
  8748. }
  8749. TEST(PathParamsTest, StaticMismatch) {
  8750. const auto pattern = "/users/all";
  8751. detail::PathParamsMatcher matcher(pattern);
  8752. Request request;
  8753. request.path = "/users/1";
  8754. ASSERT_FALSE(matcher.match(request));
  8755. }
  8756. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8757. const auto pattern = "/users/:id/subscriptions";
  8758. detail::PathParamsMatcher matcher(pattern);
  8759. Request request;
  8760. request.path = "/users/42/subscriptions";
  8761. ASSERT_TRUE(matcher.match(request));
  8762. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8763. EXPECT_EQ(request.path_params, expected_params);
  8764. }
  8765. TEST(PathParamsTest, SingleParamInTheEnd) {
  8766. const auto pattern = "/users/:id";
  8767. detail::PathParamsMatcher matcher(pattern);
  8768. Request request;
  8769. request.path = "/users/24";
  8770. ASSERT_TRUE(matcher.match(request));
  8771. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8772. EXPECT_EQ(request.path_params, expected_params);
  8773. }
  8774. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8775. const auto pattern = "/users/:id/";
  8776. detail::PathParamsMatcher matcher(pattern);
  8777. Request request;
  8778. request.path = "/users/42/";
  8779. ASSERT_TRUE(matcher.match(request));
  8780. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8781. EXPECT_EQ(request.path_params, expected_params);
  8782. }
  8783. TEST(PathParamsTest, EmptyParam) {
  8784. const auto pattern = "/users/:id/";
  8785. detail::PathParamsMatcher matcher(pattern);
  8786. Request request;
  8787. request.path = "/users//";
  8788. ASSERT_TRUE(matcher.match(request));
  8789. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8790. EXPECT_EQ(request.path_params, expected_params);
  8791. }
  8792. TEST(PathParamsTest, FragmentMismatch) {
  8793. const auto pattern = "/users/:id/";
  8794. detail::PathParamsMatcher matcher(pattern);
  8795. Request request;
  8796. request.path = "/admins/24/";
  8797. ASSERT_FALSE(matcher.match(request));
  8798. }
  8799. TEST(PathParamsTest, ExtraFragments) {
  8800. const auto pattern = "/users/:id";
  8801. detail::PathParamsMatcher matcher(pattern);
  8802. Request request;
  8803. request.path = "/users/42/subscriptions";
  8804. ASSERT_FALSE(matcher.match(request));
  8805. }
  8806. TEST(PathParamsTest, MissingTrailingParam) {
  8807. const auto pattern = "/users/:id";
  8808. detail::PathParamsMatcher matcher(pattern);
  8809. Request request;
  8810. request.path = "/users";
  8811. ASSERT_FALSE(matcher.match(request));
  8812. }
  8813. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8814. const auto pattern = "/users/:id/subscriptions";
  8815. detail::PathParamsMatcher matcher(pattern);
  8816. Request request;
  8817. request.path = "/users/subscriptions";
  8818. ASSERT_FALSE(matcher.match(request));
  8819. }
  8820. TEST(PathParamsTest, MultipleParams) {
  8821. const auto pattern = "/users/:userid/subscriptions/:subid";
  8822. detail::PathParamsMatcher matcher(pattern);
  8823. Request request;
  8824. request.path = "/users/42/subscriptions/2";
  8825. ASSERT_TRUE(matcher.match(request));
  8826. std::unordered_map<std::string, std::string> expected_params = {
  8827. {"userid", "42"}, {"subid", "2"}};
  8828. EXPECT_EQ(request.path_params, expected_params);
  8829. }
  8830. TEST(PathParamsTest, SequenceOfParams) {
  8831. const auto pattern = "/values/:x/:y/:z";
  8832. detail::PathParamsMatcher matcher(pattern);
  8833. Request request;
  8834. request.path = "/values/1/2/3";
  8835. ASSERT_TRUE(matcher.match(request));
  8836. std::unordered_map<std::string, std::string> expected_params = {
  8837. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8838. EXPECT_EQ(request.path_params, expected_params);
  8839. }
  8840. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8841. const auto pattern = "/prefix:suffix";
  8842. detail::PathParamsMatcher matcher(pattern);
  8843. Request request;
  8844. request.path = "/prefix:suffix";
  8845. ASSERT_TRUE(matcher.match(request));
  8846. const std::unordered_map<std::string, std::string> expected_params = {};
  8847. EXPECT_EQ(request.path_params, expected_params);
  8848. }
  8849. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8850. // If ipv6 regex working, regex match codepath is taken.
  8851. // else port will default to 80 in Client impl
  8852. int clientImplMagicPort = 80;
  8853. int port = 4321;
  8854. // above ports must be different to avoid false negative
  8855. EXPECT_NE(clientImplMagicPort, port);
  8856. std::string ipV6TestURL = "http://[ff06::c3]";
  8857. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8858. CLIENT_PRIVATE_KEY_FILE);
  8859. EXPECT_EQ(cli.port(), port);
  8860. }
  8861. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8862. auto file_path = "./www/dir/index.html";
  8863. auto dir_path = "./www/dir";
  8864. detail::FileStat stat_file(file_path);
  8865. EXPECT_TRUE(stat_file.is_file());
  8866. EXPECT_FALSE(stat_file.is_dir());
  8867. detail::FileStat stat_dir(dir_path);
  8868. EXPECT_FALSE(stat_dir.is_file());
  8869. EXPECT_TRUE(stat_dir.is_dir());
  8870. }
  8871. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8872. // IPv4 with default HTTP port (80)
  8873. EXPECT_EQ("example.com",
  8874. detail::make_host_and_port_string("example.com", 80, false));
  8875. // IPv4 with default HTTPS port (443)
  8876. EXPECT_EQ("example.com",
  8877. detail::make_host_and_port_string("example.com", 443, true));
  8878. // IPv4 with non-default HTTP port
  8879. EXPECT_EQ("example.com:8080",
  8880. detail::make_host_and_port_string("example.com", 8080, false));
  8881. // IPv4 with non-default HTTPS port
  8882. EXPECT_EQ("example.com:8443",
  8883. detail::make_host_and_port_string("example.com", 8443, true));
  8884. // IPv6 with default HTTP port (80)
  8885. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  8886. // IPv6 with default HTTPS port (443)
  8887. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  8888. // IPv6 with non-default HTTP port
  8889. EXPECT_EQ("[::1]:8080",
  8890. detail::make_host_and_port_string("::1", 8080, false));
  8891. // IPv6 with non-default HTTPS port
  8892. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  8893. // IPv6 full address with default port
  8894. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  8895. detail::make_host_and_port_string(
  8896. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  8897. // IPv6 full address with non-default port
  8898. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  8899. detail::make_host_and_port_string(
  8900. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  8901. // IPv6 localhost with non-default port
  8902. EXPECT_EQ("[::1]:3000",
  8903. detail::make_host_and_port_string("::1", 3000, false));
  8904. // IPv6 with zone ID (link-local address) with default port
  8905. EXPECT_EQ("[fe80::1%eth0]",
  8906. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  8907. // IPv6 with zone ID (link-local address) with non-default port
  8908. EXPECT_EQ("[fe80::1%eth0]:8080",
  8909. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  8910. // Edge case: Port 443 with is_ssl=false (should add port)
  8911. EXPECT_EQ("example.com:443",
  8912. detail::make_host_and_port_string("example.com", 443, false));
  8913. // Edge case: Port 80 with is_ssl=true (should add port)
  8914. EXPECT_EQ("example.com:80",
  8915. detail::make_host_and_port_string("example.com", 80, true));
  8916. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  8917. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  8918. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  8919. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  8920. // Security fix: Already bracketed IPv6 should not get double brackets
  8921. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  8922. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  8923. EXPECT_EQ("[::1]:8080",
  8924. detail::make_host_and_port_string("[::1]", 8080, false));
  8925. EXPECT_EQ("[2001:db8::1]:8080",
  8926. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  8927. EXPECT_EQ("[fe80::1%eth0]",
  8928. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  8929. EXPECT_EQ("[fe80::1%eth0]:8080",
  8930. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  8931. // Edge case: Empty host (should return as-is)
  8932. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  8933. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  8934. // This is a known limitation but shouldn't crash
  8935. EXPECT_EQ("[host:name]",
  8936. detail::make_host_and_port_string("host:name", 80, false));
  8937. // Port number edge cases (no validation, but should not crash)
  8938. EXPECT_EQ("example.com:0",
  8939. detail::make_host_and_port_string("example.com", 0, false));
  8940. EXPECT_EQ("example.com:-1",
  8941. detail::make_host_and_port_string("example.com", -1, false));
  8942. EXPECT_EQ("example.com:65535",
  8943. detail::make_host_and_port_string("example.com", 65535, false));
  8944. EXPECT_EQ("example.com:65536",
  8945. detail::make_host_and_port_string("example.com", 65536, false));
  8946. }
  8947. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  8948. Server svr;
  8949. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  8950. EXPECT_EQ(res.status, 400);
  8951. });
  8952. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8953. auto se = detail::scope_exit([&] {
  8954. svr.stop();
  8955. thread.join();
  8956. ASSERT_FALSE(svr.is_running());
  8957. });
  8958. svr.wait_until_ready();
  8959. Client cli(HOST, PORT);
  8960. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  8961. }
  8962. TEST(InvalidHeaderCharsTest, is_field_name) {
  8963. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  8964. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  8965. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  8966. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  8967. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  8968. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  8969. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  8970. EXPECT_FALSE(detail::fields::is_field_name(""));
  8971. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  8972. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  8973. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  8974. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  8975. }
  8976. TEST(InvalidHeaderCharsTest, is_field_value) {
  8977. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  8978. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  8979. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  8980. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  8981. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  8982. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  8983. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  8984. EXPECT_TRUE(detail::fields::is_field_value(""));
  8985. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  8986. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  8987. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  8988. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  8989. EXPECT_TRUE(detail::fields::is_field_value("0"));
  8990. }
  8991. TEST(InvalidHeaderCharsTest, OnServer) {
  8992. Server svr;
  8993. svr.Get("/test_name", [&](const Request &req, Response &res) {
  8994. std::string header = "Not Set";
  8995. if (req.has_param("header")) { header = req.get_param_value("header"); }
  8996. res.set_header(header, "value");
  8997. res.set_content("Page Content Page Content", "text/plain");
  8998. });
  8999. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9000. std::string header = "Not Set";
  9001. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9002. res.set_header("X-Test", header);
  9003. res.set_content("Page Content Page Content", "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. Client cli(HOST, PORT);
  9013. {
  9014. auto res = cli.Get(
  9015. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9016. ASSERT_TRUE(res);
  9017. EXPECT_EQ("Page Content Page Content", res->body);
  9018. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9019. }
  9020. {
  9021. auto res = cli.Get(
  9022. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9023. ASSERT_TRUE(res);
  9024. EXPECT_EQ("Page Content Page Content", res->body);
  9025. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9026. }
  9027. }
  9028. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9029. auto handled = false;
  9030. Server svr;
  9031. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9032. thread t = thread([&] { svr.listen(HOST, PORT); });
  9033. auto se = detail::scope_exit([&] {
  9034. svr.stop();
  9035. t.join();
  9036. ASSERT_FALSE(svr.is_running());
  9037. ASSERT_FALSE(handled);
  9038. });
  9039. svr.wait_until_ready();
  9040. auto req = "POST /test HTTP/1.1\r\n"
  9041. "Content-Length: x\r\n"
  9042. "\r\n";
  9043. std::string response;
  9044. ASSERT_TRUE(send_request(1, req, &response));
  9045. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9046. response.substr(0, response.find("\r\n")));
  9047. }
  9048. #ifndef _WIN32
  9049. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9050. static constexpr char reject[] = "Unauthorized";
  9051. static constexpr char accept[] = "Upload accepted";
  9052. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9053. Server svr;
  9054. svr.set_expect_100_continue_handler(
  9055. [](const Request & /*req*/, Response &res) {
  9056. res.status = StatusCode::Unauthorized_401;
  9057. res.set_content(reject, "text/plain");
  9058. return res.status;
  9059. });
  9060. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9061. res.set_content(accept, "text/plain");
  9062. });
  9063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9064. auto se = detail::scope_exit([&] {
  9065. svr.stop();
  9066. thread.join();
  9067. ASSERT_FALSE(svr.is_running());
  9068. });
  9069. svr.wait_until_ready();
  9070. {
  9071. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9072. curl_easy_init(), &curl_easy_cleanup};
  9073. ASSERT_NE(curl, nullptr);
  9074. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9075. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9076. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9077. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9078. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9079. &curl_slist_free_all};
  9080. ASSERT_NE(list, nullptr);
  9081. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9082. struct read_data {
  9083. size_t read_size;
  9084. size_t total_size;
  9085. } data = {0, total_size};
  9086. using read_callback_t =
  9087. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9088. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9089. void *userdata) -> size_t {
  9090. read_data *data = (read_data *)userdata;
  9091. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9092. std::fill_n(ptr, size * nmemb, 'A');
  9093. data->read_size += size * nmemb;
  9094. return size * nmemb;
  9095. };
  9096. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9097. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9098. std::vector<char> buffer;
  9099. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9100. using write_callback_t =
  9101. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9102. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9103. void *userdata) -> size_t {
  9104. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9105. buffer->reserve(buffer->size() + size * nmemb + 1);
  9106. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9107. return size * nmemb;
  9108. };
  9109. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9110. {
  9111. const auto res = curl_easy_perform(curl.get());
  9112. ASSERT_EQ(res, CURLE_OK);
  9113. }
  9114. {
  9115. auto response_code = long{};
  9116. const auto res =
  9117. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9118. ASSERT_EQ(res, CURLE_OK);
  9119. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9120. }
  9121. {
  9122. auto dl = curl_off_t{};
  9123. const auto res =
  9124. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9125. ASSERT_EQ(res, CURLE_OK);
  9126. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9127. }
  9128. {
  9129. buffer.push_back('\0');
  9130. ASSERT_STRCASEEQ(buffer.data(), reject);
  9131. }
  9132. }
  9133. }
  9134. #endif
  9135. template <typename S, typename C>
  9136. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9137. svr.Get("/stream", [&](const Request &, Response &res) {
  9138. auto data = new std::string("01234567890123456789");
  9139. res.set_content_provider(
  9140. data->size(), "text/plain",
  9141. [&, data](size_t offset, size_t length, DataSink &sink) {
  9142. const size_t DATA_CHUNK_SIZE = 4;
  9143. const auto &d = *data;
  9144. std::this_thread::sleep_for(std::chrono::seconds(1));
  9145. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9146. return true;
  9147. },
  9148. [data](bool success) {
  9149. EXPECT_FALSE(success);
  9150. delete data;
  9151. });
  9152. });
  9153. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9154. auto i = new size_t(0);
  9155. res.set_content_provider(
  9156. "text/plain",
  9157. [i](size_t, DataSink &sink) {
  9158. if (*i < 5) {
  9159. std::this_thread::sleep_for(std::chrono::seconds(1));
  9160. sink.write("abcd", 4);
  9161. (*i)++;
  9162. } else {
  9163. sink.done();
  9164. }
  9165. return true;
  9166. },
  9167. [i](bool success) {
  9168. EXPECT_FALSE(success);
  9169. delete i;
  9170. });
  9171. });
  9172. svr.Get("/chunked", [&](const Request &, Response &res) {
  9173. auto i = new size_t(0);
  9174. res.set_chunked_content_provider(
  9175. "text/plain",
  9176. [i](size_t, DataSink &sink) {
  9177. if (*i < 5) {
  9178. std::this_thread::sleep_for(std::chrono::seconds(1));
  9179. sink.os << "abcd";
  9180. (*i)++;
  9181. } else {
  9182. sink.done();
  9183. }
  9184. return true;
  9185. },
  9186. [i](bool success) {
  9187. EXPECT_FALSE(success);
  9188. delete i;
  9189. });
  9190. });
  9191. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9192. auto se = detail::scope_exit([&] {
  9193. svr.stop();
  9194. listen_thread.join();
  9195. ASSERT_FALSE(svr.is_running());
  9196. });
  9197. svr.wait_until_ready();
  9198. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9199. {
  9200. auto start = std::chrono::steady_clock::now();
  9201. auto res = cli.Get("/stream");
  9202. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9203. std::chrono::steady_clock::now() - start)
  9204. .count();
  9205. ASSERT_FALSE(res);
  9206. EXPECT_EQ(Error::Read, res.error());
  9207. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9208. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9209. }
  9210. {
  9211. auto start = std::chrono::steady_clock::now();
  9212. auto res = cli.Get("/stream_without_length");
  9213. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9214. std::chrono::steady_clock::now() - start)
  9215. .count();
  9216. ASSERT_FALSE(res);
  9217. EXPECT_EQ(Error::Read, res.error());
  9218. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9219. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9220. }
  9221. {
  9222. auto start = std::chrono::steady_clock::now();
  9223. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9224. EXPECT_EQ("abcd", string(data, data_length));
  9225. return true;
  9226. });
  9227. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9228. std::chrono::steady_clock::now() - start)
  9229. .count();
  9230. ASSERT_FALSE(res);
  9231. EXPECT_EQ(Error::Read, res.error());
  9232. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9233. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9234. }
  9235. }
  9236. TEST(MaxTimeoutTest, ContentStream) {
  9237. time_t timeout = 2000;
  9238. time_t threshold = 200;
  9239. Server svr;
  9240. Client cli("localhost", PORT);
  9241. max_timeout_test(svr, cli, timeout, threshold);
  9242. }
  9243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9244. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9245. time_t timeout = 2000;
  9246. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9248. SSLClient cli("localhost", PORT);
  9249. cli.enable_server_certificate_verification(false);
  9250. max_timeout_test(svr, cli, timeout, threshold);
  9251. }
  9252. #endif
  9253. class EventDispatcher {
  9254. public:
  9255. EventDispatcher() {}
  9256. bool wait_event(DataSink *sink) {
  9257. unique_lock<mutex> lk(m_);
  9258. int id = id_;
  9259. // Wait with timeout to prevent hanging if client disconnects
  9260. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9261. [&] { return cid_ == id; })) {
  9262. return false; // Timeout occurred
  9263. }
  9264. sink->write(message_.data(), message_.size());
  9265. return true;
  9266. }
  9267. void send_event(const string &message) {
  9268. lock_guard<mutex> lk(m_);
  9269. cid_ = id_++;
  9270. message_ = message;
  9271. cv_.notify_all();
  9272. }
  9273. private:
  9274. mutex m_;
  9275. condition_variable cv_;
  9276. atomic_int id_{0};
  9277. atomic_int cid_{-1};
  9278. string message_;
  9279. };
  9280. TEST(ClientInThreadTest, Issue2068) {
  9281. EventDispatcher ed;
  9282. Server svr;
  9283. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9284. res.set_chunked_content_provider("text/event-stream",
  9285. [&](size_t /*offset*/, DataSink &sink) {
  9286. return ed.wait_event(&sink);
  9287. });
  9288. });
  9289. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9290. svr.wait_until_ready();
  9291. thread event_thread([&] {
  9292. int id = 0;
  9293. while (svr.is_running()) {
  9294. this_thread::sleep_for(chrono::milliseconds(500));
  9295. std::stringstream ss;
  9296. ss << "data: " << id << "\n\n";
  9297. ed.send_event(ss.str());
  9298. id++;
  9299. }
  9300. });
  9301. auto se = detail::scope_exit([&] {
  9302. svr.stop();
  9303. listen_thread.join();
  9304. event_thread.join();
  9305. ASSERT_FALSE(svr.is_running());
  9306. });
  9307. {
  9308. auto client = detail::make_unique<Client>(HOST, PORT);
  9309. client->set_read_timeout(std::chrono::minutes(10));
  9310. std::atomic<bool> stop{false};
  9311. std::thread t([&] {
  9312. client->Get("/event1",
  9313. [&](const char *, size_t) -> bool { return !stop; });
  9314. });
  9315. std::this_thread::sleep_for(std::chrono::seconds(2));
  9316. stop = true;
  9317. client->stop();
  9318. t.join();
  9319. // Reset client after thread has finished
  9320. client.reset();
  9321. }
  9322. }
  9323. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9324. Server svr;
  9325. svr.Get("/", [](const Request &req, Response &res) {
  9326. EXPECT_EQ(2U, req.trailers.size());
  9327. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9328. // Denied
  9329. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9330. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9331. // Accepted
  9332. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9333. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9334. EXPECT_TRUE(req.has_trailer("X-World"));
  9335. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9336. res.set_content("ok", "text/plain");
  9337. });
  9338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9339. auto se = detail::scope_exit([&] {
  9340. svr.stop();
  9341. t.join();
  9342. ASSERT_FALSE(svr.is_running());
  9343. });
  9344. svr.wait_until_ready();
  9345. const std::string req = "GET / HTTP/1.1\r\n"
  9346. "Transfer-Encoding: chunked\r\n"
  9347. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9348. "\r\n"
  9349. "0\r\n"
  9350. "Content-Length: 10\r\n"
  9351. "Host: internal.local\r\n"
  9352. "Content-Type: malicious/content\r\n"
  9353. "Cookie: any\r\n"
  9354. "Set-Cookie: any\r\n"
  9355. "X-Forwarded-For: attacker.com\r\n"
  9356. "X-Real-Ip: 1.1.1.1\r\n"
  9357. "X-Hello: hello\r\n"
  9358. "X-World: world\r\n"
  9359. "\r\n";
  9360. std::string res;
  9361. ASSERT_TRUE(send_request(1, req, &res));
  9362. }
  9363. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9364. Server svr;
  9365. std::string observed_remote_addr;
  9366. std::string observed_xff;
  9367. svr.Get("/ip", [&](const Request &req, Response &res) {
  9368. observed_remote_addr = req.remote_addr;
  9369. observed_xff = req.get_header_value("X-Forwarded-For");
  9370. res.set_content("ok", "text/plain");
  9371. });
  9372. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9373. auto se = detail::scope_exit([&] {
  9374. svr.stop();
  9375. t.join();
  9376. ASSERT_FALSE(svr.is_running());
  9377. });
  9378. svr.wait_until_ready();
  9379. Client cli(HOST, PORT);
  9380. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9381. ASSERT_TRUE(res);
  9382. EXPECT_EQ(StatusCode::OK_200, res->status);
  9383. EXPECT_EQ(observed_xff, "203.0.113.66");
  9384. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9385. observed_remote_addr == "127.0.0.1");
  9386. }
  9387. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9388. Server svr;
  9389. svr.set_trusted_proxies({"203.0.113.66"});
  9390. std::string observed_remote_addr;
  9391. std::string observed_xff;
  9392. svr.Get("/ip", [&](const Request &req, Response &res) {
  9393. observed_remote_addr = req.remote_addr;
  9394. observed_xff = req.get_header_value("X-Forwarded-For");
  9395. res.set_content("ok", "text/plain");
  9396. });
  9397. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9398. auto se = detail::scope_exit([&] {
  9399. svr.stop();
  9400. t.join();
  9401. ASSERT_FALSE(svr.is_running());
  9402. });
  9403. svr.wait_until_ready();
  9404. Client cli(HOST, PORT);
  9405. auto res = cli.Get("/ip");
  9406. ASSERT_TRUE(res);
  9407. EXPECT_EQ(StatusCode::OK_200, res->status);
  9408. EXPECT_EQ(observed_xff, "");
  9409. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9410. observed_remote_addr == "127.0.0.1");
  9411. }
  9412. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9413. Server svr;
  9414. svr.set_trusted_proxies({"203.0.113.66"});
  9415. std::string observed_remote_addr;
  9416. std::string observed_xff;
  9417. svr.Get("/ip", [&](const Request &req, Response &res) {
  9418. observed_remote_addr = req.remote_addr;
  9419. observed_xff = req.get_header_value("X-Forwarded-For");
  9420. res.set_content("ok", "text/plain");
  9421. });
  9422. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9423. auto se = detail::scope_exit([&] {
  9424. svr.stop();
  9425. t.join();
  9426. ASSERT_FALSE(svr.is_running());
  9427. });
  9428. svr.wait_until_ready();
  9429. Client cli(HOST, PORT);
  9430. auto res =
  9431. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9432. ASSERT_TRUE(res);
  9433. EXPECT_EQ(StatusCode::OK_200, res->status);
  9434. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9435. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9436. }
  9437. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9438. Server svr;
  9439. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9440. std::string observed_remote_addr;
  9441. std::string observed_xff;
  9442. svr.Get("/ip", [&](const Request &req, Response &res) {
  9443. observed_remote_addr = req.remote_addr;
  9444. observed_xff = req.get_header_value("X-Forwarded-For");
  9445. res.set_content("ok", "text/plain");
  9446. });
  9447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9448. auto se = detail::scope_exit([&] {
  9449. svr.stop();
  9450. t.join();
  9451. ASSERT_FALSE(svr.is_running());
  9452. });
  9453. svr.wait_until_ready();
  9454. Client cli(HOST, PORT);
  9455. auto res = cli.Get(
  9456. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9457. ASSERT_TRUE(res);
  9458. EXPECT_EQ(StatusCode::OK_200, res->status);
  9459. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9460. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9461. }
  9462. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9463. Server svr;
  9464. svr.set_trusted_proxies({"192.0.2.45"});
  9465. std::string observed_remote_addr;
  9466. std::string observed_xff;
  9467. svr.Get("/ip", [&](const Request &req, Response &res) {
  9468. observed_remote_addr = req.remote_addr;
  9469. observed_xff = req.get_header_value("X-Forwarded-For");
  9470. res.set_content("ok", "text/plain");
  9471. });
  9472. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9473. auto se = detail::scope_exit([&] {
  9474. svr.stop();
  9475. t.join();
  9476. ASSERT_FALSE(svr.is_running());
  9477. });
  9478. svr.wait_until_ready();
  9479. Client cli(HOST, PORT);
  9480. auto res =
  9481. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9482. ASSERT_TRUE(res);
  9483. EXPECT_EQ(StatusCode::OK_200, res->status);
  9484. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9485. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9486. }
  9487. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9488. Server svr;
  9489. svr.set_trusted_proxies({"192.0.2.45"});
  9490. std::string observed_remote_addr;
  9491. std::string observed_xff;
  9492. svr.Get("/ip", [&](const Request &req, Response &res) {
  9493. observed_remote_addr = req.remote_addr;
  9494. observed_xff = req.get_header_value("X-Forwarded-For");
  9495. res.set_content("ok", "text/plain");
  9496. });
  9497. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. ASSERT_FALSE(svr.is_running());
  9502. });
  9503. svr.wait_until_ready();
  9504. Client cli(HOST, PORT);
  9505. auto res = cli.Get(
  9506. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9507. ASSERT_TRUE(res);
  9508. EXPECT_EQ(StatusCode::OK_200, res->status);
  9509. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9510. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9511. }
  9512. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9513. Server svr;
  9514. svr.set_trusted_proxies({"192.0.2.45"});
  9515. std::string observed_remote_addr;
  9516. std::string observed_xff;
  9517. svr.Get("/ip", [&](const Request &req, Response &res) {
  9518. observed_remote_addr = req.remote_addr;
  9519. observed_xff = req.get_header_value("X-Forwarded-For");
  9520. res.set_content("ok", "text/plain");
  9521. });
  9522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9523. auto se = detail::scope_exit([&] {
  9524. svr.stop();
  9525. t.join();
  9526. ASSERT_FALSE(svr.is_running());
  9527. });
  9528. svr.wait_until_ready();
  9529. Client cli(HOST, PORT);
  9530. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9531. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9532. ASSERT_TRUE(res);
  9533. EXPECT_EQ(StatusCode::OK_200, res->status);
  9534. // Header parser trims surrounding whitespace of the header value
  9535. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9536. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9537. }