test.cc 358 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688
  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. .Post("/post-loopback",
  2846. [&](const Request &, Response &res,
  2847. ContentReader const &content_reader) {
  2848. std::string body;
  2849. content_reader([&](const char *data, size_t data_length) {
  2850. body.append(data, data_length);
  2851. return true;
  2852. });
  2853. res.set_content(body, "text/plain");
  2854. })
  2855. .Put("/put-loopback",
  2856. [&](const Request &, Response &res,
  2857. ContentReader const &content_reader) {
  2858. std::string body;
  2859. content_reader([&](const char *data, size_t data_length) {
  2860. body.append(data, data_length);
  2861. return true;
  2862. });
  2863. res.set_content(body, "text/plain");
  2864. })
  2865. .Patch("/patch-loopback",
  2866. [&](const Request &, Response &res,
  2867. ContentReader const &content_reader) {
  2868. std::string body;
  2869. content_reader([&](const char *data, size_t data_length) {
  2870. body.append(data, data_length);
  2871. return true;
  2872. });
  2873. res.set_content(body, "text/plain");
  2874. })
  2875. .Put("/empty-no-content-type",
  2876. [&](const Request &req, Response &res) {
  2877. EXPECT_EQ(req.body, "");
  2878. EXPECT_FALSE(req.has_header("Content-Type"));
  2879. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2880. res.set_content("empty-no-content-type", "text/plain");
  2881. })
  2882. .Put("/put",
  2883. [&](const Request &req, Response &res) {
  2884. EXPECT_EQ(req.body, "PUT");
  2885. res.set_content(req.body, "text/plain");
  2886. })
  2887. .Put("/put-large",
  2888. [&](const Request &req, Response &res) {
  2889. EXPECT_EQ(req.body, LARGE_DATA);
  2890. res.set_content(req.body, "text/plain");
  2891. })
  2892. .Patch("/patch",
  2893. [&](const Request &req, Response &res) {
  2894. EXPECT_EQ(req.body, "PATCH");
  2895. res.set_content(req.body, "text/plain");
  2896. })
  2897. .Delete("/delete",
  2898. [&](const Request & /*req*/, Response &res) {
  2899. res.set_content("DELETE", "text/plain");
  2900. })
  2901. .Delete("/delete-body",
  2902. [&](const Request &req, Response &res) {
  2903. EXPECT_EQ(req.body, "content");
  2904. res.set_content(req.body, "text/plain");
  2905. })
  2906. .Options(R"(\*)",
  2907. [&](const Request & /*req*/, Response &res) {
  2908. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2909. })
  2910. .Get("/request-target",
  2911. [&](const Request &req, Response & /*res*/) {
  2912. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2913. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2914. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2915. })
  2916. .Get("/long-query-value",
  2917. [&](const Request &req, Response & /*res*/) {
  2918. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2919. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2920. })
  2921. .Get("/too-long-query-value",
  2922. [&](const Request &req, Response & /*res*/) {
  2923. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2924. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2925. })
  2926. .Get("/array-param",
  2927. [&](const Request &req, Response & /*res*/) {
  2928. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2929. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2930. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2931. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2932. })
  2933. .Post("/validate-no-multiple-headers",
  2934. [&](const Request &req, Response & /*res*/) {
  2935. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2936. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2937. })
  2938. .Post("/content_receiver",
  2939. [&](const Request &req, Response &res,
  2940. const ContentReader &content_reader) {
  2941. if (req.is_multipart_form_data()) {
  2942. std::vector<FormData> items;
  2943. content_reader(
  2944. [&](const FormData &file) {
  2945. items.push_back(file);
  2946. return true;
  2947. },
  2948. [&](const char *data, size_t data_length) {
  2949. items.back().content.append(data, data_length);
  2950. return true;
  2951. });
  2952. EXPECT_EQ(5u, items.size());
  2953. {
  2954. const auto &file = get_file_value(items, "text1");
  2955. EXPECT_TRUE(file.filename.empty());
  2956. EXPECT_EQ("text default", file.content);
  2957. }
  2958. {
  2959. const auto &file = get_file_value(items, "text2");
  2960. EXPECT_TRUE(file.filename.empty());
  2961. EXPECT_EQ("aωb", file.content);
  2962. }
  2963. {
  2964. const auto &file = get_file_value(items, "file1");
  2965. EXPECT_EQ("hello.txt", file.filename);
  2966. EXPECT_EQ("text/plain", file.content_type);
  2967. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2968. }
  2969. {
  2970. const auto &file = get_file_value(items, "file2");
  2971. EXPECT_EQ("world.json", file.filename);
  2972. EXPECT_EQ("application/json", file.content_type);
  2973. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  2974. }
  2975. {
  2976. const auto &file = get_file_value(items, "file3");
  2977. EXPECT_TRUE(file.filename.empty());
  2978. EXPECT_EQ("application/octet-stream", file.content_type);
  2979. EXPECT_EQ(0u, file.content.size());
  2980. }
  2981. } else {
  2982. std::string body;
  2983. content_reader([&](const char *data, size_t data_length) {
  2984. EXPECT_EQ(7U, data_length);
  2985. body.append(data, data_length);
  2986. return true;
  2987. });
  2988. EXPECT_EQ(body, "content");
  2989. res.set_content(body, "text/plain");
  2990. }
  2991. })
  2992. .Put("/content_receiver",
  2993. [&](const Request & /*req*/, Response &res,
  2994. const ContentReader &content_reader) {
  2995. std::string body;
  2996. content_reader([&](const char *data, size_t data_length) {
  2997. body.append(data, data_length);
  2998. return true;
  2999. });
  3000. EXPECT_EQ(body, "content");
  3001. res.set_content(body, "text/plain");
  3002. })
  3003. .Patch("/content_receiver",
  3004. [&](const Request & /*req*/, Response &res,
  3005. const ContentReader &content_reader) {
  3006. std::string body;
  3007. content_reader([&](const char *data, size_t data_length) {
  3008. body.append(data, data_length);
  3009. return true;
  3010. });
  3011. EXPECT_EQ(body, "content");
  3012. res.set_content(body, "text/plain");
  3013. })
  3014. .Post("/query-string-and-body",
  3015. [&](const Request &req, Response & /*res*/) {
  3016. ASSERT_TRUE(req.has_param("key"));
  3017. EXPECT_EQ(req.get_param_value("key"), "value");
  3018. EXPECT_EQ(req.body, "content");
  3019. })
  3020. .Get("/last-request",
  3021. [&](const Request &req, Response & /*res*/) {
  3022. EXPECT_EQ("close", req.get_header_value("Connection"));
  3023. })
  3024. .Get(R"(/redirect/(\d+))",
  3025. [&](const Request &req, Response &res) {
  3026. auto num = std::stoi(req.matches[1]) + 1;
  3027. std::string url = "/redirect/" + std::to_string(num);
  3028. res.set_redirect(url);
  3029. })
  3030. .Post("/binary",
  3031. [&](const Request &req, Response &res) {
  3032. EXPECT_EQ(4U, req.body.size());
  3033. EXPECT_EQ("application/octet-stream",
  3034. req.get_header_value("Content-Type"));
  3035. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3036. res.set_content(req.body, "application/octet-stream");
  3037. })
  3038. .Put("/binary",
  3039. [&](const Request &req, Response &res) {
  3040. EXPECT_EQ(4U, req.body.size());
  3041. EXPECT_EQ("application/octet-stream",
  3042. req.get_header_value("Content-Type"));
  3043. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3044. res.set_content(req.body, "application/octet-stream");
  3045. })
  3046. .Patch("/binary",
  3047. [&](const Request &req, Response &res) {
  3048. EXPECT_EQ(4U, req.body.size());
  3049. EXPECT_EQ("application/octet-stream",
  3050. req.get_header_value("Content-Type"));
  3051. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3052. res.set_content(req.body, "application/octet-stream");
  3053. })
  3054. .Delete("/binary",
  3055. [&](const Request &req, Response &res) {
  3056. EXPECT_EQ(4U, req.body.size());
  3057. EXPECT_EQ("application/octet-stream",
  3058. req.get_header_value("Content-Type"));
  3059. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3060. res.set_content(req.body, "application/octet-stream");
  3061. })
  3062. .Get("/issue1772",
  3063. [&](const Request & /*req*/, Response &res) {
  3064. res.status = 401;
  3065. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3066. })
  3067. .Delete("/issue609",
  3068. [](const httplib::Request &, httplib::Response &res,
  3069. const httplib::ContentReader &) {
  3070. res.set_content("ok", "text/plain");
  3071. })
  3072. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3073. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3074. .Get("/compress",
  3075. [&](const Request & /*req*/, Response &res) {
  3076. res.set_content(
  3077. "12345678901234567890123456789012345678901234567890123456789"
  3078. "01234567890123456789012345678901234567890",
  3079. "text/plain");
  3080. })
  3081. .Get("/nocompress",
  3082. [&](const Request & /*req*/, Response &res) {
  3083. res.set_content(
  3084. "12345678901234567890123456789012345678901234567890123456789"
  3085. "01234567890123456789012345678901234567890",
  3086. "application/octet-stream");
  3087. })
  3088. .Post("/compress-multipart",
  3089. [&](const Request &req, Response & /*res*/) {
  3090. EXPECT_EQ(2u, req.form.fields.size());
  3091. ASSERT_TRUE(!req.form.has_field("???"));
  3092. {
  3093. const auto &text = req.form.get_field("key1");
  3094. EXPECT_EQ("test", text);
  3095. }
  3096. {
  3097. const auto &text = req.form.get_field("key2");
  3098. EXPECT_EQ("--abcdefg123", text);
  3099. }
  3100. })
  3101. #endif
  3102. ;
  3103. persons_["john"] = "programmer";
  3104. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3105. svr_.wait_until_ready();
  3106. }
  3107. virtual void TearDown() {
  3108. svr_.stop();
  3109. if (!request_threads_.empty()) {
  3110. std::this_thread::sleep_for(std::chrono::seconds(1));
  3111. for (auto &t : request_threads_) {
  3112. t.join();
  3113. }
  3114. }
  3115. t_.join();
  3116. }
  3117. map<string, string> persons_;
  3118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3119. SSLClient cli_;
  3120. SSLServer svr_;
  3121. #else
  3122. Client cli_;
  3123. Server svr_;
  3124. #endif
  3125. thread t_;
  3126. std::vector<thread> request_threads_;
  3127. };
  3128. TEST_F(ServerTest, GetMethod200) {
  3129. auto res = cli_.Get("/hi");
  3130. ASSERT_TRUE(res);
  3131. EXPECT_EQ("HTTP/1.1", res->version);
  3132. EXPECT_EQ(StatusCode::OK_200, res->status);
  3133. EXPECT_EQ("OK", res->reason);
  3134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3135. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3136. EXPECT_EQ("Hello World!", res->body);
  3137. }
  3138. TEST_F(ServerTest, GetEmptyFile) {
  3139. auto res = cli_.Get("/empty_file");
  3140. ASSERT_TRUE(res);
  3141. EXPECT_EQ(StatusCode::OK_200, res->status);
  3142. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3143. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3144. EXPECT_EQ("", res->body);
  3145. }
  3146. TEST_F(ServerTest, GetFileContent) {
  3147. auto res = cli_.Get("/file_content");
  3148. ASSERT_TRUE(res);
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3151. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3152. EXPECT_EQ("test.html", res->body);
  3153. }
  3154. TEST_F(ServerTest, GetFileContentWithRange) {
  3155. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3156. ASSERT_TRUE(res);
  3157. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3158. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3159. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3160. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3161. EXPECT_EQ("est", res->body);
  3162. }
  3163. TEST_F(ServerTest, GetFileContentWithContentType) {
  3164. auto res = cli_.Get("/file_content_with_content_type");
  3165. ASSERT_TRUE(res);
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3168. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3169. EXPECT_EQ("file\n", res->body);
  3170. }
  3171. TEST_F(ServerTest, GetInvalidFileContent) {
  3172. auto res = cli_.Get("/invalid_file_content");
  3173. ASSERT_TRUE(res);
  3174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3175. }
  3176. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3177. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ("HTTP/1.1", res->version);
  3180. EXPECT_EQ(StatusCode::OK_200, res->status);
  3181. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3182. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3183. EXPECT_EQ("Hello World!", res->body);
  3184. }
  3185. TEST_F(ServerTest, GetMethod302) {
  3186. auto res = cli_.Get("/");
  3187. ASSERT_TRUE(res);
  3188. EXPECT_EQ(StatusCode::Found_302, res->status);
  3189. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3190. }
  3191. TEST_F(ServerTest, GetMethod302Redirect) {
  3192. cli_.set_follow_location(true);
  3193. auto res = cli_.Get("/");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("Hello World!", res->body);
  3197. EXPECT_EQ("/hi", res->location);
  3198. }
  3199. TEST_F(ServerTest, GetMethod404) {
  3200. auto res = cli_.Get("/invalid");
  3201. ASSERT_TRUE(res);
  3202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3203. }
  3204. TEST_F(ServerTest, HeadMethod200) {
  3205. auto res = cli_.Head("/hi");
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(StatusCode::OK_200, res->status);
  3208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3209. EXPECT_TRUE(res->body.empty());
  3210. }
  3211. TEST_F(ServerTest, HeadMethod200Static) {
  3212. auto res = cli_.Head("/mount/dir/index.html");
  3213. ASSERT_TRUE(res);
  3214. EXPECT_EQ(StatusCode::OK_200, res->status);
  3215. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3216. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3217. EXPECT_TRUE(res->body.empty());
  3218. }
  3219. TEST_F(ServerTest, HeadMethod404) {
  3220. auto res = cli_.Head("/invalid");
  3221. ASSERT_TRUE(res);
  3222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3223. EXPECT_TRUE(res->body.empty());
  3224. }
  3225. TEST_F(ServerTest, GetMethodPersonJohn) {
  3226. auto res = cli_.Get("/person/john");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ("programmer", res->body);
  3231. }
  3232. TEST_F(ServerTest, PostMethod1) {
  3233. auto res = cli_.Get("/person/john1");
  3234. ASSERT_TRUE(res);
  3235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3236. res = cli_.Post("/person", "name=john1&note=coder",
  3237. "application/x-www-form-urlencoded");
  3238. ASSERT_TRUE(res);
  3239. ASSERT_EQ(StatusCode::OK_200, res->status);
  3240. res = cli_.Get("/person/john1");
  3241. ASSERT_TRUE(res);
  3242. ASSERT_EQ(StatusCode::OK_200, res->status);
  3243. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. ASSERT_EQ("coder", res->body);
  3245. }
  3246. TEST_F(ServerTest, PostMethod2) {
  3247. auto res = cli_.Get("/person/john2");
  3248. ASSERT_TRUE(res);
  3249. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3250. Params params;
  3251. params.emplace("name", "john2");
  3252. params.emplace("note", "coder");
  3253. res = cli_.Post("/person", params);
  3254. ASSERT_TRUE(res);
  3255. ASSERT_EQ(StatusCode::OK_200, res->status);
  3256. res = cli_.Get("/person/john2");
  3257. ASSERT_TRUE(res);
  3258. ASSERT_EQ(StatusCode::OK_200, res->status);
  3259. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3260. ASSERT_EQ("coder", res->body);
  3261. }
  3262. TEST_F(ServerTest, PutMethod3) {
  3263. auto res = cli_.Get("/person/john3");
  3264. ASSERT_TRUE(res);
  3265. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3266. Params params;
  3267. params.emplace("name", "john3");
  3268. params.emplace("note", "coder");
  3269. res = cli_.Put("/person", params);
  3270. ASSERT_TRUE(res);
  3271. ASSERT_EQ(StatusCode::OK_200, res->status);
  3272. res = cli_.Get("/person/john3");
  3273. ASSERT_TRUE(res);
  3274. ASSERT_EQ(StatusCode::OK_200, res->status);
  3275. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3276. ASSERT_EQ("coder", res->body);
  3277. }
  3278. TEST_F(ServerTest, DeleteMethod1) {
  3279. auto res = cli_.Get("/person/john4");
  3280. ASSERT_TRUE(res);
  3281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3282. Params params;
  3283. params.emplace("name", "john4");
  3284. params.emplace("note", "coder");
  3285. res = cli_.Post("/person", params);
  3286. ASSERT_TRUE(res);
  3287. ASSERT_EQ(StatusCode::OK_200, res->status);
  3288. res = cli_.Get("/person/john4");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::OK_200, res->status);
  3291. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. ASSERT_EQ("coder", res->body);
  3293. Params delete_params;
  3294. delete_params.emplace("name", "john4");
  3295. res = cli_.Delete("/person", delete_params);
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("DELETED", res->body);
  3299. res = cli_.Get("/person/john4");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3302. }
  3303. TEST_F(ServerTest, DeleteMethod2) {
  3304. auto res = cli_.Get("/person/john5");
  3305. ASSERT_TRUE(res);
  3306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3307. Params params;
  3308. params.emplace("name", "john5");
  3309. params.emplace("note", "developer");
  3310. res = cli_.Post("/person", params);
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. res = cli_.Get("/person/john5");
  3314. ASSERT_TRUE(res);
  3315. ASSERT_EQ(StatusCode::OK_200, res->status);
  3316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3317. ASSERT_EQ("developer", res->body);
  3318. Params delete_params;
  3319. delete_params.emplace("name", "john5");
  3320. Headers headers;
  3321. headers.emplace("Custom-Header", "test-value");
  3322. res = cli_.Delete("/person", headers, delete_params);
  3323. ASSERT_TRUE(res);
  3324. ASSERT_EQ(StatusCode::OK_200, res->status);
  3325. ASSERT_EQ("DELETED", res->body);
  3326. res = cli_.Get("/person/john5");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3329. }
  3330. TEST_F(ServerTest, DeleteMethod3) {
  3331. auto res = cli_.Get("/person/john6");
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3334. Params params;
  3335. params.emplace("name", "john6");
  3336. params.emplace("note", "tester");
  3337. res = cli_.Post("/person", params);
  3338. ASSERT_TRUE(res);
  3339. ASSERT_EQ(StatusCode::OK_200, res->status);
  3340. res = cli_.Get("/person/john6");
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3344. ASSERT_EQ("tester", res->body);
  3345. Params delete_params;
  3346. delete_params.emplace("name", "john6");
  3347. Headers headers;
  3348. headers.emplace("Custom-Header", "test-value");
  3349. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john6");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3358. Params params;
  3359. params.emplace("json", JSON_DATA);
  3360. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3361. ASSERT_TRUE(res);
  3362. ASSERT_EQ(StatusCode::OK_200, res->status);
  3363. ASSERT_EQ(JSON_DATA, res->body);
  3364. }
  3365. TEST_F(ServerTest, PostEmptyContent) {
  3366. auto res = cli_.Post("/empty", "", "text/plain");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("empty", res->body);
  3370. }
  3371. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3372. auto res = cli_.Post("/empty-no-content-type");
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. ASSERT_EQ("empty-no-content-type", res->body);
  3376. }
  3377. TEST_F(ServerTest, PostPathOnly) {
  3378. auto res = cli_.Post("/path-only");
  3379. ASSERT_TRUE(res);
  3380. ASSERT_EQ(StatusCode::OK_200, res->status);
  3381. ASSERT_EQ("path-only", res->body);
  3382. }
  3383. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3384. auto res = cli_.Post("/path-headers-only",
  3385. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::OK_200, res->status);
  3388. ASSERT_EQ("path-headers-only", res->body);
  3389. }
  3390. TEST_F(ServerTest, PostLarge) {
  3391. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. EXPECT_EQ(LARGE_DATA, res->body);
  3395. }
  3396. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3397. auto res = cli_.Put("/empty-no-content-type");
  3398. ASSERT_TRUE(res);
  3399. ASSERT_EQ(StatusCode::OK_200, res->status);
  3400. ASSERT_EQ("empty-no-content-type", res->body);
  3401. }
  3402. TEST_F(ServerTest, GetMethodDir) {
  3403. auto res = cli_.Get("/dir/");
  3404. ASSERT_TRUE(res);
  3405. EXPECT_EQ(StatusCode::OK_200, res->status);
  3406. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3407. auto body = R"(<html>
  3408. <head>
  3409. </head>
  3410. <body>
  3411. <a href="/dir/test.html">Test</a>
  3412. <a href="/hi">hi</a>
  3413. </body>
  3414. </html>
  3415. )";
  3416. EXPECT_EQ(body, res->body);
  3417. }
  3418. TEST_F(ServerTest, GetMethodDirTest) {
  3419. auto res = cli_.Get("/dir/test.html");
  3420. ASSERT_TRUE(res);
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3423. EXPECT_EQ("test.html", res->body);
  3424. }
  3425. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3426. auto res = cli_.Get("/dir/../dir/test.html");
  3427. ASSERT_TRUE(res);
  3428. EXPECT_EQ(StatusCode::OK_200, res->status);
  3429. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3430. EXPECT_EQ("test.html", res->body);
  3431. }
  3432. TEST_F(ServerTest, GetMethodInvalidPath) {
  3433. auto res = cli_.Get("/dir/../test.html");
  3434. ASSERT_TRUE(res);
  3435. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3436. }
  3437. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3438. auto res = cli_.Get("/../www/dir/test.html");
  3439. ASSERT_TRUE(res);
  3440. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3441. }
  3442. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3443. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3444. ASSERT_TRUE(res);
  3445. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3446. }
  3447. TEST_F(ServerTest, GetMethodDirMountTest) {
  3448. auto res = cli_.Get("/mount/dir/test.html");
  3449. ASSERT_TRUE(res);
  3450. EXPECT_EQ(StatusCode::OK_200, res->status);
  3451. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3452. EXPECT_EQ("test.html", res->body);
  3453. }
  3454. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3455. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3456. ASSERT_TRUE(res);
  3457. EXPECT_EQ(StatusCode::OK_200, res->status);
  3458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3459. EXPECT_EQ("test.html", res->body);
  3460. }
  3461. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3462. auto res = cli_.Get("/mount/dir/../test.html");
  3463. ASSERT_TRUE(res);
  3464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3465. }
  3466. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3467. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3468. ASSERT_TRUE(res);
  3469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3470. }
  3471. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3472. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3475. }
  3476. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3477. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3478. ASSERT_TRUE(res);
  3479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3480. }
  3481. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3482. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3483. ASSERT_TRUE(res);
  3484. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3485. }
  3486. TEST_F(ServerTest, PostMethod303) {
  3487. auto res = cli_.Post("/1", "body", "text/plain");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3490. EXPECT_EQ("/2", res->get_header_value("Location"));
  3491. }
  3492. TEST_F(ServerTest, PostMethod303Redirect) {
  3493. cli_.set_follow_location(true);
  3494. auto res = cli_.Post("/1", "body", "text/plain");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("redirected.", res->body);
  3498. EXPECT_EQ("/2", res->location);
  3499. }
  3500. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3501. auto res = cli_.Get("/dir/test.abcde");
  3502. ASSERT_TRUE(res);
  3503. EXPECT_EQ(StatusCode::OK_200, res->status);
  3504. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3505. EXPECT_EQ("abcde", res->body);
  3506. }
  3507. TEST_F(ServerTest, StaticFileRange) {
  3508. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3509. ASSERT_TRUE(res);
  3510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3511. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3512. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3513. EXPECT_EQ(true, res->has_header("Content-Range"));
  3514. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3515. EXPECT_EQ(std::string("cd"), res->body);
  3516. }
  3517. TEST_F(ServerTest, StaticFileRanges) {
  3518. auto res =
  3519. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3520. ASSERT_TRUE(res);
  3521. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3522. EXPECT_TRUE(
  3523. res->get_header_value("Content-Type")
  3524. .find(
  3525. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3526. 0);
  3527. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3528. }
  3529. TEST_F(ServerTest, StaticFileRangeHead) {
  3530. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3531. ASSERT_TRUE(res);
  3532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3533. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3534. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3535. EXPECT_EQ(true, res->has_header("Content-Range"));
  3536. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3537. }
  3538. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3539. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3543. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3544. EXPECT_EQ(true, res->has_header("Content-Range"));
  3545. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3546. res->get_header_value("Content-Range"));
  3547. EXPECT_EQ("LAST\n", res->body);
  3548. }
  3549. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3550. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3551. ASSERT_TRUE(res);
  3552. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3553. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3554. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3555. EXPECT_EQ(true, res->has_header("Content-Range"));
  3556. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3557. }
  3558. TEST_F(ServerTest, StaticFileBigFile) {
  3559. auto res = cli_.Get("/dir/1MB.txt");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::OK_200, res->status);
  3562. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3563. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3564. }
  3565. TEST_F(ServerTest, InvalidBaseDirMount) {
  3566. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3567. }
  3568. TEST_F(ServerTest, Binary) {
  3569. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3570. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3571. "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_.Put("/binary", binary.data(), binary.size(),
  3576. "application/octet-stream");
  3577. ASSERT_TRUE(res);
  3578. ASSERT_EQ(StatusCode::OK_200, res->status);
  3579. ASSERT_EQ(4U, res->body.size());
  3580. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3581. "application/octet-stream");
  3582. ASSERT_TRUE(res);
  3583. ASSERT_EQ(StatusCode::OK_200, res->status);
  3584. ASSERT_EQ(4U, res->body.size());
  3585. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3586. "application/octet-stream");
  3587. ASSERT_TRUE(res);
  3588. ASSERT_EQ(StatusCode::OK_200, res->status);
  3589. ASSERT_EQ(4U, res->body.size());
  3590. }
  3591. TEST_F(ServerTest, BinaryString) {
  3592. auto binary = std::string("\x00\x01\x02\x03", 4);
  3593. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3594. ASSERT_TRUE(res);
  3595. ASSERT_EQ(StatusCode::OK_200, res->status);
  3596. ASSERT_EQ(4U, res->body.size());
  3597. res = cli_.Put("/binary", binary, "application/octet-stream");
  3598. ASSERT_TRUE(res);
  3599. ASSERT_EQ(StatusCode::OK_200, res->status);
  3600. ASSERT_EQ(4U, res->body.size());
  3601. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3602. ASSERT_TRUE(res);
  3603. ASSERT_EQ(StatusCode::OK_200, res->status);
  3604. ASSERT_EQ(4U, res->body.size());
  3605. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3606. ASSERT_TRUE(res);
  3607. ASSERT_EQ(StatusCode::OK_200, res->status);
  3608. ASSERT_EQ(4U, res->body.size());
  3609. }
  3610. TEST_F(ServerTest, EmptyRequest) {
  3611. auto res = cli_.Get("");
  3612. ASSERT_TRUE(!res);
  3613. EXPECT_EQ(Error::Connection, res.error());
  3614. }
  3615. TEST_F(ServerTest, LongRequest) {
  3616. std::string request;
  3617. for (size_t i = 0; i < 545; i++) {
  3618. request += "/TooLongRequest";
  3619. }
  3620. request += "OK";
  3621. auto res = cli_.Get(request.c_str());
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3624. }
  3625. TEST_F(ServerTest, TooLongRequest) {
  3626. std::string request;
  3627. for (size_t i = 0; i < 546; i++) {
  3628. request += "/TooLongRequest";
  3629. }
  3630. request += "_NG";
  3631. auto start = std::chrono::high_resolution_clock::now();
  3632. cli_.set_keep_alive(true);
  3633. auto res = cli_.Get(request.c_str());
  3634. auto end = std::chrono::high_resolution_clock::now();
  3635. auto elapsed =
  3636. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3637. .count();
  3638. ASSERT_TRUE(res);
  3639. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3640. EXPECT_LE(elapsed, 100);
  3641. EXPECT_EQ("close", res->get_header_value("Connection"));
  3642. EXPECT_FALSE(cli_.is_socket_open());
  3643. }
  3644. TEST_F(ServerTest, AlmostTooLongRequest) {
  3645. // test for #2046 - URI length check shouldn't include other content on req
  3646. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3647. // leading /, space, HTTP/1.1)
  3648. std::string request =
  3649. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3650. auto res = cli_.Get(request.c_str());
  3651. ASSERT_TRUE(res);
  3652. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3653. }
  3654. TEST_F(ServerTest, LongHeader) {
  3655. Request req;
  3656. req.method = "GET";
  3657. req.path = "/hi";
  3658. std::string host_and_port;
  3659. host_and_port += HOST;
  3660. host_and_port += ":";
  3661. host_and_port += std::to_string(PORT);
  3662. req.headers.emplace("Host", host_and_port.c_str());
  3663. req.headers.emplace("Accept", "*/*");
  3664. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3665. req.headers.emplace(
  3666. "Header-Name",
  3667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3695. "@@@@@@@@@@@@@@@@");
  3696. auto res = std::make_shared<Response>();
  3697. auto error = Error::Success;
  3698. auto ret = cli_.send(req, *res, error);
  3699. ASSERT_TRUE(ret);
  3700. EXPECT_EQ(StatusCode::OK_200, res->status);
  3701. }
  3702. TEST_F(ServerTest, LongQueryValue) {
  3703. auto start = std::chrono::high_resolution_clock::now();
  3704. cli_.set_keep_alive(true);
  3705. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3706. auto end = std::chrono::high_resolution_clock::now();
  3707. auto elapsed =
  3708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3709. .count();
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3712. EXPECT_LE(elapsed, 100);
  3713. EXPECT_EQ("close", res->get_header_value("Connection"));
  3714. EXPECT_FALSE(cli_.is_socket_open());
  3715. }
  3716. TEST_F(ServerTest, TooLongQueryValue) {
  3717. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3718. ASSERT_FALSE(res);
  3719. EXPECT_EQ(Error::Read, res.error());
  3720. }
  3721. TEST_F(ServerTest, TooLongHeader) {
  3722. Request req;
  3723. req.method = "GET";
  3724. req.path = "/hi";
  3725. std::string host_and_port;
  3726. host_and_port += HOST;
  3727. host_and_port += ":";
  3728. host_and_port += std::to_string(PORT);
  3729. req.headers.emplace("Host", host_and_port.c_str());
  3730. req.headers.emplace("Accept", "*/*");
  3731. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3732. req.headers.emplace(
  3733. "Header-Name",
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3762. "@@@@@@@@@@@@@@@@@");
  3763. auto res = std::make_shared<Response>();
  3764. auto error = Error::Success;
  3765. auto ret = cli_.send(req, *res, error);
  3766. ASSERT_TRUE(ret);
  3767. EXPECT_EQ(StatusCode::OK_200, res->status);
  3768. }
  3769. TEST_F(ServerTest, HeaderCountAtLimit) {
  3770. // Test with headers just under the 100 limit
  3771. httplib::Headers headers;
  3772. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3773. // This should keep us just under the 100 header limit
  3774. for (int i = 0; i < 95; i++) {
  3775. std::string name = "X-Test-Header-" + std::to_string(i);
  3776. std::string value = "value" + std::to_string(i);
  3777. headers.emplace(name, value);
  3778. }
  3779. // This should work fine as we're under the limit
  3780. auto res = cli_.Get("/hi", headers);
  3781. EXPECT_TRUE(res);
  3782. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3783. }
  3784. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3785. // Test with many headers to exceed the 100 limit
  3786. httplib::Headers headers;
  3787. // Add 150 headers to definitely exceed the 100 limit
  3788. for (int i = 0; i < 150; i++) {
  3789. std::string name = "X-Test-Header-" + std::to_string(i);
  3790. std::string value = "value" + std::to_string(i);
  3791. headers.emplace(name, value);
  3792. }
  3793. // This should fail due to exceeding header count limit
  3794. cli_.set_keep_alive(true);
  3795. auto res = cli_.Get("/hi", headers);
  3796. // The request should either fail or return 400 Bad Request
  3797. if (res) {
  3798. // If we get a response, it should be 400 Bad Request
  3799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3800. } else {
  3801. // Or the request should fail entirely
  3802. EXPECT_FALSE(res);
  3803. }
  3804. EXPECT_EQ("close", res->get_header_value("Connection"));
  3805. EXPECT_FALSE(cli_.is_socket_open());
  3806. }
  3807. TEST_F(ServerTest, PercentEncoding) {
  3808. auto res = cli_.Get("/e%6edwith%");
  3809. ASSERT_TRUE(res);
  3810. EXPECT_EQ(StatusCode::OK_200, res->status);
  3811. }
  3812. TEST_F(ServerTest, PercentEncodingUnicode) {
  3813. auto res = cli_.Get("/e%u006edwith%");
  3814. ASSERT_TRUE(res);
  3815. EXPECT_EQ(StatusCode::OK_200, res->status);
  3816. }
  3817. TEST_F(ServerTest, InvalidPercentEncoding) {
  3818. auto res = cli_.Get("/%endwith%");
  3819. ASSERT_TRUE(res);
  3820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3821. }
  3822. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3823. auto res = cli_.Get("/%uendwith%");
  3824. ASSERT_TRUE(res);
  3825. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3826. }
  3827. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3828. auto res = cli_.Get("/hello?aaa=bbb%");
  3829. ASSERT_TRUE(res);
  3830. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3831. }
  3832. TEST_F(ServerTest, PlusSignEncoding) {
  3833. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3834. ASSERT_TRUE(res);
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ("a +b", res->body);
  3837. }
  3838. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3839. // This test simulates a potential DoS attack using many headers
  3840. // to verify our security fix prevents memory exhaustion
  3841. httplib::Headers attack_headers;
  3842. // Attempt to add many headers like an attacker would (200 headers to far
  3843. // exceed limit)
  3844. for (int i = 0; i < 200; i++) {
  3845. std::string name = "X-Attack-Header-" + std::to_string(i);
  3846. std::string value = "attack_payload_" + std::to_string(i);
  3847. attack_headers.emplace(name, value);
  3848. }
  3849. // Try to POST with excessive headers
  3850. cli_.set_keep_alive(true);
  3851. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3852. // Should either fail or return 400 Bad Request due to security limit
  3853. if (res) {
  3854. // If we get a response, it should be 400 Bad Request
  3855. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3856. } else {
  3857. // Request failed, which is the expected behavior for DoS protection
  3858. EXPECT_FALSE(res);
  3859. }
  3860. EXPECT_EQ("close", res->get_header_value("Connection"));
  3861. EXPECT_FALSE(cli_.is_socket_open());
  3862. }
  3863. TEST_F(ServerTest, MultipartFormData) {
  3864. UploadFormDataItems items = {
  3865. {"text1", "text default", "", ""},
  3866. {"text2", "aωb", "", ""},
  3867. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3868. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3869. {"file3", "", "", "application/octet-stream"},
  3870. {"file4", "", "", " application/json tmp-string "}};
  3871. auto res = cli_.Post("/multipart", items);
  3872. ASSERT_TRUE(res);
  3873. EXPECT_EQ(StatusCode::OK_200, res->status);
  3874. }
  3875. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3876. UploadFormDataItems items = {
  3877. {"text", "default text", "", ""},
  3878. {"multi_text1", "aaaaa", "", ""},
  3879. {"multi_text1", "bbbbb", "", ""},
  3880. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3881. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3882. "application/json"},
  3883. };
  3884. auto res = cli_.Post("/multipart/multi_file_values", items);
  3885. ASSERT_TRUE(res);
  3886. EXPECT_EQ(StatusCode::OK_200, res->status);
  3887. }
  3888. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3889. auto res = cli_.Get("/hi");
  3890. ASSERT_TRUE(res);
  3891. EXPECT_EQ(StatusCode::OK_200, res->status);
  3892. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3893. EXPECT_EQ("Hello World!", res->body);
  3894. }
  3895. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3896. Request req;
  3897. req.method = "POST";
  3898. req.path = "/chunked";
  3899. std::string host_and_port;
  3900. host_and_port += HOST;
  3901. host_and_port += ":";
  3902. host_and_port += std::to_string(PORT);
  3903. req.headers.emplace("Host", host_and_port.c_str());
  3904. req.headers.emplace("Accept", "*/*");
  3905. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3906. req.headers.emplace("Content-Type", "text/plain");
  3907. req.headers.emplace("Content-Length", "0");
  3908. req.headers.emplace(
  3909. "Transfer-Encoding",
  3910. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3911. // Client does not chunk, so make a chunked body manually.
  3912. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3913. auto res = std::make_shared<Response>();
  3914. auto error = Error::Success;
  3915. auto ret = cli_.send(req, *res, error);
  3916. ASSERT_TRUE(ret);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, GetStreamed2) {
  3920. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3921. ASSERT_TRUE(res);
  3922. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3923. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3924. EXPECT_EQ(true, res->has_header("Content-Range"));
  3925. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3926. EXPECT_EQ(std::string("ab"), res->body);
  3927. }
  3928. TEST_F(ServerTest, GetStreamed) {
  3929. auto res = cli_.Get("/streamed");
  3930. ASSERT_TRUE(res);
  3931. EXPECT_EQ(StatusCode::OK_200, res->status);
  3932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3933. EXPECT_EQ(std::string("aaabbb"), res->body);
  3934. }
  3935. TEST_F(ServerTest, GetStreamedWithRange1) {
  3936. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3937. ASSERT_TRUE(res);
  3938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3939. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3940. EXPECT_EQ(true, res->has_header("Content-Range"));
  3941. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3942. EXPECT_EQ(std::string("def"), res->body);
  3943. }
  3944. TEST_F(ServerTest, GetStreamedWithRange2) {
  3945. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3946. ASSERT_TRUE(res);
  3947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3948. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3949. EXPECT_EQ(true, res->has_header("Content-Range"));
  3950. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3951. EXPECT_EQ(std::string("bcdefg"), res->body);
  3952. }
  3953. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3954. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3957. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3958. EXPECT_EQ(true, res->has_header("Content-Range"));
  3959. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3960. EXPECT_EQ(std::string("efg"), res->body);
  3961. }
  3962. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3963. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3966. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3967. EXPECT_EQ(false, res->has_header("Content-Range"));
  3968. EXPECT_EQ(0U, res->body.size());
  3969. }
  3970. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3971. auto res = cli_.Get("/streamed-with-range",
  3972. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3973. "92233720368547758079223372036854775807"}});
  3974. ASSERT_TRUE(res);
  3975. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3976. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3977. EXPECT_EQ(false, res->has_header("Content-Range"));
  3978. EXPECT_EQ(0U, res->body.size());
  3979. }
  3980. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3981. auto res = cli_.Get(
  3982. "/with-range",
  3983. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  3984. {"Accept-Encoding", ""}});
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3987. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3988. EXPECT_EQ(true, res->has_header("Content-Range"));
  3989. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3990. EXPECT_EQ(std::string("abcdefg"), res->body);
  3991. }
  3992. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3993. auto res = cli_.Get("/with-range", {
  3994. {"Range", "bytes=0-"},
  3995. {"Accept-Encoding", ""},
  3996. });
  3997. ASSERT_TRUE(res);
  3998. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3999. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4000. EXPECT_EQ(true, res->has_header("Content-Range"));
  4001. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4002. EXPECT_EQ(std::string("abcdefg"), res->body);
  4003. }
  4004. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4005. auto res =
  4006. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4007. ASSERT_TRUE(res);
  4008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4009. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4010. EXPECT_EQ(false, res->has_header("Content-Range"));
  4011. EXPECT_EQ(267U, res->body.size());
  4012. // Check that both range contents are present
  4013. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4014. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4015. // Check that Content-Range headers are present for both ranges
  4016. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4017. std::string::npos);
  4018. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4019. std::string::npos);
  4020. }
  4021. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4022. Ranges ranges;
  4023. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4024. ranges.emplace_back(0, -1);
  4025. }
  4026. auto res =
  4027. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4035. auto res =
  4036. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4037. ASSERT_TRUE(res);
  4038. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4039. EXPECT_EQ(5U, res->body.size());
  4040. // Check that overlapping ranges are coalesced into a single range
  4041. EXPECT_EQ("bcdef", res->body);
  4042. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4043. // Should be single range, not multipart
  4044. EXPECT_TRUE(res->has_header("Content-Range"));
  4045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4046. }
  4047. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4048. auto res =
  4049. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4050. ASSERT_TRUE(res);
  4051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4052. EXPECT_EQ(268U, res->body.size());
  4053. // Check that both range contents are present
  4054. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4055. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4056. // Check that Content-Range headers are present for both ranges
  4057. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4058. std::string::npos);
  4059. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4060. std::string::npos);
  4061. }
  4062. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4063. auto res =
  4064. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4065. ASSERT_TRUE(res);
  4066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4067. EXPECT_EQ(269U, res->body.size());
  4068. // Check that both duplicate range contents are present
  4069. size_t first_abc = res->body.find("abc\r\n");
  4070. EXPECT_TRUE(first_abc != std::string::npos);
  4071. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4072. EXPECT_TRUE(second_abc != std::string::npos);
  4073. // Check that Content-Range headers are present for both ranges
  4074. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4075. EXPECT_TRUE(first_range != std::string::npos);
  4076. size_t second_range =
  4077. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4078. EXPECT_TRUE(second_range != std::string::npos);
  4079. }
  4080. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4081. auto res = cli_.Get("/streamed-with-range?error",
  4082. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4085. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(false, res->has_header("Content-Range"));
  4087. EXPECT_EQ(0U, res->body.size());
  4088. }
  4089. TEST_F(ServerTest, GetStreamedEndless) {
  4090. uint64_t offset = 0;
  4091. auto res = cli_.Get("/streamed-cancel",
  4092. [&](const char * /*data*/, uint64_t data_length) {
  4093. if (offset < 100) {
  4094. offset += data_length;
  4095. return true;
  4096. }
  4097. return false;
  4098. });
  4099. ASSERT_TRUE(!res);
  4100. EXPECT_EQ(Error::Canceled, res.error());
  4101. }
  4102. TEST_F(ServerTest, ClientStop) {
  4103. std::atomic_size_t count{4};
  4104. std::vector<std::thread> threads;
  4105. for (auto i = count.load(); i != 0; --i) {
  4106. threads.emplace_back([&]() {
  4107. auto res = cli_.Get("/streamed-cancel",
  4108. [&](const char *, uint64_t) { return true; });
  4109. --count;
  4110. ASSERT_TRUE(!res);
  4111. EXPECT_TRUE(res.error() == Error::Canceled ||
  4112. res.error() == Error::Read || res.error() == Error::Write);
  4113. });
  4114. }
  4115. std::this_thread::sleep_for(std::chrono::seconds(2));
  4116. while (count != 0) {
  4117. cli_.stop();
  4118. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4119. }
  4120. for (auto &t : threads) {
  4121. t.join();
  4122. }
  4123. }
  4124. TEST_F(ServerTest, GetWithRange1) {
  4125. auto res = cli_.Get("/with-range", {
  4126. make_range_header({{3, 5}}),
  4127. {"Accept-Encoding", ""},
  4128. });
  4129. ASSERT_TRUE(res);
  4130. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4131. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4132. EXPECT_EQ(true, res->has_header("Content-Range"));
  4133. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4134. EXPECT_EQ(std::string("def"), res->body);
  4135. }
  4136. TEST_F(ServerTest, GetWithRange2) {
  4137. auto res = cli_.Get("/with-range", {
  4138. make_range_header({{1, -1}}),
  4139. {"Accept-Encoding", ""},
  4140. });
  4141. ASSERT_TRUE(res);
  4142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4143. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4144. EXPECT_EQ(true, res->has_header("Content-Range"));
  4145. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4146. EXPECT_EQ(std::string("bcdefg"), res->body);
  4147. }
  4148. TEST_F(ServerTest, GetWithRange3) {
  4149. auto res = cli_.Get("/with-range", {
  4150. make_range_header({{0, 0}}),
  4151. {"Accept-Encoding", ""},
  4152. });
  4153. ASSERT_TRUE(res);
  4154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4155. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4156. EXPECT_EQ(true, res->has_header("Content-Range"));
  4157. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4158. EXPECT_EQ(std::string("a"), res->body);
  4159. }
  4160. TEST_F(ServerTest, GetWithRange4) {
  4161. auto res = cli_.Get("/with-range", {
  4162. make_range_header({{-1, 2}}),
  4163. {"Accept-Encoding", ""},
  4164. });
  4165. ASSERT_TRUE(res);
  4166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4167. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ(true, res->has_header("Content-Range"));
  4169. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4170. EXPECT_EQ(std::string("fg"), res->body);
  4171. }
  4172. TEST_F(ServerTest, GetWithRange5) {
  4173. auto res = cli_.Get("/with-range", {
  4174. make_range_header({{0, 5}}),
  4175. {"Accept-Encoding", ""},
  4176. });
  4177. ASSERT_TRUE(res);
  4178. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4179. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4180. EXPECT_EQ(true, res->has_header("Content-Range"));
  4181. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4182. EXPECT_EQ(std::string("abcdef"), res->body);
  4183. }
  4184. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4185. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4186. ASSERT_TRUE(res);
  4187. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4188. }
  4189. TEST_F(ServerTest, GetWithRangeMultipart) {
  4190. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(false, res->has_header("Content-Range"));
  4195. EXPECT_EQ(267U, res->body.size());
  4196. }
  4197. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4198. auto res =
  4199. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4200. ASSERT_TRUE(res);
  4201. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4202. }
  4203. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4204. auto res = cli_.Get("/with-range-customized-response",
  4205. {{make_range_header({{1, 2}})}});
  4206. ASSERT_TRUE(res);
  4207. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4208. EXPECT_EQ(true, res->has_header("Content-Length"));
  4209. EXPECT_EQ(false, res->has_header("Content-Range"));
  4210. EXPECT_EQ(JSON_DATA, res->body);
  4211. }
  4212. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4213. auto res = cli_.Get("/with-range-customized-response",
  4214. {{make_range_header({{1, 2}, {4, 5}})}});
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4217. EXPECT_EQ(true, res->has_header("Content-Length"));
  4218. EXPECT_EQ(false, res->has_header("Content-Range"));
  4219. EXPECT_EQ(JSON_DATA, res->body);
  4220. }
  4221. TEST_F(ServerTest, Issue1772) {
  4222. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4223. ASSERT_TRUE(res);
  4224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4225. }
  4226. TEST_F(ServerTest, Issue609) {
  4227. auto res = cli_.Delete("/issue609");
  4228. ASSERT_TRUE(res);
  4229. EXPECT_EQ(StatusCode::OK_200, res->status);
  4230. EXPECT_EQ(std::string("ok"), res->body);
  4231. }
  4232. TEST_F(ServerTest, GetStreamedChunked) {
  4233. auto res = cli_.Get("/streamed-chunked");
  4234. ASSERT_TRUE(res);
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ(std::string("123456789"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetStreamedChunked2) {
  4239. auto res = cli_.Get("/streamed-chunked2");
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::OK_200, res->status);
  4242. EXPECT_EQ(std::string("123456789"), res->body);
  4243. }
  4244. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4245. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::OK_200, res->status);
  4248. EXPECT_EQ(std::string("123456789"), res->body);
  4249. EXPECT_TRUE(res->has_header("Trailer"));
  4250. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4251. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4252. // Trailers are now stored separately from headers (security fix)
  4253. EXPECT_EQ(2U, res->trailers.size());
  4254. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4255. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4256. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4257. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4258. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4259. // Verify trailers are NOT in headers (security verification)
  4260. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4261. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4262. }
  4263. TEST_F(ServerTest, LargeChunkedPost) {
  4264. Request req;
  4265. req.method = "POST";
  4266. req.path = "/large-chunked";
  4267. std::string host_and_port;
  4268. host_and_port += HOST;
  4269. host_and_port += ":";
  4270. host_and_port += std::to_string(PORT);
  4271. req.headers.emplace("Host", host_and_port.c_str());
  4272. req.headers.emplace("Accept", "*/*");
  4273. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4274. req.headers.emplace("Content-Type", "text/plain");
  4275. req.headers.emplace("Content-Length", "0");
  4276. req.headers.emplace("Transfer-Encoding", "chunked");
  4277. std::string long_string(30 * 1024u, 'a');
  4278. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4279. // Attempt to make a large enough post to exceed OS buffers, to test that
  4280. // the server handles short reads if the full chunk data isn't available.
  4281. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4282. auto res = std::make_shared<Response>();
  4283. auto error = Error::Success;
  4284. auto ret = cli_.send(req, *res, error);
  4285. ASSERT_TRUE(ret);
  4286. EXPECT_EQ(StatusCode::OK_200, res->status);
  4287. }
  4288. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4289. auto res = cli_.Get("/remote_addr");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4293. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4294. }
  4295. TEST_F(ServerTest, GetMethodLocalAddr) {
  4296. auto res = cli_.Get("/local_addr");
  4297. ASSERT_TRUE(res);
  4298. EXPECT_EQ(StatusCode::OK_200, res->status);
  4299. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4300. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4301. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4302. }
  4303. TEST_F(ServerTest, HTTPResponseSplitting) {
  4304. auto res = cli_.Get("/http_response_splitting");
  4305. ASSERT_TRUE(res);
  4306. EXPECT_EQ(StatusCode::OK_200, res->status);
  4307. }
  4308. TEST_F(ServerTest, SlowRequest) {
  4309. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4310. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4311. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4312. }
  4313. #if 0
  4314. TEST_F(ServerTest, SlowPost) {
  4315. char buffer[64 * 1024];
  4316. memset(buffer, 0x42, sizeof(buffer));
  4317. auto res = cli_.Post(
  4318. "/slowpost", 64 * 1024 * 1024,
  4319. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4320. auto ret = sink.write(buffer, sizeof(buffer));
  4321. EXPECT_TRUE(ret);
  4322. return true;
  4323. },
  4324. "text/plain");
  4325. ASSERT_TRUE(res);
  4326. EXPECT_EQ(StatusCode::OK_200, res->status);
  4327. }
  4328. TEST_F(ServerTest, SlowPostFail) {
  4329. char buffer[64 * 1024];
  4330. memset(buffer, 0x42, sizeof(buffer));
  4331. cli_.set_write_timeout(std::chrono::seconds(0));
  4332. auto res = cli_.Post(
  4333. "/slowpost", 64 * 1024 * 1024,
  4334. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4335. sink.write(buffer, sizeof(buffer));
  4336. return true;
  4337. },
  4338. "text/plain");
  4339. ASSERT_TRUE(!res);
  4340. EXPECT_EQ(Error::Write, res.error());
  4341. }
  4342. #endif
  4343. TEST_F(ServerTest, Put) {
  4344. auto res = cli_.Put("/put", "PUT", "text/plain");
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ("PUT", res->body);
  4348. }
  4349. TEST_F(ServerTest, PutWithContentProvider) {
  4350. auto res = cli_.Put(
  4351. "/put", 3,
  4352. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4353. sink.os << "PUT";
  4354. return true;
  4355. },
  4356. "text/plain");
  4357. ASSERT_TRUE(res);
  4358. EXPECT_EQ(StatusCode::OK_200, res->status);
  4359. EXPECT_EQ("PUT", res->body);
  4360. }
  4361. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4362. auto res = cli_.Post(
  4363. "/post", 42,
  4364. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4365. return false;
  4366. },
  4367. "text/plain");
  4368. ASSERT_TRUE(!res);
  4369. EXPECT_EQ(Error::Canceled, res.error());
  4370. }
  4371. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4372. auto res = cli_.Put(
  4373. "/put",
  4374. [](size_t /*offset*/, DataSink &sink) {
  4375. sink.os << "PUT";
  4376. sink.done();
  4377. return true;
  4378. },
  4379. "text/plain");
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. EXPECT_EQ("PUT", res->body);
  4383. }
  4384. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4385. auto res = cli_.Post(
  4386. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4387. "text/plain");
  4388. ASSERT_TRUE(!res);
  4389. EXPECT_EQ(Error::Canceled, res.error());
  4390. }
  4391. TEST_F(ServerTest, PostLoopBack) {
  4392. std::string body;
  4393. auto res = cli_.Post(
  4394. "/post-loopback", 9,
  4395. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4396. EXPECT_EQ(9u, length);
  4397. sink.write("123", 3);
  4398. sink.write("456", 3);
  4399. sink.write("789", 3);
  4400. return true;
  4401. },
  4402. "text/plain",
  4403. [&body](const char *data, size_t data_length) {
  4404. body.append(data, data_length);
  4405. return true;
  4406. });
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("123456789", body);
  4410. }
  4411. TEST_F(ServerTest, PutLoopBack) {
  4412. std::string body;
  4413. auto res = cli_.Put(
  4414. "/put-loopback", 9,
  4415. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4416. EXPECT_EQ(9u, length);
  4417. sink.write("123", 3);
  4418. sink.write("456", 3);
  4419. sink.write("789", 3);
  4420. return true;
  4421. },
  4422. "text/plain",
  4423. [&body](const char *data, size_t data_length) {
  4424. body.append(data, data_length);
  4425. return true;
  4426. });
  4427. ASSERT_TRUE(res);
  4428. EXPECT_EQ(StatusCode::OK_200, res->status);
  4429. EXPECT_EQ("123456789", body);
  4430. }
  4431. TEST_F(ServerTest, PatchLoopBack) {
  4432. std::string body;
  4433. auto res = cli_.Patch(
  4434. "/patch-loopback", 9,
  4435. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4436. EXPECT_EQ(9u, length);
  4437. sink.write("123", 3);
  4438. sink.write("456", 3);
  4439. sink.write("789", 3);
  4440. return true;
  4441. },
  4442. "text/plain",
  4443. [&body](const char *data, size_t data_length) {
  4444. body.append(data, data_length);
  4445. return true;
  4446. });
  4447. ASSERT_TRUE(res);
  4448. EXPECT_EQ(StatusCode::OK_200, res->status);
  4449. EXPECT_EQ("123456789", body);
  4450. }
  4451. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4452. std::string body;
  4453. auto res = cli_.Post(
  4454. "/post-loopback",
  4455. [](size_t /*offset*/, DataSink &sink) {
  4456. sink.write("123", 3);
  4457. sink.write("456", 3);
  4458. sink.write("789", 3);
  4459. sink.done();
  4460. return true;
  4461. },
  4462. "text/plain",
  4463. [&body](const char *data, size_t data_length) {
  4464. body.append(data, data_length);
  4465. return true;
  4466. });
  4467. ASSERT_TRUE(res);
  4468. EXPECT_EQ(StatusCode::OK_200, res->status);
  4469. EXPECT_EQ("123456789", body);
  4470. }
  4471. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4472. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4473. cli_.set_compress(true);
  4474. auto res = cli_.Put(
  4475. "/put", 3,
  4476. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4477. sink.os << "PUT";
  4478. return true;
  4479. },
  4480. "text/plain");
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("PUT", res->body);
  4484. }
  4485. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4486. cli_.set_compress(true);
  4487. auto res = cli_.Post(
  4488. "/post", 42,
  4489. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4490. return false;
  4491. },
  4492. "text/plain");
  4493. ASSERT_TRUE(!res);
  4494. EXPECT_EQ(Error::Canceled, res.error());
  4495. }
  4496. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4497. cli_.set_compress(true);
  4498. auto res = cli_.Put(
  4499. "/put",
  4500. [](size_t /*offset*/, DataSink &sink) {
  4501. sink.os << "PUT";
  4502. sink.done();
  4503. return true;
  4504. },
  4505. "text/plain");
  4506. ASSERT_TRUE(res);
  4507. EXPECT_EQ(StatusCode::OK_200, res->status);
  4508. EXPECT_EQ("PUT", res->body);
  4509. }
  4510. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4511. cli_.set_compress(true);
  4512. auto res = cli_.Post(
  4513. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4514. "text/plain");
  4515. ASSERT_TRUE(!res);
  4516. EXPECT_EQ(Error::Canceled, res.error());
  4517. }
  4518. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4519. cli_.set_compress(true);
  4520. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ(LARGE_DATA, res->body);
  4524. }
  4525. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4527. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4528. Client cli(s.c_str());
  4529. cli.enable_server_certificate_verification(false);
  4530. #else
  4531. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4532. Client cli(s.c_str());
  4533. #endif
  4534. cli.set_compress(true);
  4535. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ(LARGE_DATA, res->body);
  4539. // The compressed size should be less than a 10th of the original. May vary
  4540. // depending on the zlib library.
  4541. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4542. static_cast<uint64_t>(10 * 1024 * 1024));
  4543. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4544. }
  4545. TEST_F(ServerTest, PutContentWithDeflate) {
  4546. cli_.set_compress(false);
  4547. Headers headers;
  4548. headers.emplace("Content-Encoding", "deflate");
  4549. // PUT in deflate format:
  4550. auto res = cli_.Put("/put", headers,
  4551. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4552. ASSERT_TRUE(res);
  4553. EXPECT_EQ(StatusCode::OK_200, res->status);
  4554. EXPECT_EQ("PUT", res->body);
  4555. }
  4556. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4557. Headers headers;
  4558. headers.emplace("Accept-Encoding", "gzip, deflate");
  4559. auto res = cli_.Get("/streamed-chunked", headers);
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ(std::string("123456789"), res->body);
  4563. }
  4564. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4565. Headers headers;
  4566. headers.emplace("Accept-Encoding", "gzip, deflate");
  4567. auto res = cli_.Get("/streamed-chunked2", headers);
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ(std::string("123456789"), res->body);
  4571. }
  4572. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4573. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4574. ASSERT_TRUE(res);
  4575. EXPECT_EQ(StatusCode::OK_200, res->status);
  4576. }
  4577. TEST(GzipDecompressor, ChunkedDecompression) {
  4578. std::string data;
  4579. for (size_t i = 0; i < 32 * 1024; ++i) {
  4580. data.push_back(static_cast<char>('a' + i % 26));
  4581. }
  4582. std::string compressed_data;
  4583. {
  4584. httplib::detail::gzip_compressor compressor;
  4585. bool result = compressor.compress(
  4586. data.data(), data.size(),
  4587. /*last=*/true,
  4588. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4589. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4590. compressed_data_size);
  4591. return true;
  4592. });
  4593. ASSERT_TRUE(result);
  4594. }
  4595. std::string decompressed_data;
  4596. {
  4597. httplib::detail::gzip_decompressor decompressor;
  4598. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4599. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4600. size_t chunk_size = 130;
  4601. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4602. chunk_begin += chunk_size) {
  4603. size_t current_chunk_size =
  4604. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4605. bool result = decompressor.decompress(
  4606. compressed_data.data() + chunk_begin, current_chunk_size,
  4607. [&](const char *decompressed_data_chunk,
  4608. size_t decompressed_data_chunk_size) {
  4609. decompressed_data.insert(decompressed_data.size(),
  4610. decompressed_data_chunk,
  4611. decompressed_data_chunk_size);
  4612. return true;
  4613. });
  4614. ASSERT_TRUE(result);
  4615. }
  4616. }
  4617. ASSERT_EQ(data, decompressed_data);
  4618. }
  4619. TEST(GzipDecompressor, DeflateDecompression) {
  4620. std::string original_text = "Raw deflate without gzip";
  4621. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4622. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4623. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4624. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4625. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4626. std::string decompressed_data;
  4627. {
  4628. httplib::detail::gzip_decompressor decompressor;
  4629. bool result = decompressor.decompress(
  4630. compressed_data.data(), compressed_data.size(),
  4631. [&](const char *decompressed_data_chunk,
  4632. size_t decompressed_data_chunk_size) {
  4633. decompressed_data.insert(decompressed_data.size(),
  4634. decompressed_data_chunk,
  4635. decompressed_data_chunk_size);
  4636. return true;
  4637. });
  4638. ASSERT_TRUE(result);
  4639. }
  4640. ASSERT_EQ(original_text, decompressed_data);
  4641. }
  4642. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4643. std::string original_text = "Raw deflate without gzip";
  4644. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4645. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4646. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4647. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4648. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4649. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4650. std::string decompressed_data;
  4651. {
  4652. httplib::detail::gzip_decompressor decompressor;
  4653. bool result = decompressor.decompress(
  4654. compressed_data.data(), compressed_data.size(),
  4655. [&](const char *decompressed_data_chunk,
  4656. size_t decompressed_data_chunk_size) {
  4657. decompressed_data.insert(decompressed_data.size(),
  4658. decompressed_data_chunk,
  4659. decompressed_data_chunk_size);
  4660. return true;
  4661. });
  4662. ASSERT_TRUE(result);
  4663. }
  4664. ASSERT_EQ(original_text, decompressed_data);
  4665. }
  4666. #ifdef _WIN32
  4667. TEST(GzipDecompressor, LargeRandomData) {
  4668. // prepare large random data that is difficult to be compressed and is
  4669. // expected to have large size even when compressed
  4670. std::random_device seed_gen;
  4671. std::mt19937 random(seed_gen());
  4672. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4673. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4674. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4675. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4676. // compress data over 4GiB
  4677. std::string compressed_data;
  4678. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4679. httplib::detail::gzip_compressor compressor;
  4680. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4681. data.size() * sizeof(std::uint32_t), true,
  4682. [&](const char *data, size_t size) {
  4683. compressed_data.insert(
  4684. compressed_data.size(), data, size);
  4685. return true;
  4686. });
  4687. ASSERT_TRUE(result);
  4688. // FIXME: compressed data size is expected to be greater than 4GiB,
  4689. // but there is no guarantee
  4690. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4691. // decompress data over 4GiB
  4692. std::string decompressed_data;
  4693. decompressed_data.reserve(data_size);
  4694. httplib::detail::gzip_decompressor decompressor;
  4695. result = decompressor.decompress(
  4696. compressed_data.data(), compressed_data.size(),
  4697. [&](const char *data, size_t size) {
  4698. decompressed_data.insert(decompressed_data.size(), data, size);
  4699. return true;
  4700. });
  4701. ASSERT_TRUE(result);
  4702. // compare
  4703. ASSERT_EQ(data_size, decompressed_data.size());
  4704. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4705. 0);
  4706. }
  4707. #endif
  4708. #endif
  4709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4710. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4711. Headers headers;
  4712. headers.emplace("Accept-Encoding", "br");
  4713. auto res = cli_.Get("/streamed-chunked", headers);
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. EXPECT_EQ(std::string("123456789"), res->body);
  4717. }
  4718. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4719. Headers headers;
  4720. headers.emplace("Accept-Encoding", "br");
  4721. auto res = cli_.Get("/streamed-chunked2", headers);
  4722. ASSERT_TRUE(res);
  4723. EXPECT_EQ(StatusCode::OK_200, res->status);
  4724. EXPECT_EQ(std::string("123456789"), res->body);
  4725. }
  4726. #endif
  4727. TEST_F(ServerTest, Patch) {
  4728. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4729. ASSERT_TRUE(res);
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("PATCH", res->body);
  4732. }
  4733. TEST_F(ServerTest, Delete) {
  4734. auto res = cli_.Delete("/delete");
  4735. ASSERT_TRUE(res);
  4736. EXPECT_EQ(StatusCode::OK_200, res->status);
  4737. EXPECT_EQ("DELETE", res->body);
  4738. }
  4739. TEST_F(ServerTest, DeleteContentReceiver) {
  4740. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4741. ASSERT_TRUE(res);
  4742. EXPECT_EQ(StatusCode::OK_200, res->status);
  4743. EXPECT_EQ("content", res->body);
  4744. }
  4745. TEST_F(ServerTest, Options) {
  4746. auto res = cli_.Options("*");
  4747. ASSERT_TRUE(res);
  4748. EXPECT_EQ(StatusCode::OK_200, res->status);
  4749. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4750. EXPECT_TRUE(res->body.empty());
  4751. }
  4752. TEST_F(ServerTest, URL) {
  4753. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4754. ASSERT_TRUE(res);
  4755. EXPECT_EQ(StatusCode::OK_200, res->status);
  4756. }
  4757. TEST_F(ServerTest, ArrayParam) {
  4758. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(StatusCode::OK_200, res->status);
  4761. }
  4762. TEST_F(ServerTest, NoMultipleHeaders) {
  4763. Headers headers = {{"Content-Length", "5"}};
  4764. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4765. "text/plain");
  4766. ASSERT_TRUE(res);
  4767. EXPECT_EQ(StatusCode::OK_200, res->status);
  4768. }
  4769. TEST_F(ServerTest, PostContentReceiver) {
  4770. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4771. ASSERT_TRUE(res);
  4772. ASSERT_EQ(StatusCode::OK_200, res->status);
  4773. ASSERT_EQ("content", res->body);
  4774. }
  4775. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4776. UploadFormDataItems items = {
  4777. {"text1", "text default", "", ""},
  4778. {"text2", "aωb", "", ""},
  4779. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4780. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4781. {"file3", "", "", "application/octet-stream"},
  4782. };
  4783. auto res = cli_.Post("/content_receiver", items);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. }
  4787. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4788. UploadFormDataItems items = {
  4789. {"text1", "text default", "", ""},
  4790. {"text2", "aωb", "", ""},
  4791. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4792. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4793. {"file3", "", "", "application/octet-stream"},
  4794. };
  4795. auto boundary = std::string("+++++");
  4796. std::string body;
  4797. for (const auto &item : items) {
  4798. body += "--" + boundary + "\r\n";
  4799. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4800. if (!item.filename.empty()) {
  4801. body += "; filename=\"" + item.filename + "\"";
  4802. }
  4803. body += "\r\n";
  4804. if (!item.content_type.empty()) {
  4805. body += "Content-Type: " + item.content_type + "\r\n";
  4806. }
  4807. body += "\r\n";
  4808. body += item.content + "\r\n";
  4809. }
  4810. body += "--" + boundary + "--\r\n";
  4811. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4812. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, PostContentReceiverGzip) {
  4817. cli_.set_compress(true);
  4818. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4819. ASSERT_TRUE(res);
  4820. ASSERT_EQ(StatusCode::OK_200, res->status);
  4821. ASSERT_EQ("content", res->body);
  4822. }
  4823. TEST_F(ServerTest, PutContentReceiver) {
  4824. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PatchContentReceiver) {
  4830. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4831. ASSERT_TRUE(res);
  4832. ASSERT_EQ(StatusCode::OK_200, res->status);
  4833. ASSERT_EQ("content", res->body);
  4834. }
  4835. template <typename ClientType>
  4836. void TestWithHeadersAndContentReceiver(
  4837. ClientType &cli,
  4838. std::function<Result(ClientType &, const std::string &, const Headers &,
  4839. const std::string &, const std::string &,
  4840. ContentReceiver, DownloadProgress)>
  4841. request_func) {
  4842. Headers headers;
  4843. headers.emplace("X-Custom-Header", "test-value");
  4844. std::string received_body;
  4845. auto res = request_func(
  4846. cli, "/content_receiver", headers, "content", "application/json",
  4847. [&](const char *data, size_t data_length) {
  4848. received_body.append(data, data_length);
  4849. return true;
  4850. },
  4851. nullptr);
  4852. ASSERT_TRUE(res);
  4853. EXPECT_EQ(StatusCode::OK_200, res->status);
  4854. EXPECT_EQ("content", received_body);
  4855. }
  4856. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4857. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4858. using ClientT = SSLClient;
  4859. #else
  4860. using ClientT = Client;
  4861. #endif
  4862. TestWithHeadersAndContentReceiver<ClientT>(
  4863. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4864. const std::string &body, const std::string &content_type,
  4865. ContentReceiver receiver, DownloadProgress progress) {
  4866. return cli.Post(path, headers, body, content_type, receiver, progress);
  4867. });
  4868. }
  4869. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4870. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4871. using ClientT = SSLClient;
  4872. #else
  4873. using ClientT = Client;
  4874. #endif
  4875. TestWithHeadersAndContentReceiver<ClientT>(
  4876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4877. const std::string &body, const std::string &content_type,
  4878. ContentReceiver receiver, DownloadProgress progress) {
  4879. return cli.Put(path, headers, body, content_type, receiver, progress);
  4880. });
  4881. }
  4882. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4884. using ClientT = SSLClient;
  4885. #else
  4886. using ClientT = Client;
  4887. #endif
  4888. TestWithHeadersAndContentReceiver<ClientT>(
  4889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4890. const std::string &body, const std::string &content_type,
  4891. ContentReceiver receiver, DownloadProgress progress) {
  4892. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4893. });
  4894. }
  4895. template <typename ClientType>
  4896. void TestWithHeadersAndContentReceiverWithProgress(
  4897. ClientType &cli,
  4898. std::function<Result(ClientType &, const std::string &, const Headers &,
  4899. const std::string &, const std::string &,
  4900. ContentReceiver, DownloadProgress)>
  4901. request_func) {
  4902. Headers headers;
  4903. headers.emplace("X-Test-Header", "progress-test");
  4904. std::string received_body;
  4905. auto progress_called = false;
  4906. auto res = request_func(
  4907. cli, "/content_receiver", headers, "content", "text/plain",
  4908. [&](const char *data, size_t data_length) {
  4909. received_body.append(data, data_length);
  4910. return true;
  4911. },
  4912. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4913. progress_called = true;
  4914. return true;
  4915. });
  4916. ASSERT_TRUE(res);
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("content", received_body);
  4919. EXPECT_TRUE(progress_called);
  4920. }
  4921. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4922. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4923. using ClientT = SSLClient;
  4924. #else
  4925. using ClientT = Client;
  4926. #endif
  4927. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4928. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4929. const std::string &body, const std::string &content_type,
  4930. ContentReceiver receiver, DownloadProgress progress) {
  4931. return cli.Post(path, headers, body, content_type, receiver, progress);
  4932. });
  4933. }
  4934. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4935. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4936. using ClientT = SSLClient;
  4937. #else
  4938. using ClientT = Client;
  4939. #endif
  4940. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4941. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4942. const std::string &body, const std::string &content_type,
  4943. ContentReceiver receiver, DownloadProgress progress) {
  4944. return cli.Put(path, headers, body, content_type, receiver, progress);
  4945. });
  4946. }
  4947. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  4948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4949. using ClientT = SSLClient;
  4950. #else
  4951. using ClientT = Client;
  4952. #endif
  4953. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4954. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4955. const std::string &body, const std::string &content_type,
  4956. ContentReceiver receiver, DownloadProgress progress) {
  4957. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4958. });
  4959. }
  4960. template <typename ClientType>
  4961. void TestWithHeadersAndContentReceiverError(
  4962. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  4963. const Headers &, const std::string &,
  4964. const std::string &, ContentReceiver)>
  4965. request_func) {
  4966. Headers headers;
  4967. headers.emplace("X-Error-Test", "true");
  4968. std::string received_body;
  4969. auto receiver_failed = false;
  4970. auto res =
  4971. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  4972. [&](const char *data, size_t data_length) {
  4973. received_body.append(data, data_length);
  4974. receiver_failed = true;
  4975. return false;
  4976. });
  4977. ASSERT_FALSE(res);
  4978. EXPECT_TRUE(receiver_failed);
  4979. }
  4980. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  4981. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4982. using ClientT = SSLClient;
  4983. #else
  4984. using ClientT = Client;
  4985. #endif
  4986. TestWithHeadersAndContentReceiverError<ClientT>(
  4987. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4988. const std::string &body, const std::string &content_type,
  4989. ContentReceiver receiver) {
  4990. return cli.Post(path, headers, body, content_type, receiver);
  4991. });
  4992. }
  4993. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  4994. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4995. using ClientT = SSLClient;
  4996. #else
  4997. using ClientT = Client;
  4998. #endif
  4999. TestWithHeadersAndContentReceiverError<ClientT>(
  5000. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5001. const std::string &body, const std::string &content_type,
  5002. ContentReceiver receiver) {
  5003. return cli.Put(path, headers, body, content_type, receiver);
  5004. });
  5005. }
  5006. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5008. using ClientT = SSLClient;
  5009. #else
  5010. using ClientT = Client;
  5011. #endif
  5012. TestWithHeadersAndContentReceiverError<ClientT>(
  5013. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5014. const std::string &body, const std::string &content_type,
  5015. ContentReceiver receiver) {
  5016. return cli.Patch(path, headers, body, content_type, receiver);
  5017. });
  5018. }
  5019. TEST_F(ServerTest, PostQueryStringAndBody) {
  5020. auto res =
  5021. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5022. ASSERT_TRUE(res);
  5023. ASSERT_EQ(StatusCode::OK_200, res->status);
  5024. }
  5025. TEST_F(ServerTest, HTTP2Magic) {
  5026. Request req;
  5027. req.method = "PRI";
  5028. req.path = "*";
  5029. req.body = "SM";
  5030. auto res = std::make_shared<Response>();
  5031. auto error = Error::Success;
  5032. auto ret = cli_.send(req, *res, error);
  5033. ASSERT_TRUE(ret);
  5034. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5035. }
  5036. TEST_F(ServerTest, KeepAlive) {
  5037. auto res = cli_.Get("/hi");
  5038. ASSERT_TRUE(res);
  5039. EXPECT_EQ(StatusCode::OK_200, res->status);
  5040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5041. EXPECT_EQ("Hello World!", res->body);
  5042. res = cli_.Get("/hi");
  5043. ASSERT_TRUE(res);
  5044. EXPECT_EQ(StatusCode::OK_200, res->status);
  5045. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5046. EXPECT_EQ("Hello World!", res->body);
  5047. res = cli_.Get("/hi");
  5048. ASSERT_TRUE(res);
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("Hello World!", res->body);
  5052. res = cli_.Get("/not-exist");
  5053. ASSERT_TRUE(res);
  5054. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5055. res = cli_.Post("/empty", "", "text/plain");
  5056. ASSERT_TRUE(res);
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5059. EXPECT_EQ("empty", res->body);
  5060. EXPECT_EQ("close", res->get_header_value("Connection"));
  5061. res = cli_.Post(
  5062. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5063. "text/plain");
  5064. ASSERT_TRUE(res);
  5065. EXPECT_EQ(StatusCode::OK_200, res->status);
  5066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5067. EXPECT_EQ("empty", res->body);
  5068. cli_.set_keep_alive(false);
  5069. res = cli_.Get("/last-request");
  5070. ASSERT_TRUE(res);
  5071. EXPECT_EQ(StatusCode::OK_200, res->status);
  5072. EXPECT_EQ("close", res->get_header_value("Connection"));
  5073. }
  5074. TEST_F(ServerTest, TooManyRedirect) {
  5075. cli_.set_follow_location(true);
  5076. auto res = cli_.Get("/redirect/0");
  5077. ASSERT_TRUE(!res);
  5078. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5079. }
  5080. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5081. Request req;
  5082. req.method = "FOOBAR";
  5083. req.path = "/hi";
  5084. cli_.set_keep_alive(true);
  5085. auto res = cli_.send(req);
  5086. ASSERT_TRUE(res);
  5087. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5088. EXPECT_EQ("close", res->get_header_value("Connection"));
  5089. EXPECT_FALSE(cli_.is_socket_open());
  5090. }
  5091. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5092. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5093. TEST_F(ServerTest, Gzip) {
  5094. Headers headers;
  5095. headers.emplace("Accept-Encoding", "gzip, deflate");
  5096. auto res = cli_.Get("/compress", headers);
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5102. "7890123456789012345678901234567890",
  5103. res->body);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. }
  5106. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5107. Headers headers;
  5108. headers.emplace("Accept-Encoding", "");
  5109. auto res = cli_.Get("/compress", headers);
  5110. ASSERT_TRUE(res);
  5111. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5114. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5115. "7890123456789012345678901234567890",
  5116. res->body);
  5117. EXPECT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST_F(ServerTest, GzipWithContentReceiver) {
  5120. Headers headers;
  5121. headers.emplace("Accept-Encoding", "gzip, deflate");
  5122. std::string body;
  5123. auto res = cli_.Get("/compress", headers,
  5124. [&](const char *data, uint64_t data_length) {
  5125. EXPECT_EQ(100U, data_length);
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. ASSERT_TRUE(res);
  5130. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5131. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5132. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5133. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5134. "7890123456789012345678901234567890",
  5135. body);
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. }
  5138. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5139. Headers headers;
  5140. headers.emplace("Accept-Encoding", "gzip, deflate");
  5141. cli_.set_decompress(false);
  5142. auto res = cli_.Get("/compress", headers);
  5143. ASSERT_TRUE(res);
  5144. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5146. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5147. EXPECT_EQ(33U, res->body.size());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. }
  5150. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5151. Headers headers;
  5152. headers.emplace("Accept-Encoding", "");
  5153. std::string body;
  5154. auto res = cli_.Get("/compress", headers,
  5155. [&](const char *data, uint64_t data_length) {
  5156. EXPECT_EQ(100U, data_length);
  5157. body.append(data, data_length);
  5158. return true;
  5159. });
  5160. ASSERT_TRUE(res);
  5161. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5162. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5163. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5164. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5165. "7890123456789012345678901234567890",
  5166. body);
  5167. EXPECT_EQ(StatusCode::OK_200, res->status);
  5168. }
  5169. TEST_F(ServerTest, NoGzip) {
  5170. Headers headers;
  5171. headers.emplace("Accept-Encoding", "gzip, deflate");
  5172. auto res = cli_.Get("/nocompress", headers);
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5175. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5176. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5177. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5178. "7890123456789012345678901234567890",
  5179. res->body);
  5180. EXPECT_EQ(StatusCode::OK_200, res->status);
  5181. }
  5182. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5183. Headers headers;
  5184. headers.emplace("Accept-Encoding", "gzip, deflate");
  5185. std::string body;
  5186. auto res = cli_.Get("/nocompress", headers,
  5187. [&](const char *data, uint64_t data_length) {
  5188. EXPECT_EQ(100U, data_length);
  5189. body.append(data, data_length);
  5190. return true;
  5191. });
  5192. ASSERT_TRUE(res);
  5193. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5194. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5195. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5196. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5197. "7890123456789012345678901234567890",
  5198. body);
  5199. EXPECT_EQ(StatusCode::OK_200, res->status);
  5200. }
  5201. TEST_F(ServerTest, MultipartFormDataGzip) {
  5202. UploadFormDataItems items = {
  5203. {"key1", "test", "", ""},
  5204. {"key2", "--abcdefg123", "", ""},
  5205. };
  5206. cli_.set_compress(true);
  5207. auto res = cli_.Post("/compress-multipart", items);
  5208. ASSERT_TRUE(res);
  5209. EXPECT_EQ(StatusCode::OK_200, res->status);
  5210. }
  5211. #endif
  5212. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5213. TEST_F(ServerTest, Brotli) {
  5214. Headers headers;
  5215. headers.emplace("Accept-Encoding", "br");
  5216. auto res = cli_.Get("/compress", headers);
  5217. ASSERT_TRUE(res);
  5218. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5220. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5221. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5222. "7890123456789012345678901234567890",
  5223. res->body);
  5224. EXPECT_EQ(StatusCode::OK_200, res->status);
  5225. }
  5226. #endif
  5227. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5228. TEST_F(ServerTest, Zstd) {
  5229. Headers headers;
  5230. headers.emplace("Accept-Encoding", "zstd");
  5231. auto res = cli_.Get("/compress", headers);
  5232. ASSERT_TRUE(res);
  5233. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5234. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5235. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5236. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5237. "7890123456789012345678901234567890",
  5238. res->body);
  5239. EXPECT_EQ(StatusCode::OK_200, res->status);
  5240. }
  5241. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5242. Headers headers;
  5243. headers.emplace("Accept-Encoding", "");
  5244. auto res = cli_.Get("/compress", headers);
  5245. ASSERT_TRUE(res);
  5246. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5249. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5250. "7890123456789012345678901234567890",
  5251. res->body);
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. }
  5254. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5255. Headers headers;
  5256. headers.emplace("Accept-Encoding", "zstd");
  5257. std::string body;
  5258. auto res = cli_.Get("/compress", headers,
  5259. [&](const char *data, uint64_t data_length) {
  5260. EXPECT_EQ(100U, data_length);
  5261. body.append(data, data_length);
  5262. return true;
  5263. });
  5264. ASSERT_TRUE(res);
  5265. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5266. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5267. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5268. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5269. "7890123456789012345678901234567890",
  5270. body);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5274. Headers headers;
  5275. headers.emplace("Accept-Encoding", "zstd");
  5276. cli_.set_decompress(false);
  5277. auto res = cli_.Get("/compress", headers);
  5278. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5279. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5280. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5281. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5282. ASSERT_TRUE(res);
  5283. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5285. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. ASSERT_EQ(26U, res->body.size());
  5288. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5289. 0);
  5290. }
  5291. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5292. Headers headers;
  5293. headers.emplace("Accept-Encoding", "");
  5294. std::string body;
  5295. auto res = cli_.Get("/compress", headers,
  5296. [&](const char *data, uint64_t data_length) {
  5297. EXPECT_EQ(100U, data_length);
  5298. body.append(data, data_length);
  5299. return true;
  5300. });
  5301. ASSERT_TRUE(res);
  5302. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5304. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5305. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5306. "7890123456789012345678901234567890",
  5307. body);
  5308. EXPECT_EQ(StatusCode::OK_200, res->status);
  5309. }
  5310. TEST_F(ServerTest, NoZstd) {
  5311. Headers headers;
  5312. headers.emplace("Accept-Encoding", "zstd");
  5313. auto res = cli_.Get("/nocompress", headers);
  5314. ASSERT_TRUE(res);
  5315. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5316. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5317. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5318. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5319. "7890123456789012345678901234567890",
  5320. res->body);
  5321. EXPECT_EQ(StatusCode::OK_200, res->status);
  5322. }
  5323. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5324. Headers headers;
  5325. headers.emplace("Accept-Encoding", "zstd");
  5326. std::string body;
  5327. auto res = cli_.Get("/nocompress", headers,
  5328. [&](const char *data, uint64_t data_length) {
  5329. EXPECT_EQ(100U, data_length);
  5330. body.append(data, data_length);
  5331. return true;
  5332. });
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5335. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5336. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5337. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5338. "7890123456789012345678901234567890",
  5339. body);
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. }
  5342. // TODO: How to enable zstd ??
  5343. TEST_F(ServerTest, MultipartFormDataZstd) {
  5344. UploadFormDataItems items = {
  5345. {"key1", "test", "", ""},
  5346. {"key2", "--abcdefg123", "", ""},
  5347. };
  5348. Headers headers;
  5349. headers.emplace("Accept-Encoding", "zstd");
  5350. cli_.set_compress(true);
  5351. auto res = cli_.Post("/compress-multipart", headers, items);
  5352. ASSERT_TRUE(res);
  5353. EXPECT_EQ(StatusCode::OK_200, res->status);
  5354. }
  5355. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5356. Headers headers;
  5357. headers.emplace("Accept-Encoding", "zstd");
  5358. cli_.set_compress(true);
  5359. auto res = cli_.Put(
  5360. "/put", headers, 3,
  5361. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5362. sink.os << "PUT";
  5363. return true;
  5364. },
  5365. "text/plain");
  5366. ASSERT_TRUE(res);
  5367. EXPECT_EQ(StatusCode::OK_200, res->status);
  5368. EXPECT_EQ("PUT", res->body);
  5369. }
  5370. // Pre-compression logging tests
  5371. TEST_F(ServerTest, PreCompressionLogging) {
  5372. // Test data for compression (matches the actual /compress endpoint content)
  5373. const std::string test_content =
  5374. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5375. "3456789012345678901234567890";
  5376. // Variables to capture logging data
  5377. std::string pre_compression_body;
  5378. std::string pre_compression_content_type;
  5379. std::string pre_compression_content_encoding;
  5380. std::string post_compression_body;
  5381. std::string post_compression_content_type;
  5382. std::string post_compression_content_encoding;
  5383. // Set up pre-compression logger
  5384. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5385. const Response &res) {
  5386. pre_compression_body = res.body;
  5387. pre_compression_content_type = res.get_header_value("Content-Type");
  5388. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5389. });
  5390. // Set up post-compression logger
  5391. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5392. post_compression_body = res.body;
  5393. post_compression_content_type = res.get_header_value("Content-Type");
  5394. post_compression_content_encoding =
  5395. res.get_header_value("Content-Encoding");
  5396. });
  5397. // Test with gzip compression
  5398. Headers headers;
  5399. headers.emplace("Accept-Encoding", "gzip");
  5400. auto res = cli_.Get("/compress", headers);
  5401. // Verify response was compressed
  5402. ASSERT_TRUE(res);
  5403. EXPECT_EQ(StatusCode::OK_200, res->status);
  5404. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5405. // Verify pre-compression logger captured uncompressed content
  5406. EXPECT_EQ(test_content, pre_compression_body);
  5407. EXPECT_EQ("text/plain", pre_compression_content_type);
  5408. EXPECT_TRUE(pre_compression_content_encoding
  5409. .empty()); // No encoding header before compression
  5410. // Verify post-compression logger captured compressed content
  5411. EXPECT_NE(test_content,
  5412. post_compression_body); // Should be different after compression
  5413. EXPECT_EQ("text/plain", post_compression_content_type);
  5414. EXPECT_EQ("gzip", post_compression_content_encoding);
  5415. // Verify compressed content is smaller
  5416. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5417. }
  5418. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5419. const std::string test_content =
  5420. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5421. "3456789012345678901234567890";
  5422. std::string pre_compression_body;
  5423. std::string post_compression_body;
  5424. svr_.set_pre_compression_logger(
  5425. [&](const Request & /*req*/, const Response &res) {
  5426. pre_compression_body = res.body;
  5427. });
  5428. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5429. post_compression_body = res.body;
  5430. });
  5431. Headers headers;
  5432. headers.emplace("Accept-Encoding", "br");
  5433. auto res = cli_.Get("/compress", headers);
  5434. ASSERT_TRUE(res);
  5435. EXPECT_EQ(StatusCode::OK_200, res->status);
  5436. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5437. // Verify pre-compression content is uncompressed
  5438. EXPECT_EQ(test_content, pre_compression_body);
  5439. // Verify post-compression content is compressed
  5440. EXPECT_NE(test_content, post_compression_body);
  5441. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5442. }
  5443. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5444. const std::string test_content =
  5445. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5446. "3456789012345678901234567890";
  5447. std::string pre_compression_body;
  5448. std::string post_compression_body;
  5449. svr_.set_pre_compression_logger(
  5450. [&](const Request & /*req*/, const Response &res) {
  5451. pre_compression_body = res.body;
  5452. });
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. });
  5456. // Request without compression (use /nocompress endpoint)
  5457. Headers headers;
  5458. auto res = cli_.Get("/nocompress", headers);
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(StatusCode::OK_200, res->status);
  5461. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5462. // Pre-compression logger should not be called when no compression is applied
  5463. EXPECT_TRUE(
  5464. pre_compression_body.empty()); // Pre-compression logger not called
  5465. EXPECT_EQ(
  5466. test_content,
  5467. post_compression_body); // Post-compression logger captures final content
  5468. }
  5469. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5470. const std::string test_content =
  5471. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5472. "3456789012345678901234567890";
  5473. std::string pre_compression_body;
  5474. bool pre_logger_called = false;
  5475. // Set only pre-compression logger
  5476. svr_.set_pre_compression_logger(
  5477. [&](const Request & /*req*/, const Response &res) {
  5478. pre_compression_body = res.body;
  5479. pre_logger_called = true;
  5480. });
  5481. Headers headers;
  5482. headers.emplace("Accept-Encoding", "gzip");
  5483. auto res = cli_.Get("/compress", headers);
  5484. ASSERT_TRUE(res);
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5487. // Verify pre-compression logger was called
  5488. EXPECT_TRUE(pre_logger_called);
  5489. EXPECT_EQ(test_content, pre_compression_body);
  5490. }
  5491. TEST(ZstdDecompressor, ChunkedDecompression) {
  5492. std::string data;
  5493. for (size_t i = 0; i < 32 * 1024; ++i) {
  5494. data.push_back(static_cast<char>('a' + i % 26));
  5495. }
  5496. std::string compressed_data;
  5497. {
  5498. httplib::detail::zstd_compressor compressor;
  5499. bool result = compressor.compress(
  5500. data.data(), data.size(),
  5501. /*last=*/true,
  5502. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5503. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5504. compressed_data_size);
  5505. return true;
  5506. });
  5507. ASSERT_TRUE(result);
  5508. }
  5509. std::string decompressed_data;
  5510. {
  5511. httplib::detail::zstd_decompressor decompressor;
  5512. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5513. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5514. size_t chunk_size = 130;
  5515. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5516. chunk_begin += chunk_size) {
  5517. size_t current_chunk_size =
  5518. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5519. bool result = decompressor.decompress(
  5520. compressed_data.data() + chunk_begin, current_chunk_size,
  5521. [&](const char *decompressed_data_chunk,
  5522. size_t decompressed_data_chunk_size) {
  5523. decompressed_data.insert(decompressed_data.size(),
  5524. decompressed_data_chunk,
  5525. decompressed_data_chunk_size);
  5526. return true;
  5527. });
  5528. ASSERT_TRUE(result);
  5529. }
  5530. }
  5531. ASSERT_EQ(data, decompressed_data);
  5532. }
  5533. TEST(ZstdDecompressor, Decompress) {
  5534. std::string original_text = "Compressed with ZSTD";
  5535. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5536. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5537. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5538. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5539. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5540. std::string decompressed_data;
  5541. {
  5542. httplib::detail::zstd_decompressor decompressor;
  5543. bool result = decompressor.decompress(
  5544. compressed_data.data(), compressed_data.size(),
  5545. [&](const char *decompressed_data_chunk,
  5546. size_t decompressed_data_chunk_size) {
  5547. decompressed_data.insert(decompressed_data.size(),
  5548. decompressed_data_chunk,
  5549. decompressed_data_chunk_size);
  5550. return true;
  5551. });
  5552. ASSERT_TRUE(result);
  5553. }
  5554. ASSERT_EQ(original_text, decompressed_data);
  5555. }
  5556. #endif
  5557. // Sends a raw request to a server listening at HOST:PORT.
  5558. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5559. std::string *resp = nullptr) {
  5560. auto error = Error::Success;
  5561. auto client_sock = detail::create_client_socket(
  5562. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5563. /*connection_timeout_sec=*/5, 0,
  5564. /*read_timeout_sec=*/5, 0,
  5565. /*write_timeout_sec=*/5, 0, std::string(), error);
  5566. if (client_sock == INVALID_SOCKET) { return false; }
  5567. auto ret = detail::process_client_socket(
  5568. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5569. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5570. if (req.size() !=
  5571. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5572. return false;
  5573. }
  5574. char buf[512];
  5575. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5576. while (line_reader.getline()) {
  5577. if (resp) { *resp += line_reader.ptr(); }
  5578. }
  5579. return true;
  5580. });
  5581. detail::close_socket(client_sock);
  5582. return ret;
  5583. }
  5584. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5585. Server svr;
  5586. std::string header_value;
  5587. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5588. header_value = req.get_header_value("foo");
  5589. res.set_content("ok", "text/plain");
  5590. });
  5591. thread t = thread([&] { svr.listen(HOST, PORT); });
  5592. auto se = detail::scope_exit([&] {
  5593. svr.stop();
  5594. t.join();
  5595. ASSERT_FALSE(svr.is_running());
  5596. });
  5597. svr.wait_until_ready();
  5598. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5599. // like characters are not treated the same - use vertical tab and escape.
  5600. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5601. "foo: \t \v bar \x1B\t \r\n"
  5602. "Connection: close\r\n"
  5603. "\r\n";
  5604. std::string res;
  5605. ASSERT_TRUE(send_request(5, req, &res));
  5606. EXPECT_EQ(header_value, "");
  5607. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5608. }
  5609. // Sends a raw request and verifies that there isn't a crash or exception.
  5610. static void test_raw_request(const std::string &req,
  5611. std::string *out = nullptr) {
  5612. Server svr;
  5613. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5614. res.set_content("ok", "text/plain");
  5615. });
  5616. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5617. res.set_content("ok", "text/plain");
  5618. });
  5619. svr.Get("/header_field_value_check",
  5620. [&](const Request & /*req*/, Response &res) {
  5621. res.set_content("ok", "text/plain");
  5622. });
  5623. // Server read timeout must be longer than the client read timeout for the
  5624. // bug to reproduce, probably to force the server to process a request
  5625. // without a trailing blank line.
  5626. const time_t client_read_timeout_sec = 1;
  5627. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5628. bool listen_thread_ok = false;
  5629. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5630. auto se = detail::scope_exit([&] {
  5631. svr.stop();
  5632. t.join();
  5633. ASSERT_FALSE(svr.is_running());
  5634. EXPECT_TRUE(listen_thread_ok);
  5635. });
  5636. svr.wait_until_ready();
  5637. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5638. }
  5639. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5640. // A certain header line causes an exception if the header property is parsed
  5641. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5642. test_raw_request(
  5643. "GET /hi HTTP/1.1\r\n"
  5644. " : "
  5645. " "
  5646. " ");
  5647. }
  5648. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5649. // A certain header line causes an exception if the header property *name* is
  5650. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5651. // greedy matcher and requires backtracking when there are a lot of ":"
  5652. // characters.
  5653. // This occurs with libc++ but not libstdc++.
  5654. test_raw_request(
  5655. "GET /hi HTTP/1.1\r\n"
  5656. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5657. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5658. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5659. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5660. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5661. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5662. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5663. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5664. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5665. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5666. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5667. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5668. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5669. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5670. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5671. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5672. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5673. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5674. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5675. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5676. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5677. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5678. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5679. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5680. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5681. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5682. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5683. "&&&%%%");
  5684. }
  5685. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5686. // Make sure this doesn't crash the server.
  5687. // In a previous version of the header line regex, the "\r" rendered the line
  5688. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5689. // a new position where the leading white space ended and the field value
  5690. // began.
  5691. // The crash occurs with libc++ but not libstdc++.
  5692. test_raw_request("GET /hi HTTP/1.1\r\n"
  5693. "a:" +
  5694. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5695. "\r\n"
  5696. "\r\n");
  5697. }
  5698. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5699. std::string out;
  5700. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5701. "Content-Type: text/plain\r\n"
  5702. "Transfer-Encoding: chunked\r\n"
  5703. "\r\n"
  5704. "nothex\r\n",
  5705. &out);
  5706. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5707. }
  5708. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5709. std::string out;
  5710. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5711. "Content-Type: text/plain\r\n"
  5712. "Transfer-Encoding: chunked\r\n"
  5713. "\r\n"
  5714. "3\r\n"
  5715. "xyz\r\n"
  5716. "NaN\r\n",
  5717. &out);
  5718. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5719. }
  5720. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5721. std::string out;
  5722. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5723. "Content-Type: text/plain\r\n"
  5724. "Transfer-Encoding: chunked\r\n"
  5725. "\r\n"
  5726. // Length is too large for 64 bits.
  5727. "1ffffffffffffffff\r\n"
  5728. "xyz\r\n",
  5729. &out);
  5730. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5731. }
  5732. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5733. test_raw_request("GET /hi HTTP/1.1\r\n"
  5734. "Content-Type: text/plain\r\n\r");
  5735. }
  5736. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5737. std::string out;
  5738. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5739. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5740. }
  5741. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5742. std::string out;
  5743. std::string request(
  5744. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5745. test_raw_request(request, &out);
  5746. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5747. }
  5748. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5749. std::string out;
  5750. std::string request(
  5751. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5752. test_raw_request(request, &out);
  5753. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5754. }
  5755. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5756. std::string out;
  5757. std::string request(
  5758. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5759. test_raw_request(request, &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5763. std::string out;
  5764. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5765. "Test: \r\n\r\n",
  5766. &out);
  5767. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5768. }
  5769. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5770. Server svr;
  5771. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5772. res.set_header("Cache-Control", "no-cache");
  5773. res.set_chunked_content_provider(
  5774. "text/event-stream", [](size_t offset, DataSink &sink) {
  5775. std::string s = "data:";
  5776. s += std::to_string(offset);
  5777. s += "\n\n";
  5778. auto ret = sink.write(s.data(), s.size());
  5779. EXPECT_TRUE(ret);
  5780. std::this_thread::sleep_for(std::chrono::seconds(1));
  5781. return true;
  5782. });
  5783. });
  5784. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5785. svr.wait_until_ready();
  5786. Client client(HOST, PORT);
  5787. const Headers headers = {{"Accept", "text/event-stream"}};
  5788. auto get_thread = std::thread([&client, &headers]() {
  5789. auto res = client.Get(
  5790. "/events", headers,
  5791. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5792. });
  5793. auto se = detail::scope_exit([&] {
  5794. svr.stop();
  5795. get_thread.join();
  5796. listen_thread.join();
  5797. ASSERT_FALSE(svr.is_running());
  5798. });
  5799. // Give GET time to get a few messages.
  5800. std::this_thread::sleep_for(std::chrono::seconds(2));
  5801. }
  5802. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5803. httplib::Server svr;
  5804. svr.Post("/hi",
  5805. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5806. res.status = StatusCode::OK_200;
  5807. });
  5808. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5809. svr.wait_until_ready();
  5810. Client cli(HOST, PORT);
  5811. auto res = cli.Post("/hi", "data", "text/plain");
  5812. ASSERT_TRUE(res);
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. svr.stop();
  5815. thread.join();
  5816. ASSERT_FALSE(svr.is_running());
  5817. res = cli.Post("/hi", "data", "text/plain");
  5818. ASSERT_FALSE(res);
  5819. }
  5820. TEST(ServerStopTest, ListenFailure) {
  5821. Server svr;
  5822. auto t = thread([&]() {
  5823. auto ret = svr.listen("????", PORT);
  5824. EXPECT_FALSE(ret);
  5825. });
  5826. svr.wait_until_ready();
  5827. svr.stop();
  5828. t.join();
  5829. }
  5830. TEST(ServerStopTest, Decommision) {
  5831. Server svr;
  5832. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5833. for (int i = 0; i < 4; i++) {
  5834. auto is_even = !(i % 2);
  5835. std::thread t{[&] {
  5836. try {
  5837. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5838. if (is_even) {
  5839. throw std::runtime_error("Some thing that happens to go wrong.");
  5840. }
  5841. svr.listen(HOST, PORT);
  5842. } catch (...) { svr.decommission(); }
  5843. }};
  5844. svr.wait_until_ready();
  5845. // Server is up
  5846. {
  5847. Client cli(HOST, PORT);
  5848. auto res = cli.Get("/hi");
  5849. if (is_even) {
  5850. EXPECT_FALSE(res);
  5851. } else {
  5852. EXPECT_TRUE(res);
  5853. EXPECT_EQ("hi...", res->body);
  5854. }
  5855. }
  5856. svr.stop();
  5857. t.join();
  5858. // Server is down...
  5859. {
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/hi");
  5862. EXPECT_FALSE(res);
  5863. }
  5864. }
  5865. }
  5866. // Helper function for string body upload progress tests
  5867. template <typename SetupHandler, typename ClientCall>
  5868. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5869. ClientCall &&client_call,
  5870. const string &body) {
  5871. Server svr;
  5872. setup_handler(svr);
  5873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5874. auto se = detail::scope_exit([&] {
  5875. svr.stop();
  5876. t.join();
  5877. });
  5878. svr.wait_until_ready();
  5879. Client cli(HOST, PORT);
  5880. vector<uint64_t> progress_values;
  5881. bool progress_called = false;
  5882. auto res =
  5883. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5884. progress_values.push_back(current);
  5885. progress_called = true;
  5886. return true;
  5887. });
  5888. ASSERT_TRUE(res);
  5889. EXPECT_EQ(200, res->status);
  5890. EXPECT_TRUE(progress_called);
  5891. }
  5892. TEST(UploadProgressTest, PostStringBodyBasic) {
  5893. TestStringBodyUploadProgress(
  5894. [](Server &svr) {
  5895. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5896. res.set_content("received", "text/plain");
  5897. });
  5898. },
  5899. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5900. return cli.Post("/test", body, "text/plain", progress_callback);
  5901. },
  5902. "test data for upload progress");
  5903. }
  5904. TEST(UploadProgressTest, PutStringBodyBasic) {
  5905. TestStringBodyUploadProgress(
  5906. [](Server &svr) {
  5907. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5908. res.set_content("put received", "text/plain");
  5909. });
  5910. },
  5911. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5912. return cli.Put("/test", body, "text/plain", progress_callback);
  5913. },
  5914. "put test data for upload progress");
  5915. }
  5916. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5917. TestStringBodyUploadProgress(
  5918. [](Server &svr) {
  5919. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5920. res.set_content("patch received", "text/plain");
  5921. });
  5922. },
  5923. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5924. return cli.Patch("/test", body, "text/plain", progress_callback);
  5925. },
  5926. "patch test data for upload progress");
  5927. }
  5928. // Helper function for content provider upload progress tests
  5929. template <typename SetupHandler, typename ClientCall>
  5930. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5931. ClientCall &&client_call) {
  5932. Server svr;
  5933. setup_handler(svr);
  5934. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5935. auto se = detail::scope_exit([&] {
  5936. svr.stop();
  5937. t.join();
  5938. });
  5939. svr.wait_until_ready();
  5940. Client cli(HOST, PORT);
  5941. vector<uint64_t> progress_values;
  5942. auto res =
  5943. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5944. progress_values.push_back(current);
  5945. return true;
  5946. });
  5947. ASSERT_TRUE(res);
  5948. EXPECT_EQ(200, res->status);
  5949. EXPECT_FALSE(progress_values.empty());
  5950. }
  5951. TEST(UploadProgressTest, PostContentProviderProgress) {
  5952. TestContentProviderUploadProgress(
  5953. [](Server &svr) {
  5954. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5955. res.set_content("provider received", "text/plain");
  5956. });
  5957. },
  5958. [](Client &cli, UploadProgress progress_callback) {
  5959. return cli.Post(
  5960. "/test", 10,
  5961. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5962. sink.os << "test data";
  5963. return true;
  5964. },
  5965. "text/plain", progress_callback);
  5966. });
  5967. }
  5968. // Helper function for multipart upload progress tests
  5969. template <typename SetupHandler, typename ClientCall>
  5970. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  5971. ClientCall &&client_call,
  5972. const string &endpoint) {
  5973. Server svr;
  5974. setup_handler(svr);
  5975. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5976. auto se = detail::scope_exit([&] {
  5977. svr.stop();
  5978. t.join();
  5979. });
  5980. svr.wait_until_ready();
  5981. Client cli(HOST, PORT);
  5982. vector<uint64_t> progress_values;
  5983. UploadFormDataItems items = {
  5984. {"field1", "value1", "", ""},
  5985. {"field2", "longer value for progress tracking test", "", ""},
  5986. {"file1", "file content data for upload progress", "test.txt",
  5987. "text/plain"}};
  5988. auto res = client_call(cli, endpoint, items,
  5989. [&](uint64_t current, uint64_t /*total*/) -> bool {
  5990. progress_values.push_back(current);
  5991. return true;
  5992. });
  5993. ASSERT_TRUE(res);
  5994. EXPECT_EQ(200, res->status);
  5995. EXPECT_FALSE(progress_values.empty());
  5996. }
  5997. TEST(UploadProgressTest, PostMultipartProgress) {
  5998. TestMultipartUploadProgress(
  5999. [](Server &svr) {
  6000. svr.Post("/multipart", [](const Request &req, Response &res) {
  6001. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6002. res.set_content("multipart received", "text/plain");
  6003. });
  6004. },
  6005. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6006. UploadProgress progress_callback) {
  6007. return cli.Post(endpoint, items, progress_callback);
  6008. },
  6009. "/multipart");
  6010. }
  6011. // Helper function for basic download progress tests
  6012. template <typename SetupHandler, typename ClientCall>
  6013. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6014. ClientCall &&client_call, const string &endpoint,
  6015. size_t expected_content_size) {
  6016. Server svr;
  6017. setup_handler(svr);
  6018. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6019. auto se = detail::scope_exit([&] {
  6020. svr.stop();
  6021. t.join();
  6022. });
  6023. svr.wait_until_ready();
  6024. Client cli(HOST, PORT);
  6025. vector<uint64_t> progress_values;
  6026. auto res = client_call(cli, endpoint,
  6027. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6028. progress_values.push_back(current);
  6029. return true;
  6030. });
  6031. ASSERT_TRUE(res);
  6032. EXPECT_EQ(200, res->status);
  6033. EXPECT_FALSE(progress_values.empty());
  6034. EXPECT_EQ(expected_content_size, res->body.size());
  6035. }
  6036. TEST(DownloadProgressTest, GetBasic) {
  6037. TestBasicDownloadProgress(
  6038. [](Server &svr) {
  6039. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6040. string content(1000, 'D');
  6041. res.set_content(content, "text/plain");
  6042. });
  6043. },
  6044. [](Client &cli, const string &endpoint,
  6045. DownloadProgress progress_callback) {
  6046. return cli.Get(endpoint, progress_callback);
  6047. },
  6048. "/download", 1000u);
  6049. }
  6050. // Helper function for content receiver download progress tests
  6051. template <typename SetupHandler, typename ClientCall>
  6052. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6053. ClientCall &&client_call,
  6054. const string &endpoint,
  6055. size_t expected_content_size) {
  6056. Server svr;
  6057. setup_handler(svr);
  6058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6059. auto se = detail::scope_exit([&] {
  6060. svr.stop();
  6061. t.join();
  6062. });
  6063. svr.wait_until_ready();
  6064. Client cli(HOST, PORT);
  6065. vector<uint64_t> progress_values;
  6066. string received_body;
  6067. auto res = client_call(
  6068. cli, endpoint,
  6069. [&](const char *data, size_t data_length) -> bool {
  6070. received_body.append(data, data_length);
  6071. return true;
  6072. },
  6073. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6074. progress_values.push_back(current);
  6075. return true;
  6076. });
  6077. ASSERT_TRUE(res);
  6078. EXPECT_EQ(200, res->status);
  6079. EXPECT_FALSE(progress_values.empty());
  6080. EXPECT_EQ(expected_content_size, received_body.size());
  6081. EXPECT_TRUE(res->body.empty());
  6082. }
  6083. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6084. TestContentReceiverDownloadProgress(
  6085. [](Server &svr) {
  6086. svr.Get("/download-receiver",
  6087. [](const Request & /*req*/, Response &res) {
  6088. string content(2000, 'R');
  6089. res.set_content(content, "text/plain");
  6090. });
  6091. },
  6092. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6093. DownloadProgress progress_callback) {
  6094. return cli.Get(endpoint, content_receiver, progress_callback);
  6095. },
  6096. "/download-receiver", 2000u);
  6097. }
  6098. TEST(StreamingTest, NoContentLengthStreaming) {
  6099. Server svr;
  6100. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6101. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6102. if (offset < 6) {
  6103. sink.os << (offset < 3 ? "a" : "b");
  6104. } else {
  6105. sink.done();
  6106. }
  6107. return true;
  6108. });
  6109. });
  6110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6111. auto listen_se = detail::scope_exit([&] {
  6112. svr.stop();
  6113. listen_thread.join();
  6114. ASSERT_FALSE(svr.is_running());
  6115. });
  6116. svr.wait_until_ready();
  6117. Client client(HOST, PORT);
  6118. auto get_thread = std::thread([&client]() {
  6119. std::string s;
  6120. auto res =
  6121. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6122. s += std::string(data, len);
  6123. return true;
  6124. });
  6125. ASSERT_TRUE(res);
  6126. EXPECT_EQ(StatusCode::OK_200, res->status);
  6127. EXPECT_EQ("aaabbb", s);
  6128. });
  6129. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6130. // Give GET time to get a few messages.
  6131. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6132. }
  6133. TEST(MountTest, Unmount) {
  6134. Server svr;
  6135. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6136. auto se = detail::scope_exit([&] {
  6137. svr.stop();
  6138. listen_thread.join();
  6139. ASSERT_FALSE(svr.is_running());
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli("localhost", PORT);
  6143. svr.set_mount_point("/mount2", "./www2");
  6144. auto res = cli.Get("/");
  6145. ASSERT_TRUE(res);
  6146. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6147. res = cli.Get("/mount2/dir/test.html");
  6148. ASSERT_TRUE(res);
  6149. EXPECT_EQ(StatusCode::OK_200, res->status);
  6150. svr.set_mount_point("/", "./www");
  6151. res = cli.Get("/dir/");
  6152. ASSERT_TRUE(res);
  6153. EXPECT_EQ(StatusCode::OK_200, res->status);
  6154. svr.remove_mount_point("/");
  6155. res = cli.Get("/dir/");
  6156. ASSERT_TRUE(res);
  6157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6158. svr.remove_mount_point("/mount2");
  6159. res = cli.Get("/mount2/dir/test.html");
  6160. ASSERT_TRUE(res);
  6161. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6162. }
  6163. TEST(MountTest, Redicect) {
  6164. Server svr;
  6165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6166. auto se = detail::scope_exit([&] {
  6167. svr.stop();
  6168. listen_thread.join();
  6169. ASSERT_FALSE(svr.is_running());
  6170. });
  6171. svr.set_mount_point("/", "./www");
  6172. svr.wait_until_ready();
  6173. Client cli("localhost", PORT);
  6174. auto res = cli.Get("/dir/");
  6175. ASSERT_TRUE(res);
  6176. EXPECT_EQ(StatusCode::OK_200, res->status);
  6177. res = cli.Get("/dir");
  6178. ASSERT_TRUE(res);
  6179. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6180. res = cli.Get("/file");
  6181. ASSERT_TRUE(res);
  6182. EXPECT_EQ(StatusCode::OK_200, res->status);
  6183. res = cli.Get("/file/");
  6184. ASSERT_TRUE(res);
  6185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6186. cli.set_follow_location(true);
  6187. res = cli.Get("/dir");
  6188. ASSERT_TRUE(res);
  6189. EXPECT_EQ(StatusCode::OK_200, res->status);
  6190. }
  6191. TEST(MountTest, MultibytesPathName) {
  6192. Server svr;
  6193. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6194. auto se = detail::scope_exit([&] {
  6195. svr.stop();
  6196. listen_thread.join();
  6197. ASSERT_FALSE(svr.is_running());
  6198. });
  6199. svr.set_mount_point("/", "./www");
  6200. svr.wait_until_ready();
  6201. Client cli("localhost", PORT);
  6202. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6206. }
  6207. TEST(KeepAliveTest, ReadTimeout) {
  6208. Server svr;
  6209. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6210. std::this_thread::sleep_for(std::chrono::seconds(2));
  6211. res.set_content("a", "text/plain");
  6212. });
  6213. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6214. res.set_content("b", "text/plain");
  6215. });
  6216. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6217. auto se = detail::scope_exit([&] {
  6218. svr.stop();
  6219. listen_thread.join();
  6220. ASSERT_FALSE(svr.is_running());
  6221. });
  6222. svr.wait_until_ready();
  6223. Client cli("localhost", PORT);
  6224. cli.set_keep_alive(true);
  6225. cli.set_read_timeout(std::chrono::seconds(1));
  6226. auto resa = cli.Get("/a");
  6227. ASSERT_FALSE(resa);
  6228. EXPECT_EQ(Error::Read, resa.error());
  6229. auto resb = cli.Get("/b");
  6230. ASSERT_TRUE(resb);
  6231. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6232. EXPECT_EQ("b", resb->body);
  6233. }
  6234. TEST(KeepAliveTest, MaxCount) {
  6235. size_t keep_alive_max_count = 3;
  6236. Server svr;
  6237. svr.set_keep_alive_max_count(keep_alive_max_count);
  6238. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6239. res.set_content("Hello World!", "text/plain");
  6240. });
  6241. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6242. auto se = detail::scope_exit([&] {
  6243. svr.stop();
  6244. listen_thread.join();
  6245. ASSERT_FALSE(svr.is_running());
  6246. });
  6247. svr.wait_until_ready();
  6248. Client cli(HOST, PORT);
  6249. cli.set_keep_alive(true);
  6250. for (size_t i = 0; i < 5; i++) {
  6251. auto result = cli.Get("/hi");
  6252. ASSERT_TRUE(result);
  6253. EXPECT_EQ(StatusCode::OK_200, result->status);
  6254. if (i == keep_alive_max_count - 1) {
  6255. EXPECT_EQ("close", result->get_header_value("Connection"));
  6256. } else {
  6257. EXPECT_FALSE(result->has_header("Connection"));
  6258. }
  6259. }
  6260. }
  6261. TEST(KeepAliveTest, Issue1041) {
  6262. Server svr;
  6263. svr.set_keep_alive_timeout(3);
  6264. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6265. res.set_content("Hello World!", "text/plain");
  6266. });
  6267. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6268. auto se = detail::scope_exit([&] {
  6269. svr.stop();
  6270. listen_thread.join();
  6271. ASSERT_FALSE(svr.is_running());
  6272. });
  6273. svr.wait_until_ready();
  6274. Client cli(HOST, PORT);
  6275. cli.set_keep_alive(true);
  6276. auto result = cli.Get("/hi");
  6277. ASSERT_TRUE(result);
  6278. EXPECT_EQ(StatusCode::OK_200, result->status);
  6279. std::this_thread::sleep_for(std::chrono::seconds(5));
  6280. result = cli.Get("/hi");
  6281. ASSERT_TRUE(result);
  6282. EXPECT_EQ(StatusCode::OK_200, result->status);
  6283. }
  6284. TEST(KeepAliveTest, Issue1959) {
  6285. Server svr;
  6286. svr.set_keep_alive_timeout(5);
  6287. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6288. res.set_content("a", "text/plain");
  6289. });
  6290. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6291. auto se = detail::scope_exit([&] {
  6292. if (!svr.is_running()) return;
  6293. svr.stop();
  6294. listen_thread.join();
  6295. ASSERT_FALSE(svr.is_running());
  6296. });
  6297. svr.wait_until_ready();
  6298. Client cli("localhost", PORT);
  6299. cli.set_keep_alive(true);
  6300. using namespace std::chrono;
  6301. auto start = steady_clock::now();
  6302. cli.Get("/a");
  6303. svr.stop();
  6304. listen_thread.join();
  6305. auto end = steady_clock::now();
  6306. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6307. EXPECT_LT(elapsed, 5000);
  6308. }
  6309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6310. TEST(KeepAliveTest, SSLClientReconnection) {
  6311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6312. ASSERT_TRUE(svr.is_valid());
  6313. svr.set_keep_alive_timeout(1);
  6314. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6315. res.set_content("Hello World!", "text/plain");
  6316. });
  6317. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6318. auto se = detail::scope_exit([&] {
  6319. svr.stop();
  6320. listen_thread.join();
  6321. ASSERT_FALSE(svr.is_running());
  6322. });
  6323. svr.wait_until_ready();
  6324. SSLClient cli(HOST, PORT);
  6325. cli.enable_server_certificate_verification(false);
  6326. cli.set_keep_alive(true);
  6327. auto result = cli.Get("/hi");
  6328. ASSERT_TRUE(result);
  6329. EXPECT_EQ(StatusCode::OK_200, result->status);
  6330. result = cli.Get("/hi");
  6331. ASSERT_TRUE(result);
  6332. EXPECT_EQ(StatusCode::OK_200, result->status);
  6333. std::this_thread::sleep_for(std::chrono::seconds(2));
  6334. // Recoonect
  6335. result = cli.Get("/hi");
  6336. ASSERT_TRUE(result);
  6337. EXPECT_EQ(StatusCode::OK_200, result->status);
  6338. result = cli.Get("/hi");
  6339. ASSERT_TRUE(result);
  6340. EXPECT_EQ(StatusCode::OK_200, result->status);
  6341. }
  6342. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6344. ASSERT_TRUE(svr.is_valid());
  6345. svr.set_keep_alive_timeout(1);
  6346. std::string content = "reconnect";
  6347. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6348. res.set_content("Hello World!", "text/plain");
  6349. });
  6350. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6351. auto se = detail::scope_exit([&] {
  6352. svr.stop();
  6353. listen_thread.join();
  6354. ASSERT_FALSE(svr.is_running());
  6355. });
  6356. svr.wait_until_ready();
  6357. SSLClient cli(HOST, PORT);
  6358. cli.enable_server_certificate_verification(false);
  6359. cli.set_keep_alive(true);
  6360. auto result = cli.Post(
  6361. "/hi", content.size(),
  6362. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6363. sink.write(content.c_str(), content.size());
  6364. return true;
  6365. },
  6366. "text/plain");
  6367. ASSERT_TRUE(result);
  6368. EXPECT_EQ(200, result->status);
  6369. std::this_thread::sleep_for(std::chrono::seconds(2));
  6370. // Recoonect
  6371. result = cli.Post(
  6372. "/hi", content.size(),
  6373. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6374. sink.write(content.c_str(), content.size());
  6375. return true;
  6376. },
  6377. "text/plain");
  6378. ASSERT_TRUE(result);
  6379. EXPECT_EQ(200, result->status);
  6380. result = cli.Post(
  6381. "/hi", content.size(),
  6382. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6383. sink.write(content.c_str(), content.size());
  6384. return true;
  6385. },
  6386. "text/plain");
  6387. ASSERT_TRUE(result);
  6388. EXPECT_EQ(200, result->status);
  6389. }
  6390. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6391. {
  6392. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6393. ASSERT_TRUE(svr.is_valid());
  6394. svr.Get("/sni", [&](const Request &req, Response &res) {
  6395. std::string expected;
  6396. if (req.ssl) {
  6397. if (const char *sni =
  6398. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6399. expected = sni;
  6400. }
  6401. }
  6402. EXPECT_EQ(expected, req.get_param_value("expected"));
  6403. res.set_content("ok", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. {
  6413. SSLClient cli("localhost", PORT);
  6414. cli.enable_server_certificate_verification(false);
  6415. auto res = cli.Get("/sni?expected=localhost");
  6416. ASSERT_TRUE(res);
  6417. }
  6418. {
  6419. SSLClient cli("::1", PORT);
  6420. cli.enable_server_certificate_verification(false);
  6421. auto res = cli.Get("/sni?expected=");
  6422. // NOTE: This may fail if the server is listening on IPv4 only
  6423. // (e.g., when localhost resolves to 127.0.0.1 only)
  6424. if (res) {
  6425. EXPECT_EQ(StatusCode::OK_200, res->status);
  6426. } else {
  6427. EXPECT_EQ(Error::Connection, res.error());
  6428. }
  6429. }
  6430. }
  6431. }
  6432. #endif
  6433. TEST(ClientProblemDetectionTest, ContentProvider) {
  6434. Server svr;
  6435. size_t content_length = 1024 * 1024;
  6436. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6437. res.set_content_provider(
  6438. content_length, "text/plain",
  6439. [&](size_t offset, size_t length, DataSink &sink) {
  6440. auto out_len = std::min(length, static_cast<size_t>(1024));
  6441. std::string out(out_len, '@');
  6442. sink.write(out.data(), out_len);
  6443. return offset < 4096;
  6444. },
  6445. [](bool success) { ASSERT_FALSE(success); });
  6446. });
  6447. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6448. res.set_content_provider(
  6449. 0, "text/plain",
  6450. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6451. EXPECT_TRUE(false);
  6452. return true;
  6453. },
  6454. [](bool success) { ASSERT_FALSE(success); });
  6455. });
  6456. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6457. auto se = detail::scope_exit([&] {
  6458. svr.stop();
  6459. listen_thread.join();
  6460. ASSERT_FALSE(svr.is_running());
  6461. });
  6462. svr.wait_until_ready();
  6463. Client cli("localhost", PORT);
  6464. {
  6465. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6466. size_t /*data_length*/) { return false; });
  6467. ASSERT_FALSE(res);
  6468. }
  6469. {
  6470. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6471. size_t /*data_length*/) { return false; });
  6472. ASSERT_TRUE(res);
  6473. }
  6474. }
  6475. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6476. Server svr;
  6477. svr.set_error_handler([](Request const &, Response &res) -> void {
  6478. res.set_chunked_content_provider(
  6479. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6480. sink.os << "hello";
  6481. sink.os << "world";
  6482. sink.done();
  6483. return true;
  6484. });
  6485. });
  6486. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6487. auto se = detail::scope_exit([&] {
  6488. svr.stop();
  6489. listen_thread.join();
  6490. ASSERT_FALSE(svr.is_running());
  6491. });
  6492. svr.wait_until_ready();
  6493. Client cli("localhost", PORT);
  6494. auto res = cli.Get("/");
  6495. ASSERT_TRUE(res);
  6496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6497. EXPECT_EQ("helloworld", res->body);
  6498. }
  6499. TEST(LongPollingTest, ClientCloseDetection) {
  6500. Server svr;
  6501. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6502. res.set_chunked_content_provider(
  6503. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6504. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6505. sink.os << "hello";
  6506. auto count = 10;
  6507. while (count > 0 && sink.is_writable()) {
  6508. this_thread::sleep_for(chrono::milliseconds(10));
  6509. count--;
  6510. }
  6511. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6512. return true;
  6513. });
  6514. });
  6515. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6516. auto se = detail::scope_exit([&] {
  6517. svr.stop();
  6518. listen_thread.join();
  6519. ASSERT_FALSE(svr.is_running());
  6520. });
  6521. svr.wait_until_ready();
  6522. Client cli("localhost", PORT);
  6523. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6524. EXPECT_EQ("hello", string(data, data_length));
  6525. return false; // close the socket immediately.
  6526. });
  6527. ASSERT_FALSE(res);
  6528. }
  6529. TEST(GetWithParametersTest, GetWithParameters) {
  6530. Server svr;
  6531. svr.Get("/", [&](const Request &req, Response &) {
  6532. EXPECT_EQ("world", req.get_param_value("hello"));
  6533. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6534. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6535. });
  6536. svr.Get("/params", [&](const Request &req, Response &) {
  6537. EXPECT_EQ("world", req.get_param_value("hello"));
  6538. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6539. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6540. });
  6541. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6542. EXPECT_EQ("resource-id", req.matches[1]);
  6543. EXPECT_EQ("foo", req.get_param_value("param1"));
  6544. EXPECT_EQ("bar", req.get_param_value("param2"));
  6545. });
  6546. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6547. EXPECT_EQ("user-id", req.path_params.at("id"));
  6548. EXPECT_EQ("foo", req.get_param_value("param1"));
  6549. EXPECT_EQ("bar", req.get_param_value("param2"));
  6550. });
  6551. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6552. auto se = detail::scope_exit([&] {
  6553. svr.stop();
  6554. listen_thread.join();
  6555. ASSERT_FALSE(svr.is_running());
  6556. });
  6557. svr.wait_until_ready();
  6558. {
  6559. Client cli(HOST, PORT);
  6560. Params params;
  6561. params.emplace("hello", "world");
  6562. params.emplace("hello2", "world2");
  6563. params.emplace("hello3", "world3");
  6564. auto res = cli.Get("/", params, Headers{});
  6565. ASSERT_TRUE(res);
  6566. EXPECT_EQ(StatusCode::OK_200, res->status);
  6567. }
  6568. {
  6569. Client cli(HOST, PORT);
  6570. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6571. ASSERT_TRUE(res);
  6572. EXPECT_EQ(StatusCode::OK_200, res->status);
  6573. }
  6574. {
  6575. Client cli(HOST, PORT);
  6576. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6577. ASSERT_TRUE(res);
  6578. EXPECT_EQ(StatusCode::OK_200, res->status);
  6579. }
  6580. {
  6581. Client cli(HOST, PORT);
  6582. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6583. ASSERT_TRUE(res);
  6584. EXPECT_EQ(StatusCode::OK_200, res->status);
  6585. }
  6586. }
  6587. TEST(GetWithParametersTest, GetWithParameters2) {
  6588. Server svr;
  6589. svr.Get("/", [&](const Request &req, Response &res) {
  6590. auto text = req.get_param_value("hello");
  6591. res.set_content(text, "text/plain");
  6592. });
  6593. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6594. auto se = detail::scope_exit([&] {
  6595. svr.stop();
  6596. listen_thread.join();
  6597. ASSERT_FALSE(svr.is_running());
  6598. });
  6599. svr.wait_until_ready();
  6600. Client cli("localhost", PORT);
  6601. Params params;
  6602. params.emplace("hello", "world");
  6603. std::string body;
  6604. auto res = cli.Get("/", params, Headers{},
  6605. [&](const char *data, size_t data_length) {
  6606. body.append(data, data_length);
  6607. return true;
  6608. });
  6609. ASSERT_TRUE(res);
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. EXPECT_EQ("world", body);
  6612. }
  6613. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6614. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6615. auto host = "httpbin.org";
  6616. auto path = std::string{"/range/32"};
  6617. #else
  6618. auto host = "nghttp2.org";
  6619. auto path = std::string{"/httpbin/range/32"};
  6620. #endif
  6621. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6622. SSLClient cli(host);
  6623. #else
  6624. Client cli(host);
  6625. #endif
  6626. cli.set_default_headers({make_range_header({{1, 10}})});
  6627. cli.set_connection_timeout(5);
  6628. {
  6629. auto res = cli.Get(path);
  6630. ASSERT_TRUE(res);
  6631. EXPECT_EQ("bcdefghijk", res->body);
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. }
  6634. {
  6635. auto res = cli.Get(path);
  6636. ASSERT_TRUE(res);
  6637. EXPECT_EQ("bcdefghijk", res->body);
  6638. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6639. }
  6640. }
  6641. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6642. Server svr;
  6643. svr.set_default_headers({{"Hello", "World"}});
  6644. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6645. res.set_content("ok", "text/plain");
  6646. });
  6647. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6648. auto se = detail::scope_exit([&] {
  6649. svr.stop();
  6650. listen_thread.join();
  6651. ASSERT_FALSE(svr.is_running());
  6652. });
  6653. svr.wait_until_ready();
  6654. Client cli("localhost", PORT);
  6655. auto res = cli.Get("/");
  6656. ASSERT_TRUE(res);
  6657. EXPECT_EQ(StatusCode::OK_200, res->status);
  6658. EXPECT_EQ("ok", res->body);
  6659. EXPECT_EQ("World", res->get_header_value("Hello"));
  6660. }
  6661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6662. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6663. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6664. ASSERT_TRUE(svr.is_valid());
  6665. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6666. std::this_thread::sleep_for(std::chrono::seconds(2));
  6667. res.set_content("a", "text/plain");
  6668. });
  6669. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6670. res.set_content("b", "text/plain");
  6671. });
  6672. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6673. auto se = detail::scope_exit([&] {
  6674. svr.stop();
  6675. listen_thread.join();
  6676. ASSERT_FALSE(svr.is_running());
  6677. });
  6678. svr.wait_until_ready();
  6679. SSLClient cli("localhost", PORT);
  6680. cli.enable_server_certificate_verification(false);
  6681. cli.set_keep_alive(true);
  6682. cli.set_read_timeout(std::chrono::seconds(1));
  6683. auto resa = cli.Get("/a");
  6684. ASSERT_TRUE(!resa);
  6685. EXPECT_EQ(Error::Read, resa.error());
  6686. auto resb = cli.Get("/b");
  6687. ASSERT_TRUE(resb);
  6688. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6689. EXPECT_EQ("b", resb->body);
  6690. }
  6691. #endif
  6692. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6693. protected:
  6694. ServerTestWithAI_PASSIVE()
  6695. : cli_(HOST, PORT)
  6696. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6697. ,
  6698. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6699. #endif
  6700. {
  6701. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6702. cli_.enable_server_certificate_verification(false);
  6703. #endif
  6704. }
  6705. virtual void SetUp() {
  6706. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6707. res.set_content("Hello World!", "text/plain");
  6708. });
  6709. t_ = thread(
  6710. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6711. svr_.wait_until_ready();
  6712. }
  6713. virtual void TearDown() {
  6714. svr_.stop();
  6715. t_.join();
  6716. }
  6717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6718. SSLClient cli_;
  6719. SSLServer svr_;
  6720. #else
  6721. Client cli_;
  6722. Server svr_;
  6723. #endif
  6724. thread t_;
  6725. };
  6726. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6727. auto res = cli_.Get("/hi");
  6728. ASSERT_TRUE(res);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6731. EXPECT_EQ("Hello World!", res->body);
  6732. }
  6733. class ServerUpDownTest : public ::testing::Test {
  6734. protected:
  6735. ServerUpDownTest() : cli_(HOST, PORT) {}
  6736. virtual void SetUp() {
  6737. t_ = thread([&]() {
  6738. svr_.bind_to_any_port(HOST);
  6739. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6740. ASSERT_TRUE(svr_.listen_after_bind());
  6741. });
  6742. svr_.wait_until_ready();
  6743. }
  6744. virtual void TearDown() {
  6745. svr_.stop();
  6746. t_.join();
  6747. }
  6748. Client cli_;
  6749. Server svr_;
  6750. thread t_;
  6751. };
  6752. TEST_F(ServerUpDownTest, QuickStartStop) {
  6753. // Should not crash, especially when run with
  6754. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6755. }
  6756. class PayloadMaxLengthTest : public ::testing::Test {
  6757. protected:
  6758. PayloadMaxLengthTest()
  6759. : cli_(HOST, PORT)
  6760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6761. ,
  6762. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6763. #endif
  6764. {
  6765. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6766. cli_.enable_server_certificate_verification(false);
  6767. #endif
  6768. }
  6769. virtual void SetUp() {
  6770. svr_.set_payload_max_length(8);
  6771. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6772. res.set_content("test", "text/plain");
  6773. });
  6774. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6775. svr_.wait_until_ready();
  6776. }
  6777. virtual void TearDown() {
  6778. svr_.stop();
  6779. t_.join();
  6780. }
  6781. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6782. SSLClient cli_;
  6783. SSLServer svr_;
  6784. #else
  6785. Client cli_;
  6786. Server svr_;
  6787. #endif
  6788. thread t_;
  6789. };
  6790. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6791. auto res = cli_.Post("/test", "123456789", "text/plain");
  6792. ASSERT_TRUE(res);
  6793. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6794. res = cli_.Post("/test", "12345678", "text/plain");
  6795. ASSERT_TRUE(res);
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. }
  6798. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6799. // Test chunked encoding with payload exceeding the 8-byte limit
  6800. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6801. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6802. ASSERT_TRUE(res);
  6803. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6804. }
  6805. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6806. // Test chunked encoding with payload within the 8-byte limit
  6807. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6808. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6809. ASSERT_TRUE(res);
  6810. EXPECT_EQ(StatusCode::OK_200, res->status);
  6811. }
  6812. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6813. // Test using send_request to send chunked data exceeding payload limit
  6814. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6815. "Host: " +
  6816. std::string(HOST) + ":" + std::to_string(PORT) +
  6817. "\r\n"
  6818. "Transfer-Encoding: chunked\r\n"
  6819. "Connection: close\r\n"
  6820. "\r\n"
  6821. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6822. "0123456789\r\n"
  6823. "0\r\n" // End chunk
  6824. "\r\n";
  6825. std::string response;
  6826. bool result = send_request(1, chunked_request, &response);
  6827. if (!result) {
  6828. // If send_request fails, it might be because the server closed the
  6829. // connection due to payload limit enforcement, which is acceptable
  6830. SUCCEED()
  6831. << "Server rejected oversized chunked request (connection closed)";
  6832. } else {
  6833. // If we got a response, check if it's an error response or connection was
  6834. // closed early Short response length indicates connection was closed due to
  6835. // payload limit
  6836. if (response.length() <= 10) {
  6837. SUCCEED() << "Server closed connection for oversized chunked request";
  6838. } else {
  6839. // Check for error status codes
  6840. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6841. response.find("Payload Too Large") != std::string::npos ||
  6842. response.find("400") != std::string::npos);
  6843. }
  6844. }
  6845. }
  6846. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6847. // Test request without Content-Length header exceeding payload limit
  6848. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6849. "Host: " +
  6850. std::string(HOST) + ":" +
  6851. std::to_string(PORT) +
  6852. "\r\n"
  6853. "Connection: close\r\n"
  6854. "\r\n";
  6855. // Add payload exceeding the 8-byte limit
  6856. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6857. request_without_content_length += large_payload;
  6858. std::string response;
  6859. bool result = send_request(1, request_without_content_length, &response);
  6860. if (!result) {
  6861. // If send_request fails, server likely closed connection due to payload
  6862. // limit
  6863. SUCCEED() << "Server rejected oversized request without Content-Length "
  6864. "(connection closed)";
  6865. } else {
  6866. // Check if server responded with error or closed connection early
  6867. if (response.length() <= 10) {
  6868. SUCCEED() << "Server closed connection for oversized request without "
  6869. "Content-Length";
  6870. } else {
  6871. // Check for error status codes
  6872. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6873. response.find("Payload Too Large") != std::string::npos ||
  6874. response.find("400") != std::string::npos);
  6875. }
  6876. }
  6877. }
  6878. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6879. // Test request without Content-Length header within payload limit
  6880. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6881. "Host: " +
  6882. std::string(HOST) + ":" +
  6883. std::to_string(PORT) +
  6884. "\r\n"
  6885. "Connection: close\r\n"
  6886. "\r\n";
  6887. // Add payload within the 8-byte limit
  6888. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6889. request_without_content_length += small_payload;
  6890. std::string response;
  6891. bool result = send_request(1, request_without_content_length, &response);
  6892. // For requests without Content-Length, the server may have different behavior
  6893. // The key is that it should not reject due to payload limit for small
  6894. // payloads
  6895. if (result) {
  6896. // Check for any HTTP response (success or error, but not connection closed)
  6897. if (response.length() > 10) {
  6898. SUCCEED()
  6899. << "Server processed request without Content-Length within limit";
  6900. } else {
  6901. // Short response might indicate connection closed, which is acceptable
  6902. SUCCEED() << "Server closed connection for request without "
  6903. "Content-Length (acceptable behavior)";
  6904. }
  6905. } else {
  6906. // Connection failure might be due to protocol requirements
  6907. SUCCEED() << "Connection issue with request without Content-Length "
  6908. "(environment-specific)";
  6909. }
  6910. }
  6911. class LargePayloadMaxLengthTest : public ::testing::Test {
  6912. protected:
  6913. LargePayloadMaxLengthTest()
  6914. : cli_(HOST, PORT)
  6915. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6916. ,
  6917. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6918. #endif
  6919. {
  6920. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6921. cli_.enable_server_certificate_verification(false);
  6922. #endif
  6923. }
  6924. virtual void SetUp() {
  6925. // Set 10MB payload limit
  6926. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6927. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6928. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6929. res.set_content("Large payload test", "text/plain");
  6930. });
  6931. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6932. svr_.wait_until_ready();
  6933. }
  6934. virtual void TearDown() {
  6935. svr_.stop();
  6936. t_.join();
  6937. }
  6938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6939. SSLClient cli_;
  6940. SSLServer svr_;
  6941. #else
  6942. Client cli_;
  6943. Server svr_;
  6944. #endif
  6945. thread t_;
  6946. };
  6947. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  6948. // Test chunked encoding with payload within 10MB limit
  6949. std::string medium_payload(5 * 1024 * 1024,
  6950. 'A'); // 5MB payload, within 10MB limit
  6951. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  6952. ASSERT_TRUE(res);
  6953. EXPECT_EQ(StatusCode::OK_200, res->status);
  6954. }
  6955. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  6956. // Test chunked encoding with payload exceeding 10MB limit
  6957. std::string large_payload(12 * 1024 * 1024,
  6958. 'B'); // 12MB payload, exceeds 10MB limit
  6959. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  6960. ASSERT_TRUE(res);
  6961. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6962. }
  6963. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  6964. // Test request without Content-Length header within 10MB limit
  6965. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6966. "Host: " +
  6967. std::string(HOST) + ":" +
  6968. std::to_string(PORT) +
  6969. "\r\n"
  6970. "Connection: close\r\n"
  6971. "\r\n";
  6972. // Add 1MB payload (within 10MB limit)
  6973. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  6974. request_without_content_length += medium_payload;
  6975. std::string response;
  6976. bool result = send_request(5, request_without_content_length, &response);
  6977. if (result) {
  6978. // Should get a proper HTTP response for payloads within limit
  6979. if (response.length() > 10) {
  6980. SUCCEED() << "Server processed 1MB request without Content-Length within "
  6981. "10MB limit";
  6982. } else {
  6983. SUCCEED() << "Server closed connection (acceptable behavior for no "
  6984. "Content-Length)";
  6985. }
  6986. } else {
  6987. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  6988. }
  6989. }
  6990. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  6991. // Test request without Content-Length header exceeding 10MB limit
  6992. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6993. "Host: " +
  6994. std::string(HOST) + ":" +
  6995. std::to_string(PORT) +
  6996. "\r\n"
  6997. "Connection: close\r\n"
  6998. "\r\n";
  6999. // Add 12MB payload (exceeds 10MB limit)
  7000. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7001. request_without_content_length += large_payload;
  7002. std::string response;
  7003. bool result = send_request(10, request_without_content_length, &response);
  7004. if (!result) {
  7005. // Server should close connection due to payload limit
  7006. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7007. "(connection closed)";
  7008. } else {
  7009. // Check for error response
  7010. if (response.length() <= 10) {
  7011. SUCCEED()
  7012. << "Server closed connection for 12MB request exceeding 10MB limit";
  7013. } else {
  7014. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7015. response.find("Payload Too Large") != std::string::npos ||
  7016. response.find("400") != std::string::npos);
  7017. }
  7018. }
  7019. }
  7020. TEST(HostAndPortPropertiesTest, NoSSL) {
  7021. httplib::Client cli("www.google.com", 1234);
  7022. ASSERT_EQ("www.google.com", cli.host());
  7023. ASSERT_EQ(1234, cli.port());
  7024. }
  7025. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7026. httplib::Client cli("www.google.com:1234");
  7027. ASSERT_EQ("www.google.com", cli.host());
  7028. ASSERT_EQ(1234, cli.port());
  7029. }
  7030. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7031. TEST(HostAndPortPropertiesTest, SSL) {
  7032. httplib::SSLClient cli("www.google.com");
  7033. ASSERT_EQ("www.google.com", cli.host());
  7034. ASSERT_EQ(443, cli.port());
  7035. }
  7036. #endif
  7037. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7038. TEST(SSLClientTest, UpdateCAStore) {
  7039. httplib::SSLClient httplib_client("www.google.com");
  7040. auto ca_store_1 = X509_STORE_new();
  7041. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7042. nullptr);
  7043. httplib_client.set_ca_cert_store(ca_store_1);
  7044. auto ca_store_2 = X509_STORE_new();
  7045. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7046. nullptr);
  7047. httplib_client.set_ca_cert_store(ca_store_2);
  7048. }
  7049. TEST(SSLClientTest, ServerNameIndication_Online) {
  7050. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7051. auto host = "httpbin.org";
  7052. auto path = std::string{"/get"};
  7053. #else
  7054. auto host = "nghttp2.org";
  7055. auto path = std::string{"/httpbin/get"};
  7056. #endif
  7057. SSLClient cli(host, 443);
  7058. auto res = cli.Get(path);
  7059. ASSERT_TRUE(res);
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. }
  7062. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7063. // Use a site that will cause SSL verification failure due to self-signed cert
  7064. SSLClient cli("self-signed.badssl.com", 443);
  7065. cli.enable_server_certificate_verification(true);
  7066. auto res = cli.Get("/");
  7067. ASSERT_TRUE(!res);
  7068. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7069. // For SSL server verification errors, ssl_error should be 0, only
  7070. // ssl_openssl_error should be set
  7071. EXPECT_EQ(0, res.ssl_error());
  7072. // Verify OpenSSL error is captured for SSLServerVerification
  7073. // This occurs when SSL_get_verify_result() returns a verification failure
  7074. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7075. res.ssl_openssl_error());
  7076. }
  7077. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7078. // Use a site where hostname doesn't match the certificate
  7079. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7080. SSLClient cli("wrong.host.badssl.com", 443);
  7081. cli.enable_server_certificate_verification(true);
  7082. cli.enable_server_hostname_verification(true);
  7083. auto res = cli.Get("/");
  7084. ASSERT_TRUE(!res);
  7085. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7086. // For SSL hostname verification errors, ssl_error should be 0, only
  7087. // ssl_openssl_error should be set
  7088. EXPECT_EQ(0, res.ssl_error());
  7089. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7090. // This occurs when verify_host() fails due to hostname mismatch
  7091. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7092. res.ssl_openssl_error());
  7093. }
  7094. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7095. Client cli("https://google.com");
  7096. auto res = cli.Get("/");
  7097. ASSERT_TRUE(res);
  7098. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7099. }
  7100. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7101. SSLClient cli("google.com");
  7102. cli.set_ca_cert_path(CA_CERT_FILE);
  7103. auto res = cli.Get("/");
  7104. ASSERT_TRUE(res);
  7105. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7106. }
  7107. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7108. SSLClient cli("google.com");
  7109. cli.enable_server_certificate_verification(true);
  7110. cli.set_ca_cert_path("hello");
  7111. auto res = cli.Get("/");
  7112. ASSERT_TRUE(!res);
  7113. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7114. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7115. // should be set
  7116. EXPECT_EQ(0, res.ssl_error());
  7117. // Verify OpenSSL error is captured for SSLLoadingCerts
  7118. // This error occurs when SSL_CTX_load_verify_locations() fails
  7119. // > openssl errstr 0x80000002
  7120. // error:80000002:system library::No such file or directory
  7121. // > openssl errstr 0xA000126
  7122. // error:0A000126:SSL routines::unexpected eof while reading
  7123. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7124. res.ssl_openssl_error() == 0xA000126);
  7125. }
  7126. TEST(SSLClientTest, ServerCertificateVerification4) {
  7127. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7128. ASSERT_TRUE(svr.is_valid());
  7129. svr.Get("/test", [&](const Request &, Response &res) {
  7130. res.set_content("test", "text/plain");
  7131. svr.stop();
  7132. ASSERT_TRUE(true);
  7133. });
  7134. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7135. auto se = detail::scope_exit([&] {
  7136. t.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. SSLClient cli("127.0.0.1", PORT);
  7141. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7142. cli.enable_server_certificate_verification(true);
  7143. cli.set_connection_timeout(30);
  7144. auto res = cli.Get("/test");
  7145. ASSERT_TRUE(res);
  7146. ASSERT_EQ(StatusCode::OK_200, res->status);
  7147. }
  7148. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7149. std::string cert;
  7150. read_file(CA_CERT_FILE, cert);
  7151. SSLClient cli("google.com");
  7152. cli.load_ca_cert_store(cert.data(), cert.size());
  7153. const auto res = cli.Get("/");
  7154. ASSERT_TRUE(res);
  7155. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7156. }
  7157. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7158. // clang-format off
  7159. static constexpr char cert[] =
  7160. "GlobalSign Root CA\n"
  7161. "==================\n"
  7162. "-----BEGIN CERTIFICATE-----\n"
  7163. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7164. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7165. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7166. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7167. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7168. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7169. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7170. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7171. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7172. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7173. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7174. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7175. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7176. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7177. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7178. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7179. "-----END CERTIFICATE-----\n";
  7180. // clang-format on
  7181. SSLClient cli("google.com");
  7182. cli.load_ca_cert_store(cert, sizeof(cert));
  7183. const auto res = cli.Get("/");
  7184. ASSERT_TRUE(res);
  7185. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7186. }
  7187. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7188. SSLClient cli("www.youtube.com");
  7189. cli.set_ca_cert_path(CA_CERT_FILE);
  7190. cli.enable_server_certificate_verification(true);
  7191. cli.set_follow_location(true);
  7192. auto res = cli.Get("/");
  7193. ASSERT_TRUE(res);
  7194. ASSERT_EQ(StatusCode::OK_200, res->status);
  7195. }
  7196. TEST(SSLClientTest, Issue2004_Online) {
  7197. Client client("https://google.com");
  7198. client.set_follow_location(true);
  7199. auto res = client.Get("/");
  7200. ASSERT_TRUE(res);
  7201. ASSERT_EQ(StatusCode::OK_200, res->status);
  7202. auto body = res->body;
  7203. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7204. }
  7205. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7206. // Create SSLClient with invalid cert/key to make is_valid() return false
  7207. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7208. "nonexistent_key.pem");
  7209. // is_valid() should be false due to cert loading failure
  7210. ASSERT_FALSE(cli.is_valid());
  7211. auto res = cli.Get("/");
  7212. ASSERT_FALSE(res);
  7213. EXPECT_EQ(Error::SSLConnection, res.error());
  7214. }
  7215. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7216. // Test for Issue #2251: SSL error not properly reported when client cert
  7217. // and key paths are swapped or mismatched
  7218. // This simulates the scenario where user accidentally swaps the cert and key
  7219. // files
  7220. // Using client cert file as private key and vice versa (completely wrong)
  7221. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7222. // Should fail validation due to cert/key mismatch
  7223. ASSERT_FALSE(cli.is_valid());
  7224. // Attempt to make a request should fail with proper error
  7225. auto res = cli.Get("/");
  7226. ASSERT_FALSE(res);
  7227. EXPECT_EQ(Error::SSLConnection, res.error());
  7228. // SSL error should be recorded in the Result object (this is the key fix for
  7229. // Issue #2251)
  7230. auto openssl_error = res.ssl_openssl_error();
  7231. EXPECT_NE(0u, openssl_error);
  7232. }
  7233. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7234. // Another variant: using valid file paths but with mismatched cert/key pair
  7235. // This tests the case where files exist but contain incompatible key material
  7236. // Using client cert with wrong key (cert2 key)
  7237. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7238. // Should fail validation
  7239. ASSERT_FALSE(cli.is_valid());
  7240. auto res = cli.Get("/");
  7241. ASSERT_FALSE(res);
  7242. // Must report error properly, not appear as success
  7243. EXPECT_EQ(Error::SSLConnection, res.error());
  7244. // OpenSSL error should be captured in Result
  7245. EXPECT_NE(0u, res.ssl_openssl_error());
  7246. }
  7247. #if 0
  7248. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7249. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  7250. ASSERT_TRUE(cli != nullptr);
  7251. cli->set_address_family(AF_INET6);
  7252. cli->set_interface("en0");
  7253. auto res = cli->Get("/get");
  7254. ASSERT_TRUE(res);
  7255. ASSERT_EQ(StatusCode::OK_200, res->status);
  7256. }
  7257. #endif
  7258. void ClientCertPresent(
  7259. const std::string &client_cert_file,
  7260. const std::string &client_private_key_file,
  7261. const std::string &client_encrypted_private_key_pass = std::string()) {
  7262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7263. CLIENT_CA_CERT_DIR);
  7264. ASSERT_TRUE(svr.is_valid());
  7265. svr.Get("/test", [&](const Request &req, Response &res) {
  7266. res.set_content("test", "text/plain");
  7267. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7268. ASSERT_TRUE(peer_cert != nullptr);
  7269. auto subject_name = X509_get_subject_name(peer_cert);
  7270. ASSERT_TRUE(subject_name != nullptr);
  7271. std::string common_name;
  7272. {
  7273. char name[BUFSIZ];
  7274. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7275. name, sizeof(name));
  7276. common_name.assign(name, static_cast<size_t>(name_len));
  7277. }
  7278. EXPECT_EQ("Common Name", common_name);
  7279. X509_free(peer_cert);
  7280. });
  7281. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7282. auto se = detail::scope_exit([&] {
  7283. svr.stop();
  7284. t.join();
  7285. ASSERT_FALSE(svr.is_running());
  7286. });
  7287. svr.wait_until_ready();
  7288. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7289. client_encrypted_private_key_pass);
  7290. cli.enable_server_certificate_verification(false);
  7291. cli.set_connection_timeout(30);
  7292. auto res = cli.Get("/test");
  7293. ASSERT_TRUE(res);
  7294. ASSERT_EQ(StatusCode::OK_200, res->status);
  7295. }
  7296. TEST(SSLClientServerTest, ClientCertPresent) {
  7297. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7298. }
  7299. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7300. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7301. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7302. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7303. }
  7304. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7305. void MemoryClientCertPresent(
  7306. const std::string &client_cert_file,
  7307. const std::string &client_private_key_file,
  7308. const std::string &client_encrypted_private_key_pass = std::string()) {
  7309. auto f = fopen(SERVER_CERT_FILE, "r+");
  7310. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7311. fclose(f);
  7312. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7313. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7314. fclose(f);
  7315. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7316. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7317. auto client_ca_cert_store = X509_STORE_new();
  7318. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7319. X509_free(client_cert);
  7320. fclose(f);
  7321. f = fopen(client_cert_file.c_str(), "r+");
  7322. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7323. fclose(f);
  7324. f = fopen(client_private_key_file.c_str(), "r+");
  7325. auto client_private_key = PEM_read_PrivateKey(
  7326. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7327. fclose(f);
  7328. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7329. ASSERT_TRUE(svr.is_valid());
  7330. svr.Get("/test", [&](const Request &req, Response &res) {
  7331. res.set_content("test", "text/plain");
  7332. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7333. ASSERT_TRUE(peer_cert != nullptr);
  7334. auto subject_name = X509_get_subject_name(peer_cert);
  7335. ASSERT_TRUE(subject_name != nullptr);
  7336. std::string common_name;
  7337. {
  7338. char name[BUFSIZ];
  7339. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7340. name, sizeof(name));
  7341. common_name.assign(name, static_cast<size_t>(name_len));
  7342. }
  7343. EXPECT_EQ("Common Name", common_name);
  7344. X509_free(peer_cert);
  7345. });
  7346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7347. auto se = detail::scope_exit([&] {
  7348. svr.stop();
  7349. t.join();
  7350. ASSERT_FALSE(svr.is_running());
  7351. });
  7352. svr.wait_until_ready();
  7353. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7354. client_encrypted_private_key_pass);
  7355. cli.enable_server_certificate_verification(false);
  7356. cli.set_connection_timeout(30);
  7357. auto res = cli.Get("/test");
  7358. ASSERT_TRUE(res);
  7359. ASSERT_EQ(StatusCode::OK_200, res->status);
  7360. X509_free(server_cert);
  7361. EVP_PKEY_free(server_private_key);
  7362. X509_free(client_cert);
  7363. EVP_PKEY_free(client_private_key);
  7364. }
  7365. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7366. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7367. }
  7368. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7369. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7370. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7371. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7372. }
  7373. #endif
  7374. TEST(SSLClientServerTest, ClientCertMissing) {
  7375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7376. CLIENT_CA_CERT_DIR);
  7377. ASSERT_TRUE(svr.is_valid());
  7378. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7379. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7380. auto se = detail::scope_exit([&] {
  7381. svr.stop();
  7382. t.join();
  7383. ASSERT_FALSE(svr.is_running());
  7384. });
  7385. svr.wait_until_ready();
  7386. SSLClient cli(HOST, PORT);
  7387. cli.set_connection_timeout(30);
  7388. auto res = cli.Get("/test");
  7389. ASSERT_TRUE(!res);
  7390. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7391. // For SSL server verification errors, ssl_error should be 0, only
  7392. // ssl_openssl_error should be set
  7393. EXPECT_EQ(0, res.ssl_error());
  7394. // Verify OpenSSL error is captured for SSLServerVerification
  7395. // Note: This test may have different error codes depending on the exact
  7396. // verification failure
  7397. EXPECT_NE(0UL, res.ssl_openssl_error());
  7398. }
  7399. TEST(SSLClientServerTest, TrustDirOptional) {
  7400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7401. ASSERT_TRUE(svr.is_valid());
  7402. svr.Get("/test", [&](const Request &, Response &res) {
  7403. res.set_content("test", "text/plain");
  7404. });
  7405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7406. auto se = detail::scope_exit([&] {
  7407. svr.stop();
  7408. t.join();
  7409. ASSERT_FALSE(svr.is_running());
  7410. });
  7411. svr.wait_until_ready();
  7412. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7413. cli.enable_server_certificate_verification(false);
  7414. cli.set_connection_timeout(30);
  7415. auto res = cli.Get("/test");
  7416. ASSERT_TRUE(res);
  7417. ASSERT_EQ(StatusCode::OK_200, res->status);
  7418. }
  7419. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7420. class NoListenSSLServer : public SSLServer {
  7421. public:
  7422. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7423. const char *client_ca_cert_file_path,
  7424. const char *client_ca_cert_dir_path = nullptr)
  7425. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7426. client_ca_cert_dir_path),
  7427. stop_(false) {}
  7428. std::atomic_bool stop_;
  7429. private:
  7430. bool process_and_close_socket(socket_t /*sock*/) override {
  7431. // Don't create SSL context
  7432. while (!stop_.load()) {
  7433. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7434. }
  7435. return true;
  7436. }
  7437. };
  7438. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7439. CLIENT_CA_CERT_FILE);
  7440. ASSERT_TRUE(svr.is_valid());
  7441. svr.Get("/test", [&](const Request &, Response &res) {
  7442. res.set_content("test", "text/plain");
  7443. });
  7444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7445. auto se = detail::scope_exit([&] {
  7446. svr.stop_ = true;
  7447. svr.stop();
  7448. t.join();
  7449. ASSERT_FALSE(svr.is_running());
  7450. });
  7451. svr.wait_until_ready();
  7452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7453. cli.enable_server_certificate_verification(false);
  7454. cli.set_connection_timeout(1);
  7455. auto res = cli.Get("/test");
  7456. ASSERT_TRUE(!res);
  7457. EXPECT_EQ(Error::SSLConnection, res.error());
  7458. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7459. }
  7460. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7461. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7462. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7463. SSL_CTX_set_options(&ssl_ctx,
  7464. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7465. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7466. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7467. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7468. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7469. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7470. "ECDHE-DSS-AES128-SHA256:"
  7471. "ECDHE-RSA-AES256-SHA256:"
  7472. "ECDHE-DSS-AES256-SHA256:";
  7473. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7474. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7475. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7476. SSL_FILETYPE_PEM) != 1) {
  7477. return false;
  7478. }
  7479. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7480. CLIENT_CA_CERT_DIR);
  7481. SSL_CTX_set_verify(
  7482. &ssl_ctx,
  7483. SSL_VERIFY_PEER |
  7484. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7485. nullptr);
  7486. return true;
  7487. };
  7488. SSLServer svr(setup_ssl_ctx_callback);
  7489. ASSERT_TRUE(svr.is_valid());
  7490. svr.Get("/test", [&](const Request &req, Response &res) {
  7491. res.set_content("test", "text/plain");
  7492. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7493. ASSERT_TRUE(peer_cert != nullptr);
  7494. auto subject_name = X509_get_subject_name(peer_cert);
  7495. ASSERT_TRUE(subject_name != nullptr);
  7496. std::string common_name;
  7497. {
  7498. char name[BUFSIZ];
  7499. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7500. name, sizeof(name));
  7501. common_name.assign(name, static_cast<size_t>(name_len));
  7502. }
  7503. EXPECT_EQ("Common Name", common_name);
  7504. X509_free(peer_cert);
  7505. });
  7506. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7507. auto se = detail::scope_exit([&] {
  7508. svr.stop();
  7509. t.join();
  7510. ASSERT_FALSE(svr.is_running());
  7511. });
  7512. svr.wait_until_ready();
  7513. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7514. cli.enable_server_certificate_verification(false);
  7515. cli.set_connection_timeout(30);
  7516. auto res = cli.Get("/test");
  7517. ASSERT_TRUE(res);
  7518. ASSERT_EQ(StatusCode::OK_200, res->status);
  7519. }
  7520. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7522. ASSERT_TRUE(svr.is_valid());
  7523. // Set up a handler to verify client certificate is present
  7524. bool client_cert_verified = false;
  7525. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7526. // Verify that client certificate was provided
  7527. client_cert_verified = true;
  7528. res.set_content("success", "text/plain");
  7529. });
  7530. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7531. auto se = detail::scope_exit([&] {
  7532. svr.stop();
  7533. t.join();
  7534. ASSERT_FALSE(svr.is_running());
  7535. });
  7536. svr.wait_until_ready();
  7537. // Client with certificate
  7538. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7539. cli.enable_server_certificate_verification(false);
  7540. cli.set_connection_timeout(30);
  7541. auto res = cli.Get("/test");
  7542. ASSERT_TRUE(res);
  7543. ASSERT_EQ(StatusCode::OK_200, res->status);
  7544. ASSERT_TRUE(client_cert_verified);
  7545. EXPECT_EQ("success", res->body);
  7546. }
  7547. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7548. // Test that when client CA cert file is provided,
  7549. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7550. // Create a server with client authentication
  7551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7552. ASSERT_TRUE(svr.is_valid());
  7553. // We can't directly access the SSL_CTX from SSLServer to verify,
  7554. // but we can test that the server properly requests client certificates
  7555. // and accepts valid ones from the specified CA
  7556. bool handler_called = false;
  7557. svr.Get("/test", [&](const Request &req, Response &res) {
  7558. handler_called = true;
  7559. // Verify that a client certificate was provided
  7560. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7561. ASSERT_TRUE(peer_cert != nullptr);
  7562. // Get the issuer name
  7563. auto issuer_name = X509_get_issuer_name(peer_cert);
  7564. ASSERT_TRUE(issuer_name != nullptr);
  7565. char issuer_buf[256];
  7566. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7567. // The client certificate should be issued by our test CA
  7568. std::string issuer_str(issuer_buf);
  7569. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7570. X509_free(peer_cert);
  7571. res.set_content("authenticated", "text/plain");
  7572. });
  7573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7574. auto se = detail::scope_exit([&] {
  7575. svr.stop();
  7576. t.join();
  7577. ASSERT_FALSE(svr.is_running());
  7578. });
  7579. svr.wait_until_ready();
  7580. // Connect with a client certificate issued by the CA
  7581. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7582. cli.enable_server_certificate_verification(false);
  7583. cli.set_connection_timeout(30);
  7584. auto res = cli.Get("/test");
  7585. ASSERT_TRUE(res);
  7586. ASSERT_EQ(StatusCode::OK_200, res->status);
  7587. ASSERT_TRUE(handler_called);
  7588. EXPECT_EQ("authenticated", res->body);
  7589. }
  7590. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7591. // Test 1: Valid CA file - no error should be recorded
  7592. {
  7593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7594. CLIENT_CA_CERT_FILE);
  7595. ASSERT_TRUE(svr.is_valid());
  7596. // With valid setup, last_ssl_error should be 0
  7597. EXPECT_EQ(0, svr.ssl_last_error());
  7598. }
  7599. // Test 2: Invalid CA file content
  7600. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7601. {
  7602. // Create a temporary file with completely invalid content
  7603. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7604. {
  7605. std::ofstream ofs(temp_invalid_ca);
  7606. ofs << "This is not a certificate file at all\n";
  7607. ofs << "Just plain text content\n";
  7608. }
  7609. // Create server with invalid CA file
  7610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7611. // Clean up temporary file
  7612. std::remove(temp_invalid_ca);
  7613. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7614. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7615. // Note: SSL_CTX_load_verify_locations typically fails first,
  7616. // but our error handling code path is still exercised
  7617. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7618. }
  7619. }
  7620. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7621. // Test SSL server using X509_STORE constructor with client CA certificates
  7622. // This test verifies that Phase 2 implementation correctly extracts CA names
  7623. // from an X509_STORE and sets them in the SSL context
  7624. // Load the CA certificate into memory
  7625. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7626. ASSERT_NE(nullptr, bio);
  7627. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7628. BIO_free(bio);
  7629. ASSERT_NE(nullptr, ca_cert);
  7630. // Create an X509_STORE and add the CA certificate
  7631. auto store = X509_STORE_new();
  7632. ASSERT_NE(nullptr, store);
  7633. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7634. // Load server certificate and private key
  7635. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7636. ASSERT_NE(nullptr, cert_bio);
  7637. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7638. BIO_free(cert_bio);
  7639. ASSERT_NE(nullptr, server_cert);
  7640. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7641. ASSERT_NE(nullptr, key_bio);
  7642. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7643. BIO_free(key_bio);
  7644. ASSERT_NE(nullptr, server_key);
  7645. // Create SSLServer with X509_STORE constructor
  7646. // Note: X509_STORE ownership is transferred to SSL_CTX
  7647. SSLServer svr(server_cert, server_key, store);
  7648. ASSERT_TRUE(svr.is_valid());
  7649. // No SSL error should be recorded for valid setup
  7650. EXPECT_EQ(0, svr.ssl_last_error());
  7651. // Set up server endpoints
  7652. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7653. res.set_content("ok", "text/plain");
  7654. });
  7655. // Start server in a thread
  7656. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7657. svr.wait_until_ready();
  7658. // Connect with client certificate (using constructor with paths)
  7659. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7660. cli.enable_server_certificate_verification(false);
  7661. auto res = cli.Get("/test-x509store");
  7662. ASSERT_TRUE(res);
  7663. EXPECT_EQ(200, res->status);
  7664. EXPECT_EQ("ok", res->body);
  7665. // Clean up
  7666. X509_free(server_cert);
  7667. EVP_PKEY_free(server_key);
  7668. X509_free(ca_cert);
  7669. svr.stop();
  7670. server_thread.join();
  7671. }
  7672. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7673. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7674. // prepare large data
  7675. std::random_device seed_gen;
  7676. std::mt19937 random(seed_gen());
  7677. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7678. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7679. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7680. // server
  7681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7682. ASSERT_TRUE(svr.is_valid());
  7683. svr.Post("/binary", [&](const Request &req, Response &res) {
  7684. EXPECT_EQ(large_size_byte, req.body.size());
  7685. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7686. res.set_content(req.body, "application/octet-stream");
  7687. });
  7688. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7689. auto se = detail::scope_exit([&] {
  7690. svr.stop();
  7691. listen_thread.join();
  7692. ASSERT_FALSE(svr.is_running());
  7693. });
  7694. svr.wait_until_ready();
  7695. // client POST
  7696. SSLClient cli("localhost", PORT);
  7697. cli.enable_server_certificate_verification(false);
  7698. cli.set_read_timeout(std::chrono::seconds(100));
  7699. cli.set_write_timeout(std::chrono::seconds(100));
  7700. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7701. large_size_byte, "application/octet-stream");
  7702. // compare
  7703. EXPECT_EQ(StatusCode::OK_200, res->status);
  7704. EXPECT_EQ(large_size_byte, res->body.size());
  7705. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7706. }
  7707. #endif
  7708. #ifdef _WIN32
  7709. TEST(CleanupTest, WSACleanup) {
  7710. int ret = WSACleanup();
  7711. ASSERT_EQ(0, ret);
  7712. }
  7713. #endif
  7714. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7715. TEST(NoSSLSupport, SimpleInterface) {
  7716. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7717. }
  7718. #endif
  7719. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7720. TEST(InvalidScheme, SimpleInterface) {
  7721. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7722. }
  7723. #endif
  7724. TEST(NoScheme, SimpleInterface) {
  7725. Client cli("yahoo.com:80");
  7726. ASSERT_TRUE(cli.is_valid());
  7727. }
  7728. TEST(SendAPI, SimpleInterface_Online) {
  7729. Client cli("http://yahoo.com");
  7730. Request req;
  7731. req.method = "GET";
  7732. req.path = "/";
  7733. auto res = cli.send(req);
  7734. ASSERT_TRUE(res);
  7735. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7736. }
  7737. TEST(SendAPI, WithParamsInRequest) {
  7738. Server svr;
  7739. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7740. EXPECT_TRUE(req.has_param("test"));
  7741. EXPECT_EQ("test_value", req.get_param_value("test"));
  7742. });
  7743. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7744. auto se = detail::scope_exit([&] {
  7745. svr.stop();
  7746. t.join();
  7747. ASSERT_FALSE(svr.is_running());
  7748. });
  7749. svr.wait_until_ready();
  7750. Client cli(HOST, PORT);
  7751. {
  7752. Request req;
  7753. req.method = "GET";
  7754. req.path = "/";
  7755. req.params.emplace("test", "test_value");
  7756. auto res = cli.send(req);
  7757. ASSERT_TRUE(res);
  7758. }
  7759. {
  7760. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7761. ASSERT_TRUE(res);
  7762. }
  7763. }
  7764. TEST(ClientImplMethods, GetSocketTest) {
  7765. httplib::Server svr;
  7766. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7767. res.status = StatusCode::OK_200;
  7768. });
  7769. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7770. auto se = detail::scope_exit([&] {
  7771. svr.stop();
  7772. thread.join();
  7773. ASSERT_FALSE(svr.is_running());
  7774. });
  7775. svr.wait_until_ready();
  7776. {
  7777. httplib::Client cli("http://127.0.0.1:3333");
  7778. cli.set_keep_alive(true);
  7779. // Use the behavior of cpp-httplib of opening the connection
  7780. // only when the first request happens. If that changes,
  7781. // this test would be obsolete.
  7782. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7783. // This also implicitly tests the server. But other tests would fail much
  7784. // earlier than this one to be considered.
  7785. auto res = cli.Get("/");
  7786. ASSERT_TRUE(res);
  7787. EXPECT_EQ(StatusCode::OK_200, res->status);
  7788. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7789. }
  7790. }
  7791. // Disabled due to out-of-memory problem on GitHub Actions
  7792. #ifdef _WIN64
  7793. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7794. // allocate content size larger than 2GB in memory
  7795. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7796. char *content = (char *)malloc(content_size);
  7797. ASSERT_TRUE(content);
  7798. Server svr;
  7799. svr.Get("/foo",
  7800. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7801. res.set_content(content, content_size, "application/octet-stream");
  7802. });
  7803. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7804. auto se = detail::scope_exit([&] {
  7805. svr.stop();
  7806. listen_thread.join();
  7807. if (content) free(content);
  7808. ASSERT_FALSE(svr.is_running());
  7809. });
  7810. svr.wait_until_ready();
  7811. Client cli(HOST, PORT);
  7812. auto res = cli.Get("/foo");
  7813. ASSERT_TRUE(res);
  7814. EXPECT_EQ(StatusCode::OK_200, res->status);
  7815. EXPECT_EQ(content_size, res->body.length());
  7816. }
  7817. #endif
  7818. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7819. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7820. Client cli("http://yahoo.com");
  7821. auto res = cli.Get("/");
  7822. ASSERT_TRUE(res);
  7823. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7824. cli.set_follow_location(true);
  7825. res = cli.Get("/");
  7826. ASSERT_TRUE(res);
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7829. }
  7830. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7831. Client cli("https://yahoo.com");
  7832. auto res = cli.Get("/");
  7833. ASSERT_TRUE(res);
  7834. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7835. cli.set_follow_location(true);
  7836. res = cli.Get("/");
  7837. ASSERT_TRUE(res);
  7838. EXPECT_EQ(StatusCode::OK_200, res->status);
  7839. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7840. }
  7841. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7842. Client cli("https://yahoo.com");
  7843. auto res = cli.Get("/");
  7844. ASSERT_TRUE(res);
  7845. ASSERT_FALSE(!res);
  7846. ASSERT_TRUE(res);
  7847. ASSERT_FALSE(res == nullptr);
  7848. ASSERT_TRUE(res != nullptr);
  7849. EXPECT_EQ(Error::Success, res.error());
  7850. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7851. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7852. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7853. cli.set_follow_location(true);
  7854. res = cli.Get("/");
  7855. ASSERT_TRUE(res);
  7856. EXPECT_EQ(Error::Success, res.error());
  7857. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7858. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7861. }
  7862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7863. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7864. Client cli("https://cdnjs.cloudflare.com");
  7865. auto res =
  7866. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7867. ASSERT_TRUE(res);
  7868. EXPECT_EQ(StatusCode::OK_200, res->status);
  7869. EXPECT_EQ(287630U, res->body.size());
  7870. EXPECT_EQ("application/javascript; charset=utf-8",
  7871. res->get_header_value("Content-Type"));
  7872. }
  7873. #endif
  7874. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7875. #undef REDIR_HOST // Silence compiler warning
  7876. #define REDIR_HOST "https://httpbingo.org"
  7877. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7878. Client cli(REDIR_HOST);
  7879. cli.set_follow_location(true);
  7880. auto res =
  7881. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7882. ASSERT_TRUE(res);
  7883. EXPECT_EQ(StatusCode::OK_200, res->status);
  7884. }
  7885. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7886. Client cli(REDIR_HOST);
  7887. cli.set_follow_location(true);
  7888. Params params;
  7889. params.emplace("url", "http://example.com");
  7890. params.emplace("status_code", "302");
  7891. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7892. ASSERT_TRUE(res);
  7893. EXPECT_EQ(StatusCode::OK_200, res->status);
  7894. }
  7895. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7896. Client cli(REDIR_HOST);
  7897. cli.set_follow_location(true);
  7898. Params params;
  7899. params.emplace("url", "http://example.com");
  7900. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7901. ASSERT_TRUE(res);
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. }
  7904. TEST(HttpToHttpsRedirectTest, CertFile) {
  7905. Server svr;
  7906. ASSERT_TRUE(svr.is_valid());
  7907. svr.Get("/index", [&](const Request &, Response &res) {
  7908. res.set_redirect("https://127.0.0.1:1235/index");
  7909. svr.stop();
  7910. });
  7911. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7912. ASSERT_TRUE(ssl_svr.is_valid());
  7913. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7914. res.set_content("test", "text/plain");
  7915. ssl_svr.stop();
  7916. });
  7917. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7918. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7919. auto se = detail::scope_exit([&] {
  7920. t2.join();
  7921. t.join();
  7922. ASSERT_FALSE(svr.is_running());
  7923. });
  7924. svr.wait_until_ready();
  7925. ssl_svr.wait_until_ready();
  7926. Client cli("127.0.0.1", PORT);
  7927. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7928. cli.enable_server_certificate_verification(true);
  7929. cli.set_follow_location(true);
  7930. cli.set_connection_timeout(30);
  7931. auto res = cli.Get("/index");
  7932. ASSERT_TRUE(res);
  7933. ASSERT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST(SSLClientRedirectTest, CertFile) {
  7936. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7937. ASSERT_TRUE(ssl_svr1.is_valid());
  7938. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7939. res.set_redirect("https://127.0.0.1:1235/index");
  7940. ssl_svr1.stop();
  7941. });
  7942. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7943. ASSERT_TRUE(ssl_svr2.is_valid());
  7944. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  7945. res.set_content("test", "text/plain");
  7946. ssl_svr2.stop();
  7947. });
  7948. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  7949. thread t2 =
  7950. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  7951. auto se = detail::scope_exit([&] {
  7952. t2.join();
  7953. t.join();
  7954. ASSERT_FALSE(ssl_svr1.is_running());
  7955. });
  7956. ssl_svr1.wait_until_ready();
  7957. ssl_svr2.wait_until_ready();
  7958. SSLClient cli("127.0.0.1", PORT);
  7959. std::string cert;
  7960. read_file(SERVER_CERT2_FILE, cert);
  7961. cli.load_ca_cert_store(cert.c_str(), cert.size());
  7962. cli.enable_server_certificate_verification(true);
  7963. cli.set_follow_location(true);
  7964. cli.set_connection_timeout(30);
  7965. auto res = cli.Get("/index");
  7966. ASSERT_TRUE(res);
  7967. ASSERT_EQ(StatusCode::OK_200, res->status);
  7968. }
  7969. TEST(MultipartFormDataTest, LargeData) {
  7970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7971. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7972. const ContentReader &content_reader) {
  7973. if (req.is_multipart_form_data()) {
  7974. std::vector<FormData> items;
  7975. content_reader(
  7976. [&](const FormData &file) {
  7977. items.push_back(file);
  7978. return true;
  7979. },
  7980. [&](const char *data, size_t data_length) {
  7981. items.back().content.append(data, data_length);
  7982. return true;
  7983. });
  7984. EXPECT_TRUE(std::string(items[0].name) == "document");
  7985. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  7986. EXPECT_TRUE(items[0].filename == "2MB_data");
  7987. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  7988. EXPECT_TRUE(items[1].name == "hello");
  7989. EXPECT_TRUE(items[1].content == "world");
  7990. EXPECT_TRUE(items[1].filename == "");
  7991. EXPECT_TRUE(items[1].content_type == "");
  7992. } else {
  7993. std::string body;
  7994. content_reader([&](const char *data, size_t data_length) {
  7995. body.append(data, data_length);
  7996. return true;
  7997. });
  7998. }
  7999. });
  8000. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8001. auto se = detail::scope_exit([&] {
  8002. svr.stop();
  8003. t.join();
  8004. ASSERT_FALSE(svr.is_running());
  8005. });
  8006. svr.wait_until_ready();
  8007. {
  8008. std::string data(1024 * 1024 * 2, '.');
  8009. std::stringstream buffer;
  8010. buffer << data;
  8011. Client cli("https://localhost:8080");
  8012. cli.enable_server_certificate_verification(false);
  8013. UploadFormDataItems items{
  8014. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8015. {"hello", "world", "", ""},
  8016. };
  8017. auto res = cli.Post("/post", items);
  8018. ASSERT_TRUE(res);
  8019. ASSERT_EQ(StatusCode::OK_200, res->status);
  8020. }
  8021. }
  8022. TEST(MultipartFormDataTest, DataProviderItems) {
  8023. std::random_device seed_gen;
  8024. std::mt19937 random(seed_gen());
  8025. std::string rand1;
  8026. rand1.resize(1000);
  8027. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8028. std::string rand2;
  8029. rand2.resize(3000);
  8030. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8031. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8032. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8033. const ContentReader &content_reader) {
  8034. ASSERT_FALSE(req.is_multipart_form_data());
  8035. std::string body;
  8036. content_reader([&](const char *data, size_t data_length) {
  8037. body.append(data, data_length);
  8038. return true;
  8039. });
  8040. EXPECT_EQ(body, "");
  8041. });
  8042. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8043. const ContentReader &content_reader) {
  8044. ASSERT_TRUE(req.is_multipart_form_data());
  8045. std::vector<FormData> items;
  8046. content_reader(
  8047. [&](const FormData &file) {
  8048. items.push_back(file);
  8049. return true;
  8050. },
  8051. [&](const char *data, size_t data_length) {
  8052. items.back().content.append(data, data_length);
  8053. return true;
  8054. });
  8055. ASSERT_TRUE(items.size() == 2);
  8056. EXPECT_EQ(std::string(items[0].name), "name1");
  8057. EXPECT_EQ(items[0].content, "Testing123");
  8058. EXPECT_EQ(items[0].filename, "filename1");
  8059. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8060. EXPECT_EQ(items[1].name, "name2");
  8061. EXPECT_EQ(items[1].content, "Testing456");
  8062. EXPECT_EQ(items[1].filename, "");
  8063. EXPECT_EQ(items[1].content_type, "");
  8064. });
  8065. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8066. const ContentReader &content_reader) {
  8067. ASSERT_TRUE(req.is_multipart_form_data());
  8068. std::vector<FormData> items;
  8069. content_reader(
  8070. [&](const FormData &file) {
  8071. items.push_back(file);
  8072. return true;
  8073. },
  8074. [&](const char *data, size_t data_length) {
  8075. items.back().content.append(data, data_length);
  8076. return true;
  8077. });
  8078. ASSERT_TRUE(items.size() == 2);
  8079. EXPECT_EQ(items[0].name, "name3");
  8080. EXPECT_EQ(items[0].content, rand1);
  8081. EXPECT_EQ(items[0].filename, "filename3");
  8082. EXPECT_EQ(items[0].content_type, "");
  8083. EXPECT_EQ(items[1].name, "name4");
  8084. EXPECT_EQ(items[1].content, rand2);
  8085. EXPECT_EQ(items[1].filename, "filename4");
  8086. EXPECT_EQ(items[1].content_type, "");
  8087. });
  8088. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8089. const ContentReader &content_reader) {
  8090. ASSERT_TRUE(req.is_multipart_form_data());
  8091. std::vector<FormData> items;
  8092. content_reader(
  8093. [&](const FormData &file) {
  8094. items.push_back(file);
  8095. return true;
  8096. },
  8097. [&](const char *data, size_t data_length) {
  8098. items.back().content.append(data, data_length);
  8099. return true;
  8100. });
  8101. ASSERT_TRUE(items.size() == 4);
  8102. EXPECT_EQ(std::string(items[0].name), "name1");
  8103. EXPECT_EQ(items[0].content, "Testing123");
  8104. EXPECT_EQ(items[0].filename, "filename1");
  8105. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8106. EXPECT_EQ(items[1].name, "name2");
  8107. EXPECT_EQ(items[1].content, "Testing456");
  8108. EXPECT_EQ(items[1].filename, "");
  8109. EXPECT_EQ(items[1].content_type, "");
  8110. EXPECT_EQ(items[2].name, "name3");
  8111. EXPECT_EQ(items[2].content, rand1);
  8112. EXPECT_EQ(items[2].filename, "filename3");
  8113. EXPECT_EQ(items[2].content_type, "");
  8114. EXPECT_EQ(items[3].name, "name4");
  8115. EXPECT_EQ(items[3].content, rand2);
  8116. EXPECT_EQ(items[3].filename, "filename4");
  8117. EXPECT_EQ(items[3].content_type, "");
  8118. });
  8119. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8120. auto se = detail::scope_exit([&] {
  8121. svr.stop();
  8122. t.join();
  8123. ASSERT_FALSE(svr.is_running());
  8124. });
  8125. svr.wait_until_ready();
  8126. {
  8127. Client cli("https://localhost:8080");
  8128. cli.enable_server_certificate_verification(false);
  8129. UploadFormDataItems items{
  8130. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8131. {"name2", "Testing456", "", ""}, // not a file
  8132. };
  8133. {
  8134. auto res = cli.Post("/post-none", {}, {}, {});
  8135. ASSERT_TRUE(res);
  8136. ASSERT_EQ(StatusCode::OK_200, res->status);
  8137. }
  8138. FormDataProviderItems providers;
  8139. {
  8140. auto res =
  8141. cli.Post("/post-items", {}, items, providers); // empty providers
  8142. ASSERT_TRUE(res);
  8143. ASSERT_EQ(StatusCode::OK_200, res->status);
  8144. }
  8145. providers.push_back({"name3",
  8146. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8147. // test the offset is given correctly at each step
  8148. if (!offset)
  8149. sink.os.write(rand1.data(), 30);
  8150. else if (offset == 30)
  8151. sink.os.write(rand1.data() + 30, 300);
  8152. else if (offset == 330)
  8153. sink.os.write(rand1.data() + 330, 670);
  8154. else if (offset == rand1.size())
  8155. sink.done();
  8156. return true;
  8157. },
  8158. "filename3",
  8159. {}});
  8160. providers.push_back({"name4",
  8161. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8162. // test the offset is given correctly at each step
  8163. if (!offset)
  8164. sink.os.write(rand2.data(), 2000);
  8165. else if (offset == 2000)
  8166. sink.os.write(rand2.data() + 2000, 1);
  8167. else if (offset == 2001)
  8168. sink.os.write(rand2.data() + 2001, 999);
  8169. else if (offset == rand2.size())
  8170. sink.done();
  8171. return true;
  8172. },
  8173. "filename4",
  8174. {}});
  8175. {
  8176. auto res = cli.Post("/post-providers", {}, {}, providers);
  8177. ASSERT_TRUE(res);
  8178. ASSERT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. {
  8181. auto res = cli.Post("/post-both", {}, items, providers);
  8182. ASSERT_TRUE(res);
  8183. ASSERT_EQ(StatusCode::OK_200, res->status);
  8184. }
  8185. }
  8186. }
  8187. TEST(MultipartFormDataTest, BadHeader) {
  8188. Server svr;
  8189. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8190. res.set_content("ok", "text/plain");
  8191. });
  8192. thread t = thread([&] { svr.listen(HOST, PORT); });
  8193. auto se = detail::scope_exit([&] {
  8194. svr.stop();
  8195. t.join();
  8196. ASSERT_FALSE(svr.is_running());
  8197. });
  8198. svr.wait_until_ready();
  8199. const std::string body =
  8200. "This is the preamble. It is to be ignored, though it\r\n"
  8201. "is a handy place for composition agents to include an\r\n"
  8202. "explanatory note to non-MIME conformant readers.\r\n"
  8203. "\r\n"
  8204. "\r\n"
  8205. "--simple boundary\r\n"
  8206. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8207. ": BAD...\r\n"
  8208. "\r\n"
  8209. "value1\r\n"
  8210. "--simple boundary\r\n"
  8211. "Content-Disposition: form-data; name=\"field2\"; "
  8212. "filename=\"example.txt\"\r\n"
  8213. "\r\n"
  8214. "value2\r\n"
  8215. "--simple boundary--\r\n"
  8216. "This is the epilogue. It is also to be ignored.\r\n";
  8217. std::string content_type =
  8218. R"(multipart/form-data; boundary="simple boundary")";
  8219. Client cli(HOST, PORT);
  8220. auto res = cli.Post("/post", body, content_type.c_str());
  8221. ASSERT_TRUE(res);
  8222. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8223. }
  8224. TEST(MultipartFormDataTest, WithPreamble) {
  8225. Server svr;
  8226. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8227. res.set_content("ok", "text/plain");
  8228. });
  8229. thread t = thread([&] { svr.listen(HOST, PORT); });
  8230. auto se = detail::scope_exit([&] {
  8231. svr.stop();
  8232. t.join();
  8233. ASSERT_FALSE(svr.is_running());
  8234. });
  8235. svr.wait_until_ready();
  8236. const std::string body =
  8237. "This is the preamble. It is to be ignored, though it\r\n"
  8238. "is a handy place for composition agents to include an\r\n"
  8239. "explanatory note to non-MIME conformant readers.\r\n"
  8240. "\r\n"
  8241. "\r\n"
  8242. "--simple boundary\r\n"
  8243. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8244. "\r\n"
  8245. "value1\r\n"
  8246. "--simple boundary\r\n"
  8247. "Content-Disposition: form-data; name=\"field2\"; "
  8248. "filename=\"example.txt\"\r\n"
  8249. "\r\n"
  8250. "value2\r\n"
  8251. "--simple boundary--\r\n"
  8252. "This is the epilogue. It is also to be ignored.\r\n";
  8253. std::string content_type =
  8254. R"(multipart/form-data; boundary="simple boundary")";
  8255. Client cli(HOST, PORT);
  8256. auto res = cli.Post("/post", body, content_type.c_str());
  8257. ASSERT_TRUE(res);
  8258. EXPECT_EQ(StatusCode::OK_200, res->status);
  8259. }
  8260. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8262. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8263. const ContentReader &content_reader) {
  8264. if (req.is_multipart_form_data()) {
  8265. std::vector<FormData> items;
  8266. content_reader(
  8267. [&](const FormData &file) {
  8268. items.push_back(file);
  8269. return true;
  8270. },
  8271. [&](const char *data, size_t data_length) {
  8272. items.back().content.append(data, data_length);
  8273. return true;
  8274. });
  8275. EXPECT_TRUE(std::string(items[0].name) == "document");
  8276. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8277. EXPECT_TRUE(items[0].filename == "2MB_data");
  8278. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8279. EXPECT_TRUE(items[1].name == "hello");
  8280. EXPECT_TRUE(items[1].content == "world");
  8281. EXPECT_TRUE(items[1].filename == "");
  8282. EXPECT_TRUE(items[1].content_type == "");
  8283. } else {
  8284. std::string body;
  8285. content_reader([&](const char *data, size_t data_length) {
  8286. body.append(data, data_length);
  8287. return true;
  8288. });
  8289. }
  8290. });
  8291. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8292. auto se = detail::scope_exit([&] {
  8293. svr.stop();
  8294. t.join();
  8295. ASSERT_FALSE(svr.is_running());
  8296. });
  8297. svr.wait_until_ready();
  8298. {
  8299. std::string data(1024 * 1024 * 2, '.');
  8300. std::stringstream buffer;
  8301. buffer << data;
  8302. Client cli("https://localhost:8080");
  8303. cli.enable_server_certificate_verification(false);
  8304. UploadFormDataItems items{
  8305. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8306. {"hello", "world", "", ""},
  8307. };
  8308. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8309. ASSERT_TRUE(res);
  8310. ASSERT_EQ(StatusCode::OK_200, res->status);
  8311. }
  8312. }
  8313. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8314. std::string data(1024 * 1024 * 2, '&');
  8315. std::stringstream buffer;
  8316. buffer << data;
  8317. Client cli("https://localhost:8080");
  8318. UploadFormDataItems items{
  8319. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8320. {"hello", "world", "", ""},
  8321. };
  8322. for (const char &c : " \t\r\n") {
  8323. auto res =
  8324. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8325. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8326. ASSERT_FALSE(res);
  8327. }
  8328. }
  8329. TEST(MultipartFormDataTest, PutFormData) {
  8330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8331. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8332. const ContentReader &content_reader) {
  8333. if (req.is_multipart_form_data()) {
  8334. std::vector<FormData> items;
  8335. content_reader(
  8336. [&](const FormData &file) {
  8337. items.push_back(file);
  8338. return true;
  8339. },
  8340. [&](const char *data, size_t data_length) {
  8341. items.back().content.append(data, data_length);
  8342. return true;
  8343. });
  8344. EXPECT_TRUE(std::string(items[0].name) == "document");
  8345. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8346. EXPECT_TRUE(items[0].filename == "2MB_data");
  8347. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8348. EXPECT_TRUE(items[1].name == "hello");
  8349. EXPECT_TRUE(items[1].content == "world");
  8350. EXPECT_TRUE(items[1].filename == "");
  8351. EXPECT_TRUE(items[1].content_type == "");
  8352. } else {
  8353. std::string body;
  8354. content_reader([&](const char *data, size_t data_length) {
  8355. body.append(data, data_length);
  8356. return true;
  8357. });
  8358. }
  8359. });
  8360. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8361. auto se = detail::scope_exit([&] {
  8362. svr.stop();
  8363. t.join();
  8364. ASSERT_FALSE(svr.is_running());
  8365. });
  8366. svr.wait_until_ready();
  8367. {
  8368. std::string data(1024 * 1024 * 2, '&');
  8369. std::stringstream buffer;
  8370. buffer << data;
  8371. Client cli("https://localhost:8080");
  8372. cli.enable_server_certificate_verification(false);
  8373. UploadFormDataItems items{
  8374. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8375. {"hello", "world", "", ""},
  8376. };
  8377. auto res = cli.Put("/put", items);
  8378. ASSERT_TRUE(res);
  8379. ASSERT_EQ(StatusCode::OK_200, res->status);
  8380. }
  8381. }
  8382. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8384. svr.Put("/put_customboundary",
  8385. [&](const Request &req, const Response & /*res*/,
  8386. const ContentReader &content_reader) {
  8387. if (req.is_multipart_form_data()) {
  8388. std::vector<FormData> items;
  8389. content_reader(
  8390. [&](const FormData &file) {
  8391. items.push_back(file);
  8392. return true;
  8393. },
  8394. [&](const char *data, size_t data_length) {
  8395. items.back().content.append(data, data_length);
  8396. return true;
  8397. });
  8398. EXPECT_TRUE(std::string(items[0].name) == "document");
  8399. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8400. EXPECT_TRUE(items[0].filename == "2MB_data");
  8401. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8402. EXPECT_TRUE(items[1].name == "hello");
  8403. EXPECT_TRUE(items[1].content == "world");
  8404. EXPECT_TRUE(items[1].filename == "");
  8405. EXPECT_TRUE(items[1].content_type == "");
  8406. } else {
  8407. std::string body;
  8408. content_reader([&](const char *data, size_t data_length) {
  8409. body.append(data, data_length);
  8410. return true;
  8411. });
  8412. }
  8413. });
  8414. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8415. auto se = detail::scope_exit([&] {
  8416. svr.stop();
  8417. t.join();
  8418. ASSERT_FALSE(svr.is_running());
  8419. });
  8420. svr.wait_until_ready();
  8421. {
  8422. std::string data(1024 * 1024 * 2, '&');
  8423. std::stringstream buffer;
  8424. buffer << data;
  8425. Client cli("https://localhost:8080");
  8426. cli.enable_server_certificate_verification(false);
  8427. UploadFormDataItems items{
  8428. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8429. {"hello", "world", "", ""},
  8430. };
  8431. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8432. ASSERT_TRUE(res);
  8433. ASSERT_EQ(StatusCode::OK_200, res->status);
  8434. }
  8435. }
  8436. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8437. std::string data(1024 * 1024 * 2, '&');
  8438. std::stringstream buffer;
  8439. buffer << data;
  8440. Client cli("https://localhost:8080");
  8441. cli.enable_server_certificate_verification(false);
  8442. UploadFormDataItems items{
  8443. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8444. {"hello", "world", "", ""},
  8445. };
  8446. for (const char &c : " \t\r\n") {
  8447. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8448. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8449. ASSERT_FALSE(res);
  8450. }
  8451. }
  8452. TEST(MultipartFormDataTest, AlternateFilename) {
  8453. auto handled = false;
  8454. Server svr;
  8455. svr.Post("/test", [&](const Request &req, Response &res) {
  8456. ASSERT_EQ(2u, req.form.files.size());
  8457. ASSERT_EQ(1u, req.form.fields.size());
  8458. // Test files
  8459. const auto &file1 = req.form.get_file("file1");
  8460. ASSERT_EQ("file1", file1.name);
  8461. ASSERT_EQ("A.txt", file1.filename);
  8462. ASSERT_EQ("text/plain", file1.content_type);
  8463. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8464. const auto &file2 = req.form.get_file("file2");
  8465. ASSERT_EQ("file2", file2.name);
  8466. ASSERT_EQ("a.html", file2.filename);
  8467. ASSERT_EQ("text/html", file2.content_type);
  8468. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8469. file2.content);
  8470. // Test text field
  8471. const auto &text = req.form.get_field("text");
  8472. ASSERT_EQ("text default", text);
  8473. res.set_content("ok", "text/plain");
  8474. handled = true;
  8475. });
  8476. thread t = thread([&] { svr.listen(HOST, PORT); });
  8477. auto se = detail::scope_exit([&] {
  8478. svr.stop();
  8479. t.join();
  8480. ASSERT_FALSE(svr.is_running());
  8481. ASSERT_TRUE(handled);
  8482. });
  8483. svr.wait_until_ready();
  8484. auto req = "POST /test HTTP/1.1\r\n"
  8485. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8486. "Content-Length: 399\r\n"
  8487. "\r\n"
  8488. "----------\r\n"
  8489. "Content-Disposition: form-data; name=\"text\"\r\n"
  8490. "\r\n"
  8491. "text default\r\n"
  8492. "----------\r\n"
  8493. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8494. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8495. "Content-Type: text/plain\r\n"
  8496. "\r\n"
  8497. "Content of a.txt.\r\n"
  8498. "\r\n"
  8499. "----------\r\n"
  8500. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8501. "\"a.html\"\r\n"
  8502. "Content-Type: text/html\r\n"
  8503. "\r\n"
  8504. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8505. "\r\n"
  8506. "------------\r\n";
  8507. ASSERT_TRUE(send_request(1, req));
  8508. }
  8509. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8510. auto handled = false;
  8511. Server svr;
  8512. svr.Post("/test", [&](const Request &req, Response &) {
  8513. ASSERT_EQ(2u, req.form.fields.size());
  8514. const auto &text1 = req.form.get_field("text1");
  8515. ASSERT_EQ("text1", text1);
  8516. const auto &text2 = req.form.get_field("text2");
  8517. ASSERT_EQ("text2", text2);
  8518. handled = true;
  8519. });
  8520. thread t = thread([&] { svr.listen(HOST, PORT); });
  8521. auto se = detail::scope_exit([&] {
  8522. svr.stop();
  8523. t.join();
  8524. ASSERT_FALSE(svr.is_running());
  8525. ASSERT_TRUE(handled);
  8526. });
  8527. svr.wait_until_ready();
  8528. auto req = "POST /test HTTP/1.1\r\n"
  8529. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8530. "Content-Length: 146\r\n"
  8531. "\r\n----------\r\n"
  8532. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8533. "\r\n"
  8534. "text1"
  8535. "\r\n----------\r\n"
  8536. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8537. "\r\n"
  8538. "text2"
  8539. "\r\n------------";
  8540. std::string response;
  8541. ASSERT_TRUE(send_request(1, req, &response));
  8542. ASSERT_EQ("200", response.substr(9, 3));
  8543. }
  8544. TEST(MultipartFormDataTest, ContentLength) {
  8545. auto handled = false;
  8546. Server svr;
  8547. svr.Post("/test", [&](const Request &req, Response &) {
  8548. ASSERT_EQ(2u, req.form.fields.size());
  8549. const auto &text1 = req.form.get_field("text1");
  8550. ASSERT_EQ("text1", text1);
  8551. const auto &text2 = req.form.get_field("text2");
  8552. ASSERT_EQ("text2", text2);
  8553. handled = true;
  8554. });
  8555. thread t = thread([&] { svr.listen(HOST, PORT); });
  8556. auto se = detail::scope_exit([&] {
  8557. svr.stop();
  8558. t.join();
  8559. ASSERT_FALSE(svr.is_running());
  8560. ASSERT_TRUE(handled);
  8561. });
  8562. svr.wait_until_ready();
  8563. auto req = "POST /test HTTP/1.1\r\n"
  8564. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8565. "Content-Length: 167\r\n"
  8566. "\r\n----------\r\n"
  8567. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8568. "Content-Length: 5\r\n"
  8569. "\r\n"
  8570. "text1"
  8571. "\r\n----------\r\n"
  8572. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8573. "\r\n"
  8574. "text2"
  8575. "\r\n------------\r\n";
  8576. std::string response;
  8577. ASSERT_TRUE(send_request(1, req, &response));
  8578. ASSERT_EQ("200", response.substr(9, 3));
  8579. }
  8580. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8581. auto handled = false;
  8582. Server svr;
  8583. svr.Post("/test", [&](const Request &req, Response &) {
  8584. ASSERT_EQ(2u, req.form.fields.size());
  8585. const auto &text1 = req.form.get_field("text1");
  8586. ASSERT_EQ("text1", text1);
  8587. // TODO: Add header access for text fields if needed
  8588. const auto &text2 = req.form.get_field("text2");
  8589. ASSERT_EQ("text2", text2);
  8590. // TODO: Header access for text fields needs to be implemented
  8591. // auto &headers = it->second.headers;
  8592. // ASSERT_EQ(3U, headers.size());
  8593. // auto custom_header = headers.find("x-whatever");
  8594. // ASSERT_TRUE(custom_header != headers.end());
  8595. // ASSERT_NE("customvalue", custom_header->second);
  8596. // ASSERT_EQ("CustomValue", custom_header->second);
  8597. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8598. handled = true;
  8599. });
  8600. thread t = thread([&] { svr.listen(HOST, PORT); });
  8601. auto se = detail::scope_exit([&] {
  8602. svr.stop();
  8603. t.join();
  8604. ASSERT_FALSE(svr.is_running());
  8605. ASSERT_TRUE(handled);
  8606. });
  8607. svr.wait_until_ready();
  8608. auto req = "POST /test HTTP/1.1\r\n"
  8609. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8610. "Content-Length: 232\r\n"
  8611. "\r\n----------\r\n"
  8612. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8613. "Content-Length: 5\r\n"
  8614. "X-Test: 1\r\n"
  8615. "\r\n"
  8616. "text1"
  8617. "\r\n----------\r\n"
  8618. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8619. "Content-Type: text/plain\r\n"
  8620. "X-Whatever: CustomValue\r\n"
  8621. "\r\n"
  8622. "text2"
  8623. "\r\n------------\r\n"
  8624. "That should be disregarded. Not even read";
  8625. std::string response;
  8626. ASSERT_TRUE(send_request(1, req, &response));
  8627. ASSERT_EQ("200", response.substr(9, 3));
  8628. }
  8629. #endif
  8630. TEST(MultipartFormDataTest, LargeHeader) {
  8631. auto handled = false;
  8632. Server svr;
  8633. svr.Post("/test", [&](const Request &req, Response &) {
  8634. ASSERT_EQ(1u, req.form.fields.size());
  8635. const auto &text = req.form.get_field("name1");
  8636. ASSERT_EQ("text1", text);
  8637. handled = true;
  8638. });
  8639. thread t = thread([&] { svr.listen(HOST, PORT); });
  8640. auto se = detail::scope_exit([&] {
  8641. svr.stop();
  8642. t.join();
  8643. ASSERT_FALSE(svr.is_running());
  8644. ASSERT_TRUE(handled);
  8645. });
  8646. svr.wait_until_ready();
  8647. auto boundary = std::string("cpp-httplib-multipart-data");
  8648. std::string content = "--" + boundary +
  8649. "\r\n"
  8650. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8651. "\r\n"
  8652. "text1\r\n"
  8653. "--" +
  8654. boundary + "--\r\n";
  8655. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8656. "Content-Type: multipart/form-data;boundary=" +
  8657. boundary +
  8658. "\r\n"
  8659. "Content-Length: " +
  8660. std::to_string(content.size()) +
  8661. "\r\n"
  8662. "Dummy-Header: ";
  8663. std::string header_suffix = "\r\n"
  8664. "\r\n";
  8665. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8666. size_t header_dummy_size =
  8667. read_buff_size -
  8668. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8669. auto header_dummy = std::string(header_dummy_size, '@');
  8670. auto req = header_prefix + header_dummy + header_suffix + content;
  8671. std::string response;
  8672. ASSERT_TRUE(send_request(1, req, &response));
  8673. ASSERT_EQ("200", response.substr(9, 3));
  8674. }
  8675. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8676. static constexpr unsigned int number_of_tasks{1000000};
  8677. std::atomic_uint count{0};
  8678. std::unique_ptr<TaskQueue> task_queue{
  8679. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8680. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8681. auto queued = task_queue->enqueue(
  8682. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8683. EXPECT_TRUE(queued);
  8684. }
  8685. EXPECT_NO_THROW(task_queue->shutdown());
  8686. EXPECT_EQ(number_of_tasks, count.load());
  8687. }
  8688. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8689. static constexpr unsigned int number_of_tasks{1000000};
  8690. static constexpr unsigned int qlimit{2};
  8691. unsigned int queued_count{0};
  8692. std::atomic_uint count{0};
  8693. std::unique_ptr<TaskQueue> task_queue{
  8694. new ThreadPool{/*num_threads=*/1, qlimit}};
  8695. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8696. if (task_queue->enqueue(
  8697. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8698. queued_count++;
  8699. }
  8700. }
  8701. EXPECT_NO_THROW(task_queue->shutdown());
  8702. EXPECT_EQ(queued_count, count.load());
  8703. EXPECT_TRUE(queued_count <= number_of_tasks);
  8704. EXPECT_TRUE(queued_count >= qlimit);
  8705. }
  8706. TEST(TaskQueueTest, MaxQueuedRequests) {
  8707. static constexpr unsigned int qlimit{3};
  8708. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8709. std::condition_variable sem_cv;
  8710. std::mutex sem_mtx;
  8711. int credits = 0;
  8712. bool queued;
  8713. /* Fill up the queue with tasks that will block until we give them credits to
  8714. * complete. */
  8715. for (unsigned int n = 0; n <= qlimit;) {
  8716. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8717. std::unique_lock<std::mutex> lock(sem_mtx);
  8718. while (credits <= 0) {
  8719. sem_cv.wait(lock);
  8720. }
  8721. /* Consume the credit and signal the test code if they are all gone. */
  8722. if (--credits == 0) { sem_cv.notify_one(); }
  8723. });
  8724. if (n < qlimit) {
  8725. /* The first qlimit enqueues must succeed. */
  8726. EXPECT_TRUE(queued);
  8727. } else {
  8728. /* The last one will succeed only when the worker thread
  8729. * starts and dequeues the first blocking task. Although
  8730. * not necessary for the correctness of this test, we sleep for
  8731. * a short while to avoid busy waiting. */
  8732. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8733. }
  8734. if (queued) { n++; }
  8735. }
  8736. /* Further enqueues must fail since the queue is full. */
  8737. for (auto i = 0; i < 4; i++) {
  8738. queued = task_queue->enqueue([] {});
  8739. EXPECT_FALSE(queued);
  8740. }
  8741. /* Give the credits to allow the previous tasks to complete. */
  8742. {
  8743. std::unique_lock<std::mutex> lock(sem_mtx);
  8744. credits += qlimit + 1;
  8745. }
  8746. sem_cv.notify_all();
  8747. /* Wait for all the credits to be consumed. */
  8748. {
  8749. std::unique_lock<std::mutex> lock(sem_mtx);
  8750. while (credits > 0) {
  8751. sem_cv.wait(lock);
  8752. }
  8753. }
  8754. /* Check that we are able again to enqueue at least qlimit tasks. */
  8755. for (unsigned int i = 0; i < qlimit; i++) {
  8756. queued = task_queue->enqueue([] {});
  8757. EXPECT_TRUE(queued);
  8758. }
  8759. EXPECT_NO_THROW(task_queue->shutdown());
  8760. }
  8761. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8762. Server svr;
  8763. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8764. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8765. });
  8766. svr.Get("/hello", [](const Request &req, Response &res) {
  8767. res.set_content(req.get_param_value("key"), "text/plain");
  8768. });
  8769. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8770. auto se = detail::scope_exit([&] {
  8771. svr.stop();
  8772. thread.join();
  8773. ASSERT_FALSE(svr.is_running());
  8774. });
  8775. svr.wait_until_ready();
  8776. {
  8777. Client cli(HOST, PORT);
  8778. cli.set_follow_location(true);
  8779. auto res = cli.Get("/");
  8780. ASSERT_TRUE(res);
  8781. EXPECT_EQ(StatusCode::OK_200, res->status);
  8782. EXPECT_EQ("val&key2=val2", res->body);
  8783. }
  8784. }
  8785. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8786. Server svr;
  8787. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8788. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8789. });
  8790. svr.Get("/hello", [](const Request &req, Response &res) {
  8791. res.set_content(req.get_param_value("key"), "text/plain");
  8792. });
  8793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8794. auto se = detail::scope_exit([&] {
  8795. svr.stop();
  8796. thread.join();
  8797. ASSERT_FALSE(svr.is_running());
  8798. });
  8799. svr.wait_until_ready();
  8800. {
  8801. Client cli(HOST, PORT);
  8802. cli.set_follow_location(true);
  8803. auto res = cli.Get("/");
  8804. ASSERT_TRUE(res);
  8805. EXPECT_EQ(StatusCode::OK_200, res->status);
  8806. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8807. }
  8808. }
  8809. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8810. TEST(RedirectTest, Issue2185_Online) {
  8811. SSLClient client("github.com");
  8812. client.set_follow_location(true);
  8813. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8814. "Coollab-Windows.zip");
  8815. ASSERT_TRUE(res);
  8816. EXPECT_EQ(StatusCode::OK_200, res->status);
  8817. EXPECT_EQ(9920427U, res->body.size());
  8818. }
  8819. #endif
  8820. TEST(VulnerabilityTest, CRLFInjection) {
  8821. Server svr;
  8822. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8823. res.set_content("Hello 1", "text/plain");
  8824. });
  8825. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8826. res.set_content("Hello 2", "text/plain");
  8827. });
  8828. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8829. res.set_content("Hello 3", "text/plain");
  8830. });
  8831. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8832. res.set_content("Hello 4", "text/plain");
  8833. });
  8834. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8835. for (const auto &x : req.headers) {
  8836. auto key = x.first;
  8837. EXPECT_STRNE("evil", key.c_str());
  8838. }
  8839. });
  8840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8841. auto se = detail::scope_exit([&] {
  8842. svr.stop();
  8843. thread.join();
  8844. ASSERT_FALSE(svr.is_running());
  8845. });
  8846. svr.wait_until_ready();
  8847. {
  8848. Client cli(HOST, PORT);
  8849. cli.Post("/test1", "A=B",
  8850. "application/x-www-form-urlencoded\r\nevil: hello1");
  8851. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8852. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8853. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8854. }
  8855. }
  8856. TEST(PathParamsTest, StaticMatch) {
  8857. const auto pattern = "/users/all";
  8858. detail::PathParamsMatcher matcher(pattern);
  8859. Request request;
  8860. request.path = "/users/all";
  8861. ASSERT_TRUE(matcher.match(request));
  8862. std::unordered_map<std::string, std::string> expected_params = {};
  8863. EXPECT_EQ(request.path_params, expected_params);
  8864. }
  8865. TEST(PathParamsTest, StaticMismatch) {
  8866. const auto pattern = "/users/all";
  8867. detail::PathParamsMatcher matcher(pattern);
  8868. Request request;
  8869. request.path = "/users/1";
  8870. ASSERT_FALSE(matcher.match(request));
  8871. }
  8872. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8873. const auto pattern = "/users/:id/subscriptions";
  8874. detail::PathParamsMatcher matcher(pattern);
  8875. Request request;
  8876. request.path = "/users/42/subscriptions";
  8877. ASSERT_TRUE(matcher.match(request));
  8878. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8879. EXPECT_EQ(request.path_params, expected_params);
  8880. }
  8881. TEST(PathParamsTest, SingleParamInTheEnd) {
  8882. const auto pattern = "/users/:id";
  8883. detail::PathParamsMatcher matcher(pattern);
  8884. Request request;
  8885. request.path = "/users/24";
  8886. ASSERT_TRUE(matcher.match(request));
  8887. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8888. EXPECT_EQ(request.path_params, expected_params);
  8889. }
  8890. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8891. const auto pattern = "/users/:id/";
  8892. detail::PathParamsMatcher matcher(pattern);
  8893. Request request;
  8894. request.path = "/users/42/";
  8895. ASSERT_TRUE(matcher.match(request));
  8896. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8897. EXPECT_EQ(request.path_params, expected_params);
  8898. }
  8899. TEST(PathParamsTest, EmptyParam) {
  8900. const auto pattern = "/users/:id/";
  8901. detail::PathParamsMatcher matcher(pattern);
  8902. Request request;
  8903. request.path = "/users//";
  8904. ASSERT_TRUE(matcher.match(request));
  8905. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8906. EXPECT_EQ(request.path_params, expected_params);
  8907. }
  8908. TEST(PathParamsTest, FragmentMismatch) {
  8909. const auto pattern = "/users/:id/";
  8910. detail::PathParamsMatcher matcher(pattern);
  8911. Request request;
  8912. request.path = "/admins/24/";
  8913. ASSERT_FALSE(matcher.match(request));
  8914. }
  8915. TEST(PathParamsTest, ExtraFragments) {
  8916. const auto pattern = "/users/:id";
  8917. detail::PathParamsMatcher matcher(pattern);
  8918. Request request;
  8919. request.path = "/users/42/subscriptions";
  8920. ASSERT_FALSE(matcher.match(request));
  8921. }
  8922. TEST(PathParamsTest, MissingTrailingParam) {
  8923. const auto pattern = "/users/:id";
  8924. detail::PathParamsMatcher matcher(pattern);
  8925. Request request;
  8926. request.path = "/users";
  8927. ASSERT_FALSE(matcher.match(request));
  8928. }
  8929. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8930. const auto pattern = "/users/:id/subscriptions";
  8931. detail::PathParamsMatcher matcher(pattern);
  8932. Request request;
  8933. request.path = "/users/subscriptions";
  8934. ASSERT_FALSE(matcher.match(request));
  8935. }
  8936. TEST(PathParamsTest, MultipleParams) {
  8937. const auto pattern = "/users/:userid/subscriptions/:subid";
  8938. detail::PathParamsMatcher matcher(pattern);
  8939. Request request;
  8940. request.path = "/users/42/subscriptions/2";
  8941. ASSERT_TRUE(matcher.match(request));
  8942. std::unordered_map<std::string, std::string> expected_params = {
  8943. {"userid", "42"}, {"subid", "2"}};
  8944. EXPECT_EQ(request.path_params, expected_params);
  8945. }
  8946. TEST(PathParamsTest, SequenceOfParams) {
  8947. const auto pattern = "/values/:x/:y/:z";
  8948. detail::PathParamsMatcher matcher(pattern);
  8949. Request request;
  8950. request.path = "/values/1/2/3";
  8951. ASSERT_TRUE(matcher.match(request));
  8952. std::unordered_map<std::string, std::string> expected_params = {
  8953. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  8954. EXPECT_EQ(request.path_params, expected_params);
  8955. }
  8956. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  8957. const auto pattern = "/prefix:suffix";
  8958. detail::PathParamsMatcher matcher(pattern);
  8959. Request request;
  8960. request.path = "/prefix:suffix";
  8961. ASSERT_TRUE(matcher.match(request));
  8962. const std::unordered_map<std::string, std::string> expected_params = {};
  8963. EXPECT_EQ(request.path_params, expected_params);
  8964. }
  8965. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  8966. // If ipv6 regex working, regex match codepath is taken.
  8967. // else port will default to 80 in Client impl
  8968. int clientImplMagicPort = 80;
  8969. int port = 4321;
  8970. // above ports must be different to avoid false negative
  8971. EXPECT_NE(clientImplMagicPort, port);
  8972. std::string ipV6TestURL = "http://[ff06::c3]";
  8973. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  8974. CLIENT_PRIVATE_KEY_FILE);
  8975. EXPECT_EQ(cli.port(), port);
  8976. }
  8977. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  8978. auto file_path = "./www/dir/index.html";
  8979. auto dir_path = "./www/dir";
  8980. detail::FileStat stat_file(file_path);
  8981. EXPECT_TRUE(stat_file.is_file());
  8982. EXPECT_FALSE(stat_file.is_dir());
  8983. detail::FileStat stat_dir(dir_path);
  8984. EXPECT_FALSE(stat_dir.is_file());
  8985. EXPECT_TRUE(stat_dir.is_dir());
  8986. }
  8987. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  8988. // IPv4 with default HTTP port (80)
  8989. EXPECT_EQ("example.com",
  8990. detail::make_host_and_port_string("example.com", 80, false));
  8991. // IPv4 with default HTTPS port (443)
  8992. EXPECT_EQ("example.com",
  8993. detail::make_host_and_port_string("example.com", 443, true));
  8994. // IPv4 with non-default HTTP port
  8995. EXPECT_EQ("example.com:8080",
  8996. detail::make_host_and_port_string("example.com", 8080, false));
  8997. // IPv4 with non-default HTTPS port
  8998. EXPECT_EQ("example.com:8443",
  8999. detail::make_host_and_port_string("example.com", 8443, true));
  9000. // IPv6 with default HTTP port (80)
  9001. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9002. // IPv6 with default HTTPS port (443)
  9003. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9004. // IPv6 with non-default HTTP port
  9005. EXPECT_EQ("[::1]:8080",
  9006. detail::make_host_and_port_string("::1", 8080, false));
  9007. // IPv6 with non-default HTTPS port
  9008. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9009. // IPv6 full address with default port
  9010. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9011. detail::make_host_and_port_string(
  9012. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9013. // IPv6 full address with non-default port
  9014. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9015. detail::make_host_and_port_string(
  9016. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9017. // IPv6 localhost with non-default port
  9018. EXPECT_EQ("[::1]:3000",
  9019. detail::make_host_and_port_string("::1", 3000, false));
  9020. // IPv6 with zone ID (link-local address) with default port
  9021. EXPECT_EQ("[fe80::1%eth0]",
  9022. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9023. // IPv6 with zone ID (link-local address) with non-default port
  9024. EXPECT_EQ("[fe80::1%eth0]:8080",
  9025. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9026. // Edge case: Port 443 with is_ssl=false (should add port)
  9027. EXPECT_EQ("example.com:443",
  9028. detail::make_host_and_port_string("example.com", 443, false));
  9029. // Edge case: Port 80 with is_ssl=true (should add port)
  9030. EXPECT_EQ("example.com:80",
  9031. detail::make_host_and_port_string("example.com", 80, true));
  9032. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9033. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9034. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9035. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9036. // Security fix: Already bracketed IPv6 should not get double brackets
  9037. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9038. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9039. EXPECT_EQ("[::1]:8080",
  9040. detail::make_host_and_port_string("[::1]", 8080, false));
  9041. EXPECT_EQ("[2001:db8::1]:8080",
  9042. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9043. EXPECT_EQ("[fe80::1%eth0]",
  9044. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9045. EXPECT_EQ("[fe80::1%eth0]:8080",
  9046. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9047. // Edge case: Empty host (should return as-is)
  9048. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9049. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9050. // This is a known limitation but shouldn't crash
  9051. EXPECT_EQ("[host:name]",
  9052. detail::make_host_and_port_string("host:name", 80, false));
  9053. // Port number edge cases (no validation, but should not crash)
  9054. EXPECT_EQ("example.com:0",
  9055. detail::make_host_and_port_string("example.com", 0, false));
  9056. EXPECT_EQ("example.com:-1",
  9057. detail::make_host_and_port_string("example.com", -1, false));
  9058. EXPECT_EQ("example.com:65535",
  9059. detail::make_host_and_port_string("example.com", 65535, false));
  9060. EXPECT_EQ("example.com:65536",
  9061. detail::make_host_and_port_string("example.com", 65536, false));
  9062. }
  9063. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9064. Server svr;
  9065. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9066. EXPECT_EQ(res.status, 400);
  9067. });
  9068. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9069. auto se = detail::scope_exit([&] {
  9070. svr.stop();
  9071. thread.join();
  9072. ASSERT_FALSE(svr.is_running());
  9073. });
  9074. svr.wait_until_ready();
  9075. Client cli(HOST, PORT);
  9076. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9077. }
  9078. TEST(InvalidHeaderCharsTest, is_field_name) {
  9079. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9080. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9081. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9082. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9083. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9084. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9085. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9086. EXPECT_FALSE(detail::fields::is_field_name(""));
  9087. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9088. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9089. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9090. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9091. }
  9092. TEST(InvalidHeaderCharsTest, is_field_value) {
  9093. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9094. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9095. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9096. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9097. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9098. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9099. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9100. EXPECT_TRUE(detail::fields::is_field_value(""));
  9101. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9102. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9103. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9104. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9105. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9106. }
  9107. TEST(InvalidHeaderCharsTest, OnServer) {
  9108. Server svr;
  9109. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9110. std::string header = "Not Set";
  9111. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9112. res.set_header(header, "value");
  9113. res.set_content("Page Content Page Content", "text/plain");
  9114. });
  9115. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9116. std::string header = "Not Set";
  9117. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9118. res.set_header("X-Test", header);
  9119. res.set_content("Page Content Page Content", "text/plain");
  9120. });
  9121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9122. auto se = detail::scope_exit([&] {
  9123. svr.stop();
  9124. thread.join();
  9125. ASSERT_FALSE(svr.is_running());
  9126. });
  9127. svr.wait_until_ready();
  9128. Client cli(HOST, PORT);
  9129. {
  9130. auto res = cli.Get(
  9131. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9132. ASSERT_TRUE(res);
  9133. EXPECT_EQ("Page Content Page Content", res->body);
  9134. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9135. }
  9136. {
  9137. auto res = cli.Get(
  9138. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9139. ASSERT_TRUE(res);
  9140. EXPECT_EQ("Page Content Page Content", res->body);
  9141. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9142. }
  9143. }
  9144. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9145. auto handled = false;
  9146. Server svr;
  9147. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9148. thread t = thread([&] { svr.listen(HOST, PORT); });
  9149. auto se = detail::scope_exit([&] {
  9150. svr.stop();
  9151. t.join();
  9152. ASSERT_FALSE(svr.is_running());
  9153. ASSERT_FALSE(handled);
  9154. });
  9155. svr.wait_until_ready();
  9156. auto req = "POST /test HTTP/1.1\r\n"
  9157. "Content-Length: x\r\n"
  9158. "\r\n";
  9159. std::string response;
  9160. ASSERT_TRUE(send_request(1, req, &response));
  9161. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9162. response.substr(0, response.find("\r\n")));
  9163. }
  9164. #ifndef _WIN32
  9165. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9166. static constexpr char reject[] = "Unauthorized";
  9167. static constexpr char accept[] = "Upload accepted";
  9168. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9169. Server svr;
  9170. svr.set_expect_100_continue_handler(
  9171. [](const Request & /*req*/, Response &res) {
  9172. res.status = StatusCode::Unauthorized_401;
  9173. res.set_content(reject, "text/plain");
  9174. return res.status;
  9175. });
  9176. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9177. res.set_content(accept, "text/plain");
  9178. });
  9179. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9180. auto se = detail::scope_exit([&] {
  9181. svr.stop();
  9182. thread.join();
  9183. ASSERT_FALSE(svr.is_running());
  9184. });
  9185. svr.wait_until_ready();
  9186. {
  9187. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9188. curl_easy_init(), &curl_easy_cleanup};
  9189. ASSERT_NE(curl, nullptr);
  9190. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9191. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9192. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9193. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9194. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9195. &curl_slist_free_all};
  9196. ASSERT_NE(list, nullptr);
  9197. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9198. struct read_data {
  9199. size_t read_size;
  9200. size_t total_size;
  9201. } data = {0, total_size};
  9202. using read_callback_t =
  9203. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9204. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9205. void *userdata) -> size_t {
  9206. read_data *data = (read_data *)userdata;
  9207. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9208. std::fill_n(ptr, size * nmemb, 'A');
  9209. data->read_size += size * nmemb;
  9210. return size * nmemb;
  9211. };
  9212. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9213. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9214. std::vector<char> buffer;
  9215. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9216. using write_callback_t =
  9217. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9218. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9219. void *userdata) -> size_t {
  9220. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9221. buffer->reserve(buffer->size() + size * nmemb + 1);
  9222. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9223. return size * nmemb;
  9224. };
  9225. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9226. {
  9227. const auto res = curl_easy_perform(curl.get());
  9228. ASSERT_EQ(res, CURLE_OK);
  9229. }
  9230. {
  9231. auto response_code = long{};
  9232. const auto res =
  9233. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9234. ASSERT_EQ(res, CURLE_OK);
  9235. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9236. }
  9237. {
  9238. auto dl = curl_off_t{};
  9239. const auto res =
  9240. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9241. ASSERT_EQ(res, CURLE_OK);
  9242. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9243. }
  9244. {
  9245. buffer.push_back('\0');
  9246. ASSERT_STRCASEEQ(buffer.data(), reject);
  9247. }
  9248. }
  9249. }
  9250. #endif
  9251. template <typename S, typename C>
  9252. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9253. svr.Get("/stream", [&](const Request &, Response &res) {
  9254. auto data = new std::string("01234567890123456789");
  9255. res.set_content_provider(
  9256. data->size(), "text/plain",
  9257. [&, data](size_t offset, size_t length, DataSink &sink) {
  9258. const size_t DATA_CHUNK_SIZE = 4;
  9259. const auto &d = *data;
  9260. std::this_thread::sleep_for(std::chrono::seconds(1));
  9261. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9262. return true;
  9263. },
  9264. [data](bool success) {
  9265. EXPECT_FALSE(success);
  9266. delete data;
  9267. });
  9268. });
  9269. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9270. auto i = new size_t(0);
  9271. res.set_content_provider(
  9272. "text/plain",
  9273. [i](size_t, DataSink &sink) {
  9274. if (*i < 5) {
  9275. std::this_thread::sleep_for(std::chrono::seconds(1));
  9276. sink.write("abcd", 4);
  9277. (*i)++;
  9278. } else {
  9279. sink.done();
  9280. }
  9281. return true;
  9282. },
  9283. [i](bool success) {
  9284. EXPECT_FALSE(success);
  9285. delete i;
  9286. });
  9287. });
  9288. svr.Get("/chunked", [&](const Request &, Response &res) {
  9289. auto i = new size_t(0);
  9290. res.set_chunked_content_provider(
  9291. "text/plain",
  9292. [i](size_t, DataSink &sink) {
  9293. if (*i < 5) {
  9294. std::this_thread::sleep_for(std::chrono::seconds(1));
  9295. sink.os << "abcd";
  9296. (*i)++;
  9297. } else {
  9298. sink.done();
  9299. }
  9300. return true;
  9301. },
  9302. [i](bool success) {
  9303. EXPECT_FALSE(success);
  9304. delete i;
  9305. });
  9306. });
  9307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9308. auto se = detail::scope_exit([&] {
  9309. svr.stop();
  9310. listen_thread.join();
  9311. ASSERT_FALSE(svr.is_running());
  9312. });
  9313. svr.wait_until_ready();
  9314. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9315. {
  9316. auto start = std::chrono::steady_clock::now();
  9317. auto res = cli.Get("/stream");
  9318. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9319. std::chrono::steady_clock::now() - start)
  9320. .count();
  9321. ASSERT_FALSE(res);
  9322. EXPECT_EQ(Error::Read, res.error());
  9323. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9324. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9325. }
  9326. {
  9327. auto start = std::chrono::steady_clock::now();
  9328. auto res = cli.Get("/stream_without_length");
  9329. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9330. std::chrono::steady_clock::now() - start)
  9331. .count();
  9332. ASSERT_FALSE(res);
  9333. EXPECT_EQ(Error::Read, res.error());
  9334. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9335. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9336. }
  9337. {
  9338. auto start = std::chrono::steady_clock::now();
  9339. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9340. EXPECT_EQ("abcd", string(data, data_length));
  9341. return true;
  9342. });
  9343. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9344. std::chrono::steady_clock::now() - start)
  9345. .count();
  9346. ASSERT_FALSE(res);
  9347. EXPECT_EQ(Error::Read, res.error());
  9348. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9349. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9350. }
  9351. }
  9352. TEST(MaxTimeoutTest, ContentStream) {
  9353. time_t timeout = 2000;
  9354. time_t threshold = 200;
  9355. Server svr;
  9356. Client cli("localhost", PORT);
  9357. max_timeout_test(svr, cli, timeout, threshold);
  9358. }
  9359. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9360. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9361. time_t timeout = 2000;
  9362. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9364. SSLClient cli("localhost", PORT);
  9365. cli.enable_server_certificate_verification(false);
  9366. max_timeout_test(svr, cli, timeout, threshold);
  9367. }
  9368. #endif
  9369. class EventDispatcher {
  9370. public:
  9371. EventDispatcher() {}
  9372. bool wait_event(DataSink *sink) {
  9373. unique_lock<mutex> lk(m_);
  9374. int id = id_;
  9375. // Wait with timeout to prevent hanging if client disconnects
  9376. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9377. [&] { return cid_ == id; })) {
  9378. return false; // Timeout occurred
  9379. }
  9380. sink->write(message_.data(), message_.size());
  9381. return true;
  9382. }
  9383. void send_event(const string &message) {
  9384. lock_guard<mutex> lk(m_);
  9385. cid_ = id_++;
  9386. message_ = message;
  9387. cv_.notify_all();
  9388. }
  9389. private:
  9390. mutex m_;
  9391. condition_variable cv_;
  9392. atomic_int id_{0};
  9393. atomic_int cid_{-1};
  9394. string message_;
  9395. };
  9396. TEST(ClientInThreadTest, Issue2068) {
  9397. EventDispatcher ed;
  9398. Server svr;
  9399. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9400. res.set_chunked_content_provider("text/event-stream",
  9401. [&](size_t /*offset*/, DataSink &sink) {
  9402. return ed.wait_event(&sink);
  9403. });
  9404. });
  9405. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9406. svr.wait_until_ready();
  9407. thread event_thread([&] {
  9408. int id = 0;
  9409. while (svr.is_running()) {
  9410. this_thread::sleep_for(chrono::milliseconds(500));
  9411. std::stringstream ss;
  9412. ss << "data: " << id << "\n\n";
  9413. ed.send_event(ss.str());
  9414. id++;
  9415. }
  9416. });
  9417. auto se = detail::scope_exit([&] {
  9418. svr.stop();
  9419. listen_thread.join();
  9420. event_thread.join();
  9421. ASSERT_FALSE(svr.is_running());
  9422. });
  9423. {
  9424. auto client = detail::make_unique<Client>(HOST, PORT);
  9425. client->set_read_timeout(std::chrono::minutes(10));
  9426. std::atomic<bool> stop{false};
  9427. std::thread t([&] {
  9428. client->Get("/event1",
  9429. [&](const char *, size_t) -> bool { return !stop; });
  9430. });
  9431. std::this_thread::sleep_for(std::chrono::seconds(2));
  9432. stop = true;
  9433. client->stop();
  9434. t.join();
  9435. // Reset client after thread has finished
  9436. client.reset();
  9437. }
  9438. }
  9439. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9440. Server svr;
  9441. svr.Get("/", [](const Request &req, Response &res) {
  9442. EXPECT_EQ(2U, req.trailers.size());
  9443. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9444. // Denied
  9445. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9446. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9447. // Accepted
  9448. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9449. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9450. EXPECT_TRUE(req.has_trailer("X-World"));
  9451. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9452. res.set_content("ok", "text/plain");
  9453. });
  9454. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9455. auto se = detail::scope_exit([&] {
  9456. svr.stop();
  9457. t.join();
  9458. ASSERT_FALSE(svr.is_running());
  9459. });
  9460. svr.wait_until_ready();
  9461. const std::string req = "GET / HTTP/1.1\r\n"
  9462. "Transfer-Encoding: chunked\r\n"
  9463. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9464. "\r\n"
  9465. "0\r\n"
  9466. "Content-Length: 10\r\n"
  9467. "Host: internal.local\r\n"
  9468. "Content-Type: malicious/content\r\n"
  9469. "Cookie: any\r\n"
  9470. "Set-Cookie: any\r\n"
  9471. "X-Forwarded-For: attacker.com\r\n"
  9472. "X-Real-Ip: 1.1.1.1\r\n"
  9473. "X-Hello: hello\r\n"
  9474. "X-World: world\r\n"
  9475. "\r\n";
  9476. std::string res;
  9477. ASSERT_TRUE(send_request(1, req, &res));
  9478. }
  9479. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9480. Server svr;
  9481. std::string observed_remote_addr;
  9482. std::string observed_xff;
  9483. svr.Get("/ip", [&](const Request &req, Response &res) {
  9484. observed_remote_addr = req.remote_addr;
  9485. observed_xff = req.get_header_value("X-Forwarded-For");
  9486. res.set_content("ok", "text/plain");
  9487. });
  9488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. t.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. Client cli(HOST, PORT);
  9496. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9497. ASSERT_TRUE(res);
  9498. EXPECT_EQ(StatusCode::OK_200, res->status);
  9499. EXPECT_EQ(observed_xff, "203.0.113.66");
  9500. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9501. observed_remote_addr == "127.0.0.1");
  9502. }
  9503. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9504. Server svr;
  9505. svr.set_trusted_proxies({"203.0.113.66"});
  9506. std::string observed_remote_addr;
  9507. std::string observed_xff;
  9508. svr.Get("/ip", [&](const Request &req, Response &res) {
  9509. observed_remote_addr = req.remote_addr;
  9510. observed_xff = req.get_header_value("X-Forwarded-For");
  9511. res.set_content("ok", "text/plain");
  9512. });
  9513. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9514. auto se = detail::scope_exit([&] {
  9515. svr.stop();
  9516. t.join();
  9517. ASSERT_FALSE(svr.is_running());
  9518. });
  9519. svr.wait_until_ready();
  9520. Client cli(HOST, PORT);
  9521. auto res = cli.Get("/ip");
  9522. ASSERT_TRUE(res);
  9523. EXPECT_EQ(StatusCode::OK_200, res->status);
  9524. EXPECT_EQ(observed_xff, "");
  9525. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9526. observed_remote_addr == "127.0.0.1");
  9527. }
  9528. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9529. Server svr;
  9530. svr.set_trusted_proxies({"203.0.113.66"});
  9531. std::string observed_remote_addr;
  9532. std::string observed_xff;
  9533. svr.Get("/ip", [&](const Request &req, Response &res) {
  9534. observed_remote_addr = req.remote_addr;
  9535. observed_xff = req.get_header_value("X-Forwarded-For");
  9536. res.set_content("ok", "text/plain");
  9537. });
  9538. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9539. auto se = detail::scope_exit([&] {
  9540. svr.stop();
  9541. t.join();
  9542. ASSERT_FALSE(svr.is_running());
  9543. });
  9544. svr.wait_until_ready();
  9545. Client cli(HOST, PORT);
  9546. auto res =
  9547. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9548. ASSERT_TRUE(res);
  9549. EXPECT_EQ(StatusCode::OK_200, res->status);
  9550. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9551. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9552. }
  9553. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9554. Server svr;
  9555. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9556. std::string observed_remote_addr;
  9557. std::string observed_xff;
  9558. svr.Get("/ip", [&](const Request &req, Response &res) {
  9559. observed_remote_addr = req.remote_addr;
  9560. observed_xff = req.get_header_value("X-Forwarded-For");
  9561. res.set_content("ok", "text/plain");
  9562. });
  9563. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9564. auto se = detail::scope_exit([&] {
  9565. svr.stop();
  9566. t.join();
  9567. ASSERT_FALSE(svr.is_running());
  9568. });
  9569. svr.wait_until_ready();
  9570. Client cli(HOST, PORT);
  9571. auto res = cli.Get(
  9572. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9573. ASSERT_TRUE(res);
  9574. EXPECT_EQ(StatusCode::OK_200, res->status);
  9575. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9576. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9577. }
  9578. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9579. Server svr;
  9580. svr.set_trusted_proxies({"192.0.2.45"});
  9581. std::string observed_remote_addr;
  9582. std::string observed_xff;
  9583. svr.Get("/ip", [&](const Request &req, Response &res) {
  9584. observed_remote_addr = req.remote_addr;
  9585. observed_xff = req.get_header_value("X-Forwarded-For");
  9586. res.set_content("ok", "text/plain");
  9587. });
  9588. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9589. auto se = detail::scope_exit([&] {
  9590. svr.stop();
  9591. t.join();
  9592. ASSERT_FALSE(svr.is_running());
  9593. });
  9594. svr.wait_until_ready();
  9595. Client cli(HOST, PORT);
  9596. auto res =
  9597. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9598. ASSERT_TRUE(res);
  9599. EXPECT_EQ(StatusCode::OK_200, res->status);
  9600. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9601. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9602. }
  9603. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9604. Server svr;
  9605. svr.set_trusted_proxies({"192.0.2.45"});
  9606. std::string observed_remote_addr;
  9607. std::string observed_xff;
  9608. svr.Get("/ip", [&](const Request &req, Response &res) {
  9609. observed_remote_addr = req.remote_addr;
  9610. observed_xff = req.get_header_value("X-Forwarded-For");
  9611. res.set_content("ok", "text/plain");
  9612. });
  9613. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9614. auto se = detail::scope_exit([&] {
  9615. svr.stop();
  9616. t.join();
  9617. ASSERT_FALSE(svr.is_running());
  9618. });
  9619. svr.wait_until_ready();
  9620. Client cli(HOST, PORT);
  9621. auto res = cli.Get(
  9622. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9623. ASSERT_TRUE(res);
  9624. EXPECT_EQ(StatusCode::OK_200, res->status);
  9625. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9626. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9627. }
  9628. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9629. Server svr;
  9630. svr.set_trusted_proxies({"192.0.2.45"});
  9631. std::string observed_remote_addr;
  9632. std::string observed_xff;
  9633. svr.Get("/ip", [&](const Request &req, Response &res) {
  9634. observed_remote_addr = req.remote_addr;
  9635. observed_xff = req.get_header_value("X-Forwarded-For");
  9636. res.set_content("ok", "text/plain");
  9637. });
  9638. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9639. auto se = detail::scope_exit([&] {
  9640. svr.stop();
  9641. t.join();
  9642. ASSERT_FALSE(svr.is_running());
  9643. });
  9644. svr.wait_until_ready();
  9645. Client cli(HOST, PORT);
  9646. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9647. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9648. ASSERT_TRUE(res);
  9649. EXPECT_EQ(StatusCode::OK_200, res->status);
  9650. // Header parser trims surrounding whitespace of the header value
  9651. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9652. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9653. }
  9654. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9655. Server svr;
  9656. svr.Post("/post", [&](const Request &req, Response &res) {
  9657. res.set_content(req.body, "text/plain");
  9658. });
  9659. svr.Put("/put", [&](const Request &req, Response &res) {
  9660. res.set_content(req.body, "text/plain");
  9661. });
  9662. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9663. res.set_content(req.body, "text/plain");
  9664. });
  9665. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9666. res.set_content(req.body, "text/plain");
  9667. });
  9668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9669. auto se = detail::scope_exit([&] {
  9670. svr.stop();
  9671. t.join();
  9672. ASSERT_FALSE(svr.is_running());
  9673. });
  9674. svr.wait_until_ready();
  9675. std::string resp;
  9676. // POST without Content-Length
  9677. ASSERT_TRUE(send_request(5,
  9678. "POST /post HTTP/1.1\r\n"
  9679. "Host: localhost\r\n"
  9680. "Connection: close\r\n"
  9681. "\r\n",
  9682. &resp));
  9683. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9684. // PUT without Content-Length
  9685. resp.clear();
  9686. ASSERT_TRUE(send_request(5,
  9687. "PUT /put HTTP/1.1\r\n"
  9688. "Host: localhost\r\n"
  9689. "Connection: close\r\n"
  9690. "\r\n",
  9691. &resp));
  9692. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9693. // PATCH without Content-Length
  9694. resp.clear();
  9695. ASSERT_TRUE(send_request(5,
  9696. "PATCH /patch HTTP/1.1\r\n"
  9697. "Host: localhost\r\n"
  9698. "Connection: close\r\n"
  9699. "\r\n",
  9700. &resp));
  9701. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9702. // DELETE without Content-Length
  9703. resp.clear();
  9704. ASSERT_TRUE(send_request(5,
  9705. "DELETE /delete HTTP/1.1\r\n"
  9706. "Host: localhost\r\n"
  9707. "Connection: close\r\n"
  9708. "\r\n",
  9709. &resp));
  9710. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9711. }