test.cc 450 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) throw std::runtime_error("File not found: " + path);
  74. fs.seekg(0, std::ios_base::end);
  75. auto size = fs.tellg();
  76. fs.seekg(0);
  77. out.resize(static_cast<size_t>(size));
  78. fs.read(&out[0], static_cast<std::streamsize>(size));
  79. }
  80. void performance_test(const char *host) {
  81. Server svr;
  82. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  83. res.set_content("Benchmark Response", "text/plain");
  84. });
  85. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  86. auto se = detail::scope_exit([&] {
  87. svr.stop();
  88. listen_thread.join();
  89. ASSERT_FALSE(svr.is_running());
  90. });
  91. svr.wait_until_ready();
  92. Client cli(host, PORT);
  93. // Warm-up request to establish connection and resolve DNS
  94. auto warmup_res = cli.Get("/benchmark");
  95. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  96. // Run multiple trials and collect timings
  97. const int num_trials = 20;
  98. std::vector<int64_t> timings;
  99. timings.reserve(num_trials);
  100. for (int i = 0; i < num_trials; i++) {
  101. auto start = std::chrono::high_resolution_clock::now();
  102. auto res = cli.Get("/benchmark");
  103. auto end = std::chrono::high_resolution_clock::now();
  104. auto elapsed =
  105. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  106. .count();
  107. // Assertions after timing measurement to avoid overhead
  108. ASSERT_TRUE(res);
  109. EXPECT_EQ(StatusCode::OK_200, res->status);
  110. timings.push_back(elapsed);
  111. }
  112. // Calculate 25th percentile (lower quartile)
  113. std::sort(timings.begin(), timings.end());
  114. auto p25 = timings[num_trials / 4];
  115. // Format timings for output
  116. std::ostringstream timings_str;
  117. timings_str << "[";
  118. for (size_t i = 0; i < timings.size(); i++) {
  119. if (i > 0) timings_str << ", ";
  120. timings_str << timings[i];
  121. }
  122. timings_str << "]";
  123. // Localhost HTTP GET should be fast even in CI environments
  124. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  125. << "ms (Issue #1777). Timings: " << timings_str.str();
  126. }
  127. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  128. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  129. class UnixSocketTest : public ::testing::Test {
  130. protected:
  131. void TearDown() override { std::remove(pathname_.c_str()); }
  132. void client_GET(const std::string &addr) {
  133. httplib::Client cli{addr};
  134. cli.set_address_family(AF_UNIX);
  135. ASSERT_TRUE(cli.is_valid());
  136. const auto &result = cli.Get(pattern_);
  137. ASSERT_TRUE(result) << "error: " << result.error();
  138. const auto &resp = result.value();
  139. EXPECT_EQ(resp.status, StatusCode::OK_200);
  140. EXPECT_EQ(resp.body, content_);
  141. }
  142. const std::string pathname_{"./httplib-server.sock"};
  143. const std::string pattern_{"/hi"};
  144. const std::string content_{"Hello World!"};
  145. };
  146. TEST_F(UnixSocketTest, pathname) {
  147. httplib::Server svr;
  148. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  149. res.set_content(content_, "text/plain");
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_EQ(0, close(fds[1]));
  254. EXPECT_FALSE(s0.wait_writable());
  255. return true;
  256. });
  257. EXPECT_EQ(0, close(fds[0]));
  258. }
  259. TEST(SocketStream, wait_writable_INET) {
  260. sockaddr_in addr;
  261. memset(&addr, 0, sizeof(addr));
  262. addr.sin_family = AF_INET;
  263. addr.sin_port = htons(PORT + 1);
  264. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  265. int disconnected_svr_sock = -1;
  266. std::thread svr{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. EXPECT_FALSE(ss.wait_writable());
  292. return true;
  293. });
  294. ASSERT_EQ(0, close(disconnected_svr_sock));
  295. }
  296. #endif // #ifndef _WIN32
  297. TEST(ClientTest, MoveConstructible) {
  298. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  299. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  300. }
  301. TEST(ClientTest, MoveAssignable) {
  302. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  303. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  304. }
  305. #ifdef _WIN32
  306. TEST(StartupTest, WSAStartup) {
  307. WSADATA wsaData;
  308. int ret = WSAStartup(0x0002, &wsaData);
  309. ASSERT_EQ(0, ret);
  310. }
  311. #endif
  312. TEST(DecodePathTest, PercentCharacter) {
  313. EXPECT_EQ(
  314. decode_path_component(
  315. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  316. U8("descrip=Gastos áéíóúñÑ 6"));
  317. }
  318. TEST(DecodePathTest, PercentCharacterNUL) {
  319. string expected;
  320. expected.push_back('x');
  321. expected.push_back('\0');
  322. expected.push_back('x');
  323. EXPECT_EQ(decode_path_component("x%00x"), expected);
  324. }
  325. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  326. string unescapedCharacters = "-_.!~*'()";
  327. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  328. }
  329. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  330. string reservedCharacters = ";,/?:@&=+$";
  331. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  332. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  333. }
  334. TEST(ClientQueryOrder, PreserveOrder) {
  335. // This test reproduces Issue #2259: client may reorder query parameters
  336. // when sending a GET request. The expected behavior is that the client
  337. // preserves the original query string order when the caller supplied it
  338. // as part of the path.
  339. Server svr;
  340. svr.Get("/", [&](const Request &req, Response &res) {
  341. // Echo back the raw target so the test can assert ordering
  342. res.set_content(req.target, "text/plain");
  343. });
  344. std::thread t{[&] { svr.listen(HOST, PORT); }};
  345. auto se = detail::scope_exit([&] {
  346. svr.stop();
  347. t.join();
  348. ASSERT_FALSE(svr.is_running());
  349. });
  350. svr.wait_until_ready();
  351. Client cli(HOST, PORT);
  352. ASSERT_TRUE(cli.is_valid());
  353. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  354. auto res = cli.Get(original);
  355. ASSERT_TRUE(res);
  356. // Expect the echoed target to exactly match the original path (order
  357. // preserved)
  358. EXPECT_EQ(res->body, original);
  359. }
  360. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  361. string chineseCharacters = U8("中国語");
  362. string russianCharacters = U8("дом");
  363. string brazilianCharacters = U8("óculos");
  364. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  365. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  366. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  367. "%D0%B4%D0%BE%D0%BC");
  368. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  369. }
  370. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  371. string unescapedCharacters = "-_.!~*'()";
  372. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  373. }
  374. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  375. string reservedCharacters = ";,/?:@&=+$";
  376. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  377. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  378. }
  379. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  380. string chineseCharacters = U8("中国語");
  381. string russianCharacters = U8("дом");
  382. string brazilianCharacters = U8("óculos");
  383. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  384. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  385. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  386. "%D0%B4%D0%BE%D0%BC");
  387. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  388. }
  389. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  390. // Issue #2082 use case: encoding path component with ampersand
  391. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  392. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  393. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  394. }
  395. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  400. string reservedCharacters = ";,/?:@&=+$#";
  401. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  402. }
  403. TEST(EncodeUriTest, TestUTF8Characters) {
  404. string chineseCharacters = U8("中国語");
  405. string russianCharacters = U8("дом");
  406. string brazilianCharacters = U8("óculos");
  407. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  408. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  409. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  410. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  411. }
  412. TEST(EncodeUriTest, TestCompleteUri) {
  413. string uri =
  414. "https://example.com/path/to/resource?query=value&param=test#fragment";
  415. EXPECT_EQ(
  416. httplib::encode_uri(uri),
  417. "https://example.com/path/to/resource?query=value&param=test#fragment");
  418. }
  419. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  420. string uri =
  421. "https://example.com/path with spaces/file name.html?q=hello world";
  422. EXPECT_EQ(httplib::encode_uri(uri),
  423. "https://example.com/path%20with%20spaces/"
  424. "file%20name.html?q=hello%20world");
  425. }
  426. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  427. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  428. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  429. }
  430. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  435. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  436. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  437. string encodedBrazilian = "%C3%B3culos";
  438. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  441. }
  442. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  443. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  445. "Piri Tommy Villiers - on & on");
  446. }
  447. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  449. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  450. }
  451. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  453. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  454. }
  455. TEST(DecodeUriTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriTest, TestCompleteUri) {
  464. string encodedUri = "https://example.com/path%20with%20spaces/"
  465. "file%20name.html?q=hello%20world";
  466. EXPECT_EQ(
  467. httplib::decode_uri(encodedUri),
  468. "https://example.com/path with spaces/file name.html?q=hello world");
  469. }
  470. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  471. string original =
  472. "https://example.com/path with spaces/file name.html?q=hello world";
  473. string encoded = httplib::encode_uri(original);
  474. string decoded = httplib::decode_uri(encoded);
  475. EXPECT_EQ(decoded, original);
  476. }
  477. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  478. string original = "Piri Tommy Villiers - on & on";
  479. string encoded = httplib::encode_uri_component(original);
  480. string decoded = httplib::decode_uri_component(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(TrimTests, TrimStringTests) {
  484. EXPECT_EQ("abc", detail::trim_copy("abc"));
  485. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  486. EXPECT_TRUE(detail::trim_copy("").empty());
  487. }
  488. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  489. // Simple case without quality values
  490. std::vector<std::string> result1;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html,application/json,text/plain", result1));
  493. EXPECT_EQ(result1.size(), 3U);
  494. EXPECT_EQ(result1[0], "text/html");
  495. EXPECT_EQ(result1[1], "application/json");
  496. EXPECT_EQ(result1[2], "text/plain");
  497. // With quality values
  498. std::vector<std::string> result2;
  499. EXPECT_TRUE(detail::parse_accept_header(
  500. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  501. EXPECT_EQ(result2.size(), 3U);
  502. EXPECT_EQ(result2[0], "application/json"); // highest q value
  503. EXPECT_EQ(result2[1], "text/html");
  504. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  505. }
  506. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  507. // Mixed with and without quality values
  508. std::vector<std::string> result;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  511. EXPECT_EQ(result.size(), 3U);
  512. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  513. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  514. EXPECT_EQ(result[2], "application/json"); // q=0.5
  515. }
  516. TEST(ParseAcceptHeaderTest, EdgeCases) {
  517. // Empty header
  518. std::vector<std::string> empty_result;
  519. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  520. EXPECT_TRUE(empty_result.empty());
  521. // Single type
  522. std::vector<std::string> single_result;
  523. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  524. EXPECT_EQ(single_result.size(), 1U);
  525. EXPECT_EQ(single_result[0], "application/json");
  526. // Wildcard types
  527. std::vector<std::string> wildcard_result;
  528. EXPECT_TRUE(detail::parse_accept_header(
  529. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  530. EXPECT_EQ(wildcard_result.size(), 3U);
  531. EXPECT_EQ(wildcard_result[0], "application/json");
  532. EXPECT_EQ(wildcard_result[1], "text/*");
  533. EXPECT_EQ(wildcard_result[2], "*/*");
  534. }
  535. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  536. // Common browser Accept header
  537. std::vector<std::string> browser_result;
  538. EXPECT_TRUE(
  539. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  540. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  541. browser_result));
  542. EXPECT_EQ(browser_result.size(), 6U);
  543. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  548. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  549. // API client header
  550. std::vector<std::string> api_result;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  553. api_result));
  554. EXPECT_EQ(api_result.size(), 3U);
  555. EXPECT_EQ(api_result[0], "application/json");
  556. EXPECT_EQ(api_result[1], "application/xml");
  557. EXPECT_EQ(api_result[2], "text/plain");
  558. }
  559. TEST(ParseAcceptHeaderTest, SpecialCases) {
  560. // Quality value with 3 decimal places
  561. std::vector<std::string> decimal_result;
  562. EXPECT_TRUE(detail::parse_accept_header(
  563. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  564. EXPECT_EQ(decimal_result.size(), 2U);
  565. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  566. EXPECT_EQ(decimal_result[1], "text/html");
  567. // Zero quality (should still be included but with lowest priority)
  568. std::vector<std::string> zero_q_result;
  569. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  570. zero_q_result));
  571. EXPECT_EQ(zero_q_result.size(), 2U);
  572. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  573. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  574. // No spaces around commas
  575. std::vector<std::string> no_space_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  578. no_space_result));
  579. EXPECT_EQ(no_space_result.size(), 3U);
  580. EXPECT_EQ(no_space_result[0], "text/html");
  581. EXPECT_EQ(no_space_result[1], "application/json");
  582. EXPECT_EQ(no_space_result[2], "text/plain");
  583. }
  584. TEST(ParseAcceptHeaderTest, InvalidCases) {
  585. std::vector<std::string> result;
  586. // Invalid quality value (> 1.0)
  587. EXPECT_FALSE(
  588. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  589. // Invalid quality value (< 0.0)
  590. EXPECT_FALSE(
  591. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  592. // Invalid quality value (not a number)
  593. EXPECT_FALSE(detail::parse_accept_header(
  594. "text/html;q=invalid,application/json", result));
  595. // Empty quality value
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=,application/json", result));
  598. // Invalid media type format (no slash and not wildcard)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("invalidtype,application/json", result));
  601. // Empty media type
  602. result.clear();
  603. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  604. // Only commas
  605. result.clear();
  606. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  607. // Valid cases should still work
  608. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  609. EXPECT_EQ(result.size(), 1U);
  610. EXPECT_EQ(result[0], "*/*");
  611. EXPECT_TRUE(detail::parse_accept_header("*", result));
  612. EXPECT_EQ(result.size(), 1U);
  613. EXPECT_EQ(result[0], "*");
  614. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "text/*");
  617. }
  618. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  619. Server svr;
  620. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  621. EXPECT_EQ(req.accept_content_types.size(), 3U);
  622. EXPECT_EQ(req.accept_content_types[0], "application/json");
  623. EXPECT_EQ(req.accept_content_types[1], "text/html");
  624. EXPECT_EQ(req.accept_content_types[2], "*/*");
  625. res.set_content("ok", "text/plain");
  626. });
  627. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  628. EXPECT_TRUE(false);
  629. res.set_content("bad request", "text/plain");
  630. });
  631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  632. auto se = detail::scope_exit([&] {
  633. svr.stop();
  634. listen_thread.join();
  635. ASSERT_FALSE(svr.is_running());
  636. });
  637. svr.wait_until_ready();
  638. Client cli("localhost", PORT);
  639. {
  640. auto res =
  641. cli.Get("/accept_ok",
  642. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  643. ASSERT_TRUE(res);
  644. EXPECT_EQ(StatusCode::OK_200, res->status);
  645. }
  646. {
  647. auto res = cli.Get("/accept_bad_request",
  648. {{"Accept", "text/html;q=abc,application/json"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  651. }
  652. }
  653. TEST(DivideTest, DivideStringTests) {
  654. auto divide = [](const std::string &str, char d) {
  655. std::string lhs;
  656. std::string rhs;
  657. detail::divide(str, d,
  658. [&](const char *lhs_data, std::size_t lhs_size,
  659. const char *rhs_data, std::size_t rhs_size) {
  660. lhs.assign(lhs_data, lhs_size);
  661. rhs.assign(rhs_data, rhs_size);
  662. });
  663. return std::make_pair(std::move(lhs), std::move(rhs));
  664. };
  665. {
  666. const auto res = divide("", '=');
  667. EXPECT_EQ(res.first, "");
  668. EXPECT_EQ(res.second, "");
  669. }
  670. {
  671. const auto res = divide("=", '=');
  672. EXPECT_EQ(res.first, "");
  673. EXPECT_EQ(res.second, "");
  674. }
  675. {
  676. const auto res = divide(" ", '=');
  677. EXPECT_EQ(res.first, " ");
  678. EXPECT_EQ(res.second, "");
  679. }
  680. {
  681. const auto res = divide("a", '=');
  682. EXPECT_EQ(res.first, "a");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("a=", '=');
  687. EXPECT_EQ(res.first, "a");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide("=b", '=');
  692. EXPECT_EQ(res.first, "");
  693. EXPECT_EQ(res.second, "b");
  694. }
  695. {
  696. const auto res = divide("a=b", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "b");
  699. }
  700. {
  701. const auto res = divide("a=b=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "b=");
  704. }
  705. {
  706. const auto res = divide("a=b=c", '=');
  707. EXPECT_EQ(res.first, "a");
  708. EXPECT_EQ(res.second, "b=c");
  709. }
  710. }
  711. TEST(SplitTest, ParseQueryString) {
  712. string s = "key1=val1&key2=val2&key3=val3";
  713. Params dic;
  714. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  715. [&](const char *b, const char *e) {
  716. string key, val;
  717. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  718. if (key.empty()) {
  719. key.assign(b2, e2);
  720. } else {
  721. val.assign(b2, e2);
  722. }
  723. });
  724. dic.emplace(key, val);
  725. });
  726. EXPECT_EQ("val1", dic.find("key1")->second);
  727. EXPECT_EQ("val2", dic.find("key2")->second);
  728. EXPECT_EQ("val3", dic.find("key3")->second);
  729. }
  730. TEST(SplitTest, ParseInvalidQueryTests) {
  731. {
  732. string s = " ";
  733. Params dict;
  734. detail::parse_query_text(s, dict);
  735. EXPECT_TRUE(dict.empty());
  736. }
  737. {
  738. string s = " = =";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. }
  744. TEST(ParseQueryTest, ParseQueryString) {
  745. {
  746. std::string s = "key1=val1&key2=val2&key3=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("val1", dic.find("key1")->second);
  750. EXPECT_EQ("val2", dic.find("key2")->second);
  751. EXPECT_EQ("val3", dic.find("key3")->second);
  752. }
  753. {
  754. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  755. Params dic;
  756. detail::parse_query_text(s, dic);
  757. EXPECT_EQ("", dic.find("key1")->second);
  758. EXPECT_EQ("val1", dic.find("key2")->second);
  759. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  760. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  761. }
  762. }
  763. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  764. Params dic;
  765. EXPECT_EQ(detail::params_to_query_str(dic), "");
  766. dic.emplace("key1", "val1");
  767. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  768. dic.emplace("key2", "val2");
  769. dic.emplace("key3", "val3");
  770. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  771. }
  772. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  773. string content_type = "multipart/form-data; boundary=something";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "something");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  780. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  795. string content_type =
  796. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  797. string boundary;
  798. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  801. }
  802. TEST(GetHeaderValueTest, DefaultValue) {
  803. Headers headers = {{"Dummy", "Dummy"}};
  804. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  805. EXPECT_STREQ("text/plain", val);
  806. }
  807. TEST(GetHeaderValueTest, DefaultValueInt) {
  808. Headers headers = {{"Dummy", "Dummy"}};
  809. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  810. EXPECT_EQ(100ull, val);
  811. }
  812. TEST(GetHeaderValueTest, RegularValue) {
  813. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  814. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  815. EXPECT_STREQ("text/html", val);
  816. }
  817. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  818. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  820. EXPECT_STREQ("text/html", val);
  821. }
  822. TEST(GetHeaderValueTest, SetContent) {
  823. Response res;
  824. res.set_content("html", "text/html");
  825. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  826. res.set_content("text", "text/plain");
  827. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  828. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  829. }
  830. TEST(GetHeaderValueTest, RegularValueInt) {
  831. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  833. EXPECT_EQ(100ull, val);
  834. }
  835. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  836. Headers headers = {{"Content-Length", "x"}};
  837. auto is_invalid_value = false;
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  839. is_invalid_value);
  840. EXPECT_EQ(0ull, val);
  841. EXPECT_TRUE(is_invalid_value);
  842. }
  843. TEST(GetHeaderValueTest, Range) {
  844. {
  845. Headers headers = {make_range_header({{1, -1}})};
  846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  847. EXPECT_STREQ("bytes=1-", val);
  848. }
  849. {
  850. Headers headers = {make_range_header({{-1, 1}})};
  851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  852. EXPECT_STREQ("bytes=-1", val);
  853. }
  854. {
  855. Headers headers = {make_range_header({{1, 10}})};
  856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  857. EXPECT_STREQ("bytes=1-10", val);
  858. }
  859. {
  860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-10, 100-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=0-0, -1", val);
  873. }
  874. }
  875. TEST(ParseHeaderValueTest, Range) {
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=1-", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(1u, ranges[0].first);
  882. EXPECT_EQ(-1, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=-1", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(-1, ranges[0].first);
  890. EXPECT_EQ(1u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  895. EXPECT_TRUE(ret);
  896. EXPECT_EQ(1u, ranges.size());
  897. EXPECT_EQ(1u, ranges[0].first);
  898. EXPECT_EQ(10u, ranges[0].second);
  899. }
  900. {
  901. Ranges ranges;
  902. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  903. EXPECT_FALSE(ret);
  904. }
  905. {
  906. Ranges ranges;
  907. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  908. EXPECT_TRUE(ret);
  909. EXPECT_EQ(2u, ranges.size());
  910. EXPECT_EQ(1u, ranges[0].first);
  911. EXPECT_EQ(10u, ranges[0].second);
  912. EXPECT_EQ(100u, ranges[1].first);
  913. EXPECT_EQ(-1, ranges[1].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret =
  918. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  919. EXPECT_TRUE(ret);
  920. EXPECT_EQ(3u, ranges.size());
  921. EXPECT_EQ(1u, ranges[0].first);
  922. EXPECT_EQ(10u, ranges[0].second);
  923. EXPECT_EQ(100u, ranges[1].first);
  924. EXPECT_EQ(200u, ranges[1].second);
  925. EXPECT_EQ(300u, ranges[2].first);
  926. EXPECT_EQ(400u, ranges[2].second);
  927. }
  928. {
  929. Ranges ranges;
  930. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  943. EXPECT_TRUE(ranges.empty());
  944. }
  945. }
  946. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  947. Request req;
  948. req.set_header("Accept-Encoding", "gzip");
  949. Response res;
  950. res.set_header("Content-Type", "text/plain");
  951. auto ret = detail::encoding_type(req, res);
  952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  966. #elif CPPHTTPLIB_ZLIB_SUPPORT
  967. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  968. #elif CPPHTTPLIB_ZSTD_SUPPORT
  969. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  970. #else
  971. EXPECT_TRUE(ret == detail::EncodingType::None);
  972. #endif
  973. }
  974. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  975. Request req;
  976. req.set_header("Accept-Encoding",
  977. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  978. Response res;
  979. res.set_header("Content-Type", "text/plain");
  980. auto ret = detail::encoding_type(req, res);
  981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  983. #elif CPPHTTPLIB_ZLIB_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  985. #elif CPPHTTPLIB_ZSTD_SUPPORT
  986. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  987. #else
  988. EXPECT_TRUE(ret == detail::EncodingType::None);
  989. #endif
  990. }
  991. TEST(BufferStreamTest, read) {
  992. detail::BufferStream strm1;
  993. Stream &strm = strm1;
  994. EXPECT_EQ(5, strm.write("hello"));
  995. char buf[512];
  996. EXPECT_EQ(2, strm.read(buf, 2));
  997. EXPECT_EQ('h', buf[0]);
  998. EXPECT_EQ('e', buf[1]);
  999. EXPECT_EQ(2, strm.read(buf, 2));
  1000. EXPECT_EQ('l', buf[0]);
  1001. EXPECT_EQ('l', buf[1]);
  1002. EXPECT_EQ(1, strm.read(buf, 1));
  1003. EXPECT_EQ('o', buf[0]);
  1004. EXPECT_EQ(0, strm.read(buf, 1));
  1005. }
  1006. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1007. auto host = "www.httpwatch.com";
  1008. auto ip = hosted_at(host);
  1009. EXPECT_EQ("23.96.13.243", ip);
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(1u, addrs.size());
  1013. }
  1014. #if 0 // It depends on each test environment...
  1015. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1016. auto host = "www.youtube.com";
  1017. std::vector<std::string> addrs;
  1018. hosted_at(host, addrs);
  1019. EXPECT_EQ(20u, addrs.size());
  1020. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1021. EXPECT_TRUE(it != addrs.end());
  1022. }
  1023. #endif
  1024. class ChunkedEncodingTest : public ::testing::Test {
  1025. protected:
  1026. ChunkedEncodingTest()
  1027. : cli_(HOST, PORT)
  1028. #ifdef CPPHTTPLIB_SSL_ENABLED
  1029. ,
  1030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1031. #endif
  1032. {
  1033. cli_.set_connection_timeout(2);
  1034. #ifdef CPPHTTPLIB_SSL_ENABLED
  1035. cli_.enable_server_certificate_verification(false);
  1036. #endif
  1037. }
  1038. virtual void SetUp() {
  1039. read_file("./image.jpg", image_data_);
  1040. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content("Hello World!", "text/plain");
  1042. });
  1043. svr_.Get(
  1044. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1045. res.set_chunked_content_provider(
  1046. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1047. size_t remaining = image_data_.size() - offset;
  1048. if (remaining == 0) {
  1049. sink.done();
  1050. } else {
  1051. constexpr size_t CHUNK_SIZE = 1024;
  1052. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1053. sink.write(&image_data_[offset], send_size);
  1054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1055. }
  1056. return true;
  1057. });
  1058. });
  1059. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1060. svr_.wait_until_ready();
  1061. }
  1062. virtual void TearDown() {
  1063. svr_.stop();
  1064. if (!request_threads_.empty()) {
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. for (auto &t : request_threads_) {
  1067. t.join();
  1068. }
  1069. }
  1070. t_.join();
  1071. }
  1072. #ifdef CPPHTTPLIB_SSL_ENABLED
  1073. SSLClient cli_;
  1074. SSLServer svr_;
  1075. #else
  1076. Client cli_;
  1077. Server svr_;
  1078. #endif
  1079. thread t_;
  1080. std::vector<thread> request_threads_;
  1081. std::string image_data_;
  1082. };
  1083. TEST_F(ChunkedEncodingTest, NormalGet) {
  1084. auto res = cli_.Get("/chunked");
  1085. ASSERT_TRUE(res);
  1086. std::string out;
  1087. read_file("./image.jpg", out);
  1088. EXPECT_EQ(StatusCode::OK_200, res->status);
  1089. EXPECT_EQ(out, res->body);
  1090. }
  1091. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1092. std::string body;
  1093. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1094. body.append(data, data_length);
  1095. return true;
  1096. });
  1097. ASSERT_TRUE(res);
  1098. std::string out;
  1099. read_file("./image.jpg", out);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. EXPECT_EQ(out, body);
  1102. }
  1103. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1104. std::string body;
  1105. auto res = cli_.Get(
  1106. "/chunked",
  1107. [&](const Response &response) {
  1108. EXPECT_EQ(StatusCode::OK_200, response.status);
  1109. return true;
  1110. },
  1111. [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST(RangeTest, FromHTTPBin_Online) {
  1122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1123. auto host = "httpcan.org";
  1124. auto path = std::string{"/range/32"};
  1125. #else
  1126. auto host = "nghttp2.org";
  1127. auto path = std::string{"/httpbin/range/32"};
  1128. #endif
  1129. #ifdef CPPHTTPLIB_SSL_ENABLED
  1130. auto port = 443;
  1131. SSLClient cli(host, port);
  1132. #else
  1133. auto port = 80;
  1134. Client cli(host, port);
  1135. #endif
  1136. cli.set_connection_timeout(5);
  1137. {
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::OK_200, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, -1}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{1, 10}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("bcdefghijk", res->body);
  1155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, 31}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, -1}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. }
  1171. {
  1172. Headers headers = {make_range_header({{0, 32}})};
  1173. auto res = cli.Get(path, headers);
  1174. ASSERT_TRUE(res);
  1175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1176. }
  1177. }
  1178. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1179. auto host = "unresolvableaddress.local";
  1180. auto path = std::string{"/"};
  1181. #ifdef CPPHTTPLIB_SSL_ENABLED
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(1);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_FALSE(res);
  1192. }
  1193. std::this_thread::sleep_for(std::chrono::seconds(8));
  1194. }
  1195. TEST(ConnectionErrorTest, InvalidHost) {
  1196. auto host = "-abcde.com";
  1197. #ifdef CPPHTTPLIB_SSL_ENABLED
  1198. auto port = 443;
  1199. SSLClient cli(host, port);
  1200. #else
  1201. auto port = 80;
  1202. Client cli(host, port);
  1203. #endif
  1204. cli.set_connection_timeout(std::chrono::seconds(2));
  1205. auto res = cli.Get("/");
  1206. ASSERT_TRUE(!res);
  1207. EXPECT_EQ(Error::Connection, res.error());
  1208. }
  1209. TEST(ConnectionErrorTest, InvalidHost2) {
  1210. auto host = "httpcan.org/";
  1211. #ifdef CPPHTTPLIB_SSL_ENABLED
  1212. SSLClient cli(host);
  1213. #else
  1214. Client cli(host);
  1215. #endif
  1216. cli.set_connection_timeout(std::chrono::seconds(2));
  1217. auto res = cli.Get("/");
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Connection, res.error());
  1220. }
  1221. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1222. auto host = "httpcan.org/";
  1223. #ifdef CPPHTTPLIB_SSL_ENABLED
  1224. SSLClient cli(host);
  1225. #else
  1226. Client cli(host);
  1227. #endif
  1228. cli.set_connection_timeout(std::chrono::seconds(2));
  1229. auto res = cli.Get("/");
  1230. ASSERT_TRUE(!res);
  1231. stringstream s;
  1232. s << "error code: " << res.error();
  1233. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1234. }
  1235. TEST(ConnectionErrorTest, InvalidPort) {
  1236. auto host = "localhost";
  1237. auto port = 44380;
  1238. #ifdef CPPHTTPLIB_SSL_ENABLED
  1239. SSLClient cli(host, port);
  1240. #else
  1241. Client cli(host, port);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. EXPECT_TRUE(Error::Connection == res.error() ||
  1247. Error::ConnectionTimeout == res.error());
  1248. }
  1249. TEST(ConnectionErrorTest, Timeout_Online) {
  1250. auto host = "google.com";
  1251. #ifdef CPPHTTPLIB_SSL_ENABLED
  1252. auto port = 44380;
  1253. SSLClient cli(host, port);
  1254. #else
  1255. auto port = 8080;
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. // only probe one address type so that the error reason
  1260. // correlates to the timed-out IPv4, not the unsupported
  1261. // IPv6 connection attempt
  1262. cli.set_address_family(AF_INET);
  1263. auto res = cli.Get("/");
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1266. }
  1267. TEST(CancelTest, NoCancel_Online) {
  1268. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1269. auto host = "httpcan.org";
  1270. auto path = std::string{"/range/32"};
  1271. #else
  1272. auto host = "nghttp2.org";
  1273. auto path = std::string{"/httpbin/range/32"};
  1274. #endif
  1275. #ifdef CPPHTTPLIB_SSL_ENABLED
  1276. auto port = 443;
  1277. SSLClient cli(host, port);
  1278. #else
  1279. auto port = 80;
  1280. Client cli(host, port);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(5));
  1283. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1284. ASSERT_TRUE(res);
  1285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1286. EXPECT_EQ(StatusCode::OK_200, res->status);
  1287. }
  1288. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1289. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1290. auto host = "httpcan.org";
  1291. auto path = std::string{"/range/32"};
  1292. #else
  1293. auto host = "nghttp2.org";
  1294. auto path = std::string{"/httpbin/range/32"};
  1295. #endif
  1296. #ifdef CPPHTTPLIB_SSL_ENABLED
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1304. cli.set_connection_timeout(std::chrono::seconds(5));
  1305. ASSERT_TRUE(!res);
  1306. EXPECT_EQ(Error::Canceled, res.error());
  1307. }
  1308. TEST(CancelTest, WithCancelLargePayload_Online) {
  1309. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1310. auto host = "httpcan.org";
  1311. auto path = std::string{"/range/65536"};
  1312. #else
  1313. auto host = "nghttp2.org";
  1314. auto path = std::string{"/httpbin/range/65536"};
  1315. #endif
  1316. #ifdef CPPHTTPLIB_SSL_ENABLED
  1317. auto port = 443;
  1318. SSLClient cli(host, port);
  1319. #else
  1320. auto port = 80;
  1321. Client cli(host, port);
  1322. #endif
  1323. cli.set_connection_timeout(std::chrono::seconds(5));
  1324. uint32_t count = 0;
  1325. auto res =
  1326. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1327. ASSERT_TRUE(!res);
  1328. EXPECT_EQ(Error::Canceled, res.error());
  1329. }
  1330. TEST(CancelTest, NoCancelPost) {
  1331. Server svr;
  1332. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1333. res.set_content("Hello World!", "text/plain");
  1334. });
  1335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1336. auto se = detail::scope_exit([&] {
  1337. svr.stop();
  1338. thread.join();
  1339. ASSERT_FALSE(svr.is_running());
  1340. });
  1341. svr.wait_until_ready();
  1342. Client cli(HOST, PORT);
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res =
  1345. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1346. "application/json", [](uint64_t, uint64_t) { return true; });
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("Hello World!", res->body);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1352. Server svr;
  1353. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1354. res.set_content("Hello World!", "text/plain");
  1355. });
  1356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1357. auto se = detail::scope_exit([&] {
  1358. svr.stop();
  1359. thread.join();
  1360. ASSERT_FALSE(svr.is_running());
  1361. });
  1362. svr.wait_until_ready();
  1363. Client cli(HOST, PORT);
  1364. cli.set_connection_timeout(std::chrono::seconds(5));
  1365. auto res =
  1366. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1367. "application/json", [](uint64_t, uint64_t) { return false; });
  1368. ASSERT_TRUE(!res);
  1369. EXPECT_EQ(Error::Canceled, res.error());
  1370. }
  1371. TEST(CancelTest, WithCancelLargePayloadPost) {
  1372. Server svr;
  1373. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1374. res.set_content(LARGE_DATA, "text/plain");
  1375. });
  1376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1377. auto se = detail::scope_exit([&] {
  1378. svr.stop();
  1379. thread.join();
  1380. ASSERT_FALSE(svr.is_running());
  1381. });
  1382. svr.wait_until_ready();
  1383. Client cli(HOST, PORT);
  1384. cli.set_connection_timeout(std::chrono::seconds(5));
  1385. auto res =
  1386. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1387. "application/json", [](uint64_t, uint64_t) { return false; });
  1388. ASSERT_TRUE(!res);
  1389. EXPECT_EQ(Error::Canceled, res.error());
  1390. }
  1391. TEST(CancelTest, NoCancelPut) {
  1392. Server svr;
  1393. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. });
  1396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. thread.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. Client cli(HOST, PORT);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return true; });
  1408. ASSERT_TRUE(res);
  1409. EXPECT_EQ("Hello World!", res->body);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. }
  1412. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1413. Server svr;
  1414. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1415. res.set_content("Hello World!", "text/plain");
  1416. });
  1417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1418. auto se = detail::scope_exit([&] {
  1419. svr.stop();
  1420. thread.join();
  1421. ASSERT_FALSE(svr.is_running());
  1422. });
  1423. svr.wait_until_ready();
  1424. Client cli(HOST, PORT);
  1425. cli.set_connection_timeout(std::chrono::seconds(5));
  1426. auto res =
  1427. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1428. "application/json", [](uint64_t, uint64_t) { return false; });
  1429. ASSERT_TRUE(!res);
  1430. EXPECT_EQ(Error::Canceled, res.error());
  1431. }
  1432. TEST(CancelTest, WithCancelLargePayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content(LARGE_DATA, "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, NoCancelPatch) {
  1453. Server svr;
  1454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("Hello World!", "text/plain");
  1456. });
  1457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1458. auto se = detail::scope_exit([&] {
  1459. svr.stop();
  1460. thread.join();
  1461. ASSERT_FALSE(svr.is_running());
  1462. });
  1463. svr.wait_until_ready();
  1464. Client cli(HOST, PORT);
  1465. cli.set_connection_timeout(std::chrono::seconds(5));
  1466. auto res =
  1467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1468. "application/json", [](uint64_t, uint64_t) { return true; });
  1469. ASSERT_TRUE(res);
  1470. EXPECT_EQ("Hello World!", res->body);
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1474. Server svr;
  1475. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1476. res.set_content("Hello World!", "text/plain");
  1477. });
  1478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. thread.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. Client cli(HOST, PORT);
  1486. cli.set_connection_timeout(std::chrono::seconds(5));
  1487. auto res =
  1488. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1489. "application/json", [](uint64_t, uint64_t) { return false; });
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_EQ(Error::Canceled, res.error());
  1492. }
  1493. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1494. Server svr;
  1495. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1496. res.set_content(LARGE_DATA, "text/plain");
  1497. });
  1498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1499. auto se = detail::scope_exit([&] {
  1500. svr.stop();
  1501. thread.join();
  1502. ASSERT_FALSE(svr.is_running());
  1503. });
  1504. svr.wait_until_ready();
  1505. Client cli(HOST, PORT);
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. auto res =
  1508. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1509. "application/json", [](uint64_t, uint64_t) { return false; });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelDelete) {
  1514. Server svr;
  1515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1555. Server svr;
  1556. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1557. res.set_content(LARGE_DATA, "text/plain");
  1558. });
  1559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. thread.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. Client cli(HOST, PORT);
  1567. cli.set_connection_timeout(std::chrono::seconds(5));
  1568. auto res =
  1569. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1570. "application/json", [](uint64_t, uint64_t) { return false; });
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Canceled, res.error());
  1573. }
  1574. static std::string remove_whitespace(const std::string &input) {
  1575. std::string output;
  1576. output.reserve(input.size());
  1577. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1578. [](unsigned char c) { return !std::isspace(c); });
  1579. return output;
  1580. }
  1581. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1582. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1583. auto host = "httpcan.org";
  1584. auto path = std::string{"/basic-auth/hello/world"};
  1585. #else
  1586. auto host = "nghttp2.org";
  1587. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1588. #endif
  1589. #ifdef CPPHTTPLIB_SSL_ENABLED
  1590. auto port = 443;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 80;
  1594. Client cli(host, port);
  1595. #endif
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1600. }
  1601. {
  1602. auto res =
  1603. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "world");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1614. remove_whitespace(res->body));
  1615. EXPECT_EQ(StatusCode::OK_200, res->status);
  1616. }
  1617. {
  1618. cli.set_basic_auth("hello", "bad");
  1619. auto res = cli.Get(path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("bad", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. }
  1630. #ifdef CPPHTTPLIB_SSL_ENABLED
  1631. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1632. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1633. auto host = "httpcan.org";
  1634. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/digest-auth/auth/hello/world/MD5",
  1637. "/digest-auth/auth/hello/world/SHA-256",
  1638. "/digest-auth/auth/hello/world/SHA-512",
  1639. };
  1640. #else
  1641. auto host = "nghttp2.org";
  1642. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1643. auto paths = std::vector<std::string>{
  1644. "/httpbin/digest-auth/auth/hello/world/MD5",
  1645. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1646. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1647. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1648. };
  1649. #endif
  1650. auto port = 443;
  1651. SSLClient cli(host, port);
  1652. {
  1653. auto res = cli.Get(unauth_path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. cli.set_digest_auth("hello", "world");
  1659. for (const auto &path : paths) {
  1660. auto res = cli.Get(path.c_str());
  1661. ASSERT_TRUE(res);
  1662. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1663. std::string algo(path.substr(path.rfind('/') + 1));
  1664. EXPECT_EQ(
  1665. remove_whitespace("{\"algorithm\":\"" + algo +
  1666. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1667. remove_whitespace(res->body));
  1668. #else
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. #endif
  1672. EXPECT_EQ(StatusCode::OK_200, res->status);
  1673. }
  1674. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1675. cli.set_digest_auth("hello", "bad");
  1676. for (const auto &path : paths) {
  1677. auto res = cli.Get(path.c_str());
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. #endif
  1682. }
  1683. }
  1684. #endif
  1685. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1686. auto host = "google.com";
  1687. auto another_host = "example.com";
  1688. auto wrong_ip = "0.0.0.0";
  1689. #ifdef CPPHTTPLIB_SSL_ENABLED
  1690. SSLClient cli(host);
  1691. #else
  1692. Client cli(host);
  1693. #endif
  1694. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1695. auto res = cli.Get("/");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1698. }
  1699. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1700. auto host = "google.com";
  1701. auto wrong_ip = "0.0.0.0";
  1702. #ifdef CPPHTTPLIB_SSL_ENABLED
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_hostname_addr_map({{host, wrong_ip}});
  1708. auto res = cli.Get("/");
  1709. ASSERT_TRUE(!res);
  1710. EXPECT_EQ(Error::Connection, res.error());
  1711. }
  1712. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_SSL_ENABLED
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(StatusCode::OK_200, res->status);
  1723. }
  1724. TEST(RedirectTest, Redirect_Online) {
  1725. auto host = "nghttp2.org";
  1726. #ifdef CPPHTTPLIB_SSL_ENABLED
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_follow_location(true);
  1732. auto res = cli.Get("/httpbin/redirect/3");
  1733. ASSERT_TRUE(res);
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. TEST(RelativeRedirectTest, Redirect_Online) {
  1737. auto host = "nghttp2.org";
  1738. #ifdef CPPHTTPLIB_SSL_ENABLED
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_follow_location(true);
  1744. auto res = cli.Get("/httpbin/relative-redirect/3");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. }
  1748. TEST(TooManyRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_SSL_ENABLED
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/redirect/21");
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1759. }
  1760. #ifdef CPPHTTPLIB_SSL_ENABLED
  1761. TEST(YahooRedirectTest, Redirect_Online) {
  1762. Client cli("yahoo.com");
  1763. auto res = cli.Get("/");
  1764. ASSERT_TRUE(res);
  1765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1766. cli.set_follow_location(true);
  1767. res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1771. }
  1772. #endif
  1773. #ifdef CPPHTTPLIB_SSL_ENABLED
  1774. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1775. #define REDIR_HOST "httpbingo.org"
  1776. #define REDIR_PATH "/redirect-to"
  1777. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1778. SSLClient cli(REDIR_HOST);
  1779. cli.set_follow_location(true);
  1780. auto res =
  1781. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. params.emplace("status_code", "302");
  1791. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1792. ASSERT_TRUE(res);
  1793. EXPECT_EQ(StatusCode::OK_200, res->status);
  1794. }
  1795. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1796. SSLClient cli(REDIR_HOST);
  1797. cli.set_follow_location(true);
  1798. Params params;
  1799. params.emplace("url", "http://example.com");
  1800. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(StatusCode::OK_200, res->status);
  1803. }
  1804. #endif
  1805. #ifdef CPPHTTPLIB_SSL_ENABLED
  1806. TEST(UrlWithSpace, Redirect_Online) {
  1807. SSLClient cli("edge.forgecdn.net");
  1808. cli.set_follow_location(true);
  1809. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1810. ASSERT_TRUE(res);
  1811. EXPECT_EQ(StatusCode::OK_200, res->status);
  1812. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1813. }
  1814. #endif
  1815. #if !defined(_WIN32) && !defined(_WIN64)
  1816. TEST(ReceiveSignals, Signal) {
  1817. auto setupSignalHandlers = []() {
  1818. struct sigaction act;
  1819. sigemptyset(&act.sa_mask);
  1820. act.sa_flags = SA_SIGINFO;
  1821. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1822. switch (sig) {
  1823. case SIGINT:
  1824. default: break;
  1825. }
  1826. };
  1827. ::sigaction(SIGINT, &act, nullptr);
  1828. };
  1829. Server svr;
  1830. int port = 0;
  1831. auto thread = std::thread([&]() {
  1832. setupSignalHandlers();
  1833. port = svr.bind_to_any_port(HOST);
  1834. svr.listen_after_bind();
  1835. });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. thread.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. ASSERT_TRUE(svr.is_running());
  1843. pthread_kill(thread.native_handle(), SIGINT);
  1844. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1845. ASSERT_TRUE(svr.is_running());
  1846. }
  1847. #endif
  1848. TEST(RedirectToDifferentPort, Redirect) {
  1849. Server svr1;
  1850. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1851. res.set_content("Hello World!", "text/plain");
  1852. });
  1853. int svr1_port = 0;
  1854. auto thread1 = std::thread([&]() {
  1855. svr1_port = svr1.bind_to_any_port(HOST);
  1856. svr1.listen_after_bind();
  1857. });
  1858. Server svr2;
  1859. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1860. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1861. });
  1862. int svr2_port = 0;
  1863. auto thread2 = std::thread([&]() {
  1864. svr2_port = svr2.bind_to_any_port(HOST);
  1865. svr2.listen_after_bind();
  1866. });
  1867. auto se = detail::scope_exit([&] {
  1868. svr2.stop();
  1869. thread2.join();
  1870. svr1.stop();
  1871. thread1.join();
  1872. ASSERT_FALSE(svr2.is_running());
  1873. ASSERT_FALSE(svr1.is_running());
  1874. });
  1875. svr1.wait_until_ready();
  1876. svr2.wait_until_ready();
  1877. Client cli("localhost", svr2_port);
  1878. cli.set_follow_location(true);
  1879. auto res = cli.Get("/2");
  1880. ASSERT_TRUE(res);
  1881. EXPECT_EQ(StatusCode::OK_200, res->status);
  1882. EXPECT_EQ("Hello World!", res->body);
  1883. }
  1884. TEST(RedirectFromPageWithContent, 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. });
  1890. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1891. res.set_content("Hello World!", "text/plain");
  1892. });
  1893. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1894. auto se = detail::scope_exit([&] {
  1895. svr.stop();
  1896. th.join();
  1897. ASSERT_FALSE(svr.is_running());
  1898. });
  1899. svr.wait_until_ready();
  1900. {
  1901. Client cli("localhost", PORT);
  1902. cli.set_follow_location(true);
  1903. std::string body;
  1904. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1905. body.append(data, data_length);
  1906. return true;
  1907. });
  1908. ASSERT_TRUE(res);
  1909. EXPECT_EQ(StatusCode::OK_200, res->status);
  1910. EXPECT_EQ("Hello World!", body);
  1911. }
  1912. {
  1913. Client cli("localhost", PORT);
  1914. std::string body;
  1915. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1916. body.append(data, data_length);
  1917. return true;
  1918. });
  1919. ASSERT_TRUE(res);
  1920. EXPECT_EQ(StatusCode::Found_302, res->status);
  1921. EXPECT_EQ("___", body);
  1922. }
  1923. }
  1924. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1925. Server svr;
  1926. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1927. res.set_content("___", "text/plain");
  1928. // res.set_redirect("/2");
  1929. res.set_redirect("http://[::1]:1234/2");
  1930. });
  1931. svr.Get("/2", [&](const Request &req, Response &res) {
  1932. auto host_header = req.headers.find("Host");
  1933. ASSERT_TRUE(host_header != req.headers.end());
  1934. EXPECT_EQ("[::1]:1234", host_header->second);
  1935. res.set_content("Hello World!", "text/plain");
  1936. });
  1937. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1938. auto se = detail::scope_exit([&] {
  1939. svr.stop();
  1940. th.join();
  1941. ASSERT_FALSE(svr.is_running());
  1942. });
  1943. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1944. // actually starts anything, so the condition !svr.is_running() will
  1945. // always remain true, and the loop never stops.
  1946. // This basically counts how many milliseconds have passed since the
  1947. // call to svr.listen(), and if after 5 seconds nothing started yet
  1948. // aborts the test.
  1949. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1950. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1951. ASSERT_LT(milliseconds, 5000U);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. cli.set_follow_location(true);
  1956. std::string body;
  1957. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1958. body.append(data, data_length);
  1959. return true;
  1960. });
  1961. ASSERT_TRUE(res);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ("Hello World!", body);
  1964. }
  1965. {
  1966. Client cli("http://[::1]:1234");
  1967. std::string body;
  1968. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1969. body.append(data, data_length);
  1970. return true;
  1971. });
  1972. ASSERT_TRUE(res);
  1973. EXPECT_EQ(StatusCode::Found_302, res->status);
  1974. EXPECT_EQ("___", body);
  1975. }
  1976. }
  1977. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1978. Server svr;
  1979. svr.Get("/foo", [](const Request &req, Response &res) {
  1980. auto a = req.params.find("a");
  1981. if (a != req.params.end()) {
  1982. res.set_content((*a).second, "text/plain");
  1983. res.status = StatusCode::OK_200;
  1984. } else {
  1985. res.status = StatusCode::BadRequest_400;
  1986. }
  1987. });
  1988. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1989. auto se = detail::scope_exit([&] {
  1990. svr.stop();
  1991. thread.join();
  1992. ASSERT_FALSE(svr.is_running());
  1993. });
  1994. svr.wait_until_ready();
  1995. {
  1996. Client cli(HOST, PORT);
  1997. cli.set_path_encode(false);
  1998. auto res = cli.Get("/foo?a=explicitly+encoded");
  1999. ASSERT_TRUE(res);
  2000. EXPECT_EQ(StatusCode::OK_200, res->status);
  2001. // This expects it back with a space, as the `+` won't have been
  2002. // url-encoded, and server-side the params get decoded turning `+`
  2003. // into spaces.
  2004. EXPECT_EQ("explicitly encoded", res->body);
  2005. }
  2006. }
  2007. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2008. Server svr;
  2009. svr.Get("/", [](const Request &req, Response &) {
  2010. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2011. });
  2012. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2013. auto se = detail::scope_exit([&] {
  2014. svr.stop();
  2015. thread.join();
  2016. ASSERT_FALSE(svr.is_running());
  2017. });
  2018. svr.wait_until_ready();
  2019. {
  2020. Client cli(HOST, PORT);
  2021. cli.set_path_encode(false);
  2022. auto res = cli.Get("/?something=%0A");
  2023. ASSERT_TRUE(res);
  2024. EXPECT_EQ(StatusCode::OK_200, res->status);
  2025. }
  2026. }
  2027. TEST(BindServerTest, DISABLED_BindDualStack) {
  2028. Server svr;
  2029. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2030. res.set_content("Hello World!", "text/plain");
  2031. });
  2032. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2033. auto se = detail::scope_exit([&] {
  2034. svr.stop();
  2035. thread.join();
  2036. ASSERT_FALSE(svr.is_running());
  2037. });
  2038. svr.wait_until_ready();
  2039. {
  2040. Client cli("127.0.0.1", PORT);
  2041. auto res = cli.Get("/1");
  2042. ASSERT_TRUE(res);
  2043. EXPECT_EQ(StatusCode::OK_200, res->status);
  2044. EXPECT_EQ("Hello World!", res->body);
  2045. }
  2046. {
  2047. Client cli("::1", PORT);
  2048. auto res = cli.Get("/1");
  2049. ASSERT_TRUE(res);
  2050. EXPECT_EQ(StatusCode::OK_200, res->status);
  2051. EXPECT_EQ("Hello World!", res->body);
  2052. }
  2053. }
  2054. TEST(BindServerTest, BindAndListenSeparately) {
  2055. Server svr;
  2056. int port = svr.bind_to_any_port("0.0.0.0");
  2057. ASSERT_TRUE(svr.is_valid());
  2058. ASSERT_TRUE(port > 0);
  2059. svr.stop();
  2060. }
  2061. #ifdef CPPHTTPLIB_SSL_ENABLED
  2062. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2064. CLIENT_CA_CERT_DIR);
  2065. int port = svr.bind_to_any_port("0.0.0.0");
  2066. ASSERT_TRUE(svr.is_valid());
  2067. ASSERT_TRUE(port > 0);
  2068. svr.stop();
  2069. }
  2070. #endif
  2071. #ifdef CPPHTTPLIB_SSL_ENABLED
  2072. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2073. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2074. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2075. int port = svr.bind_to_any_port("0.0.0.0");
  2076. ASSERT_TRUE(svr.is_valid());
  2077. ASSERT_TRUE(port > 0);
  2078. svr.stop();
  2079. }
  2080. #endif
  2081. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2082. X509 *readCertificate(const std::string &strFileName) {
  2083. std::ifstream inStream(strFileName);
  2084. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2085. std::istreambuf_iterator<char>());
  2086. if (strCertPEM.empty()) return (nullptr);
  2087. BIO *pbCert = BIO_new(BIO_s_mem());
  2088. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2089. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2090. BIO_free(pbCert);
  2091. return (pCert);
  2092. }
  2093. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2094. std::ifstream inStream(strFileName);
  2095. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2096. std::istreambuf_iterator<char>());
  2097. if (strPrivateKeyPEM.empty()) return (nullptr);
  2098. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2099. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2100. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2101. BIO_free(pbPrivKey);
  2102. return (pPrivateKey);
  2103. }
  2104. TEST(BindServerTest, UpdateCerts) {
  2105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2106. int port = svr.bind_to_any_port("0.0.0.0");
  2107. ASSERT_TRUE(svr.is_valid());
  2108. ASSERT_TRUE(port > 0);
  2109. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2110. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2111. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2112. ASSERT_TRUE(cert != nullptr);
  2113. ASSERT_TRUE(ca_cert != nullptr);
  2114. ASSERT_TRUE(key != nullptr);
  2115. X509_STORE *cert_store = X509_STORE_new();
  2116. X509_STORE_add_cert(cert_store, ca_cert);
  2117. svr.update_certs(cert, key, cert_store);
  2118. ASSERT_TRUE(svr.is_valid());
  2119. svr.stop();
  2120. X509_free(cert);
  2121. X509_free(ca_cert);
  2122. EVP_PKEY_free(key);
  2123. }
  2124. // Test that SSLServer(X509*, EVP_PKEY*, X509_STORE*) constructor sets
  2125. // client CA list correctly for TLS handshake
  2126. TEST(SSLClientServerTest, X509ConstructorSetsClientCAList) {
  2127. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2128. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2129. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2130. ASSERT_TRUE(cert != nullptr);
  2131. ASSERT_TRUE(ca_cert != nullptr);
  2132. ASSERT_TRUE(key != nullptr);
  2133. X509_STORE *cert_store = X509_STORE_new();
  2134. X509_STORE_add_cert(cert_store, ca_cert);
  2135. // Use X509-based constructor (deprecated but should still work correctly)
  2136. #pragma GCC diagnostic push
  2137. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  2138. SSLServer svr(cert, key, cert_store);
  2139. #pragma GCC diagnostic pop
  2140. ASSERT_TRUE(svr.is_valid());
  2141. // Verify that client CA list is set in SSL_CTX
  2142. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  2143. ASSERT_TRUE(ssl_ctx != nullptr);
  2144. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  2145. ASSERT_TRUE(ca_list != nullptr);
  2146. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  2147. X509_free(cert);
  2148. X509_free(ca_cert);
  2149. EVP_PKEY_free(key);
  2150. }
  2151. // Test that update_certs() updates client CA list correctly
  2152. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  2153. // Start with file-based constructor
  2154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2155. ASSERT_TRUE(svr.is_valid());
  2156. // Initially no client CA list should be set
  2157. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  2158. ASSERT_TRUE(ssl_ctx != nullptr);
  2159. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  2160. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  2161. EXPECT_EQ(0, count_before);
  2162. // Now update with client CA
  2163. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2164. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2165. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2166. ASSERT_TRUE(cert != nullptr);
  2167. ASSERT_TRUE(ca_cert != nullptr);
  2168. ASSERT_TRUE(key != nullptr);
  2169. X509_STORE *cert_store = X509_STORE_new();
  2170. X509_STORE_add_cert(cert_store, ca_cert);
  2171. #pragma GCC diagnostic push
  2172. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  2173. svr.update_certs(cert, key, cert_store);
  2174. #pragma GCC diagnostic pop
  2175. ASSERT_TRUE(svr.is_valid());
  2176. // Now client CA list should be set
  2177. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  2178. ASSERT_TRUE(ca_list_after != nullptr);
  2179. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  2180. X509_free(cert);
  2181. X509_free(ca_cert);
  2182. EVP_PKEY_free(key);
  2183. }
  2184. #endif
  2185. TEST(ErrorHandlerTest, ContentLength) {
  2186. Server svr;
  2187. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2188. res.status = StatusCode::OK_200;
  2189. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2190. "text/html"); // <= Content-Length still 13
  2191. });
  2192. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!\n", "text/plain");
  2194. res.status = 524;
  2195. });
  2196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2197. auto se = detail::scope_exit([&] {
  2198. svr.stop();
  2199. thread.join();
  2200. ASSERT_FALSE(svr.is_running());
  2201. });
  2202. svr.wait_until_ready();
  2203. {
  2204. Client cli(HOST, PORT);
  2205. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2206. ASSERT_TRUE(res);
  2207. EXPECT_EQ(StatusCode::OK_200, res->status);
  2208. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2209. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2211. }
  2212. }
  2213. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2214. TEST(ExceptionTest, WithoutExceptionHandler) {
  2215. Server svr;
  2216. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2217. throw std::runtime_error("exception...");
  2218. });
  2219. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2220. throw std::runtime_error("exception\r\n...");
  2221. });
  2222. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2223. auto se = detail::scope_exit([&] {
  2224. svr.stop();
  2225. listen_thread.join();
  2226. ASSERT_FALSE(svr.is_running());
  2227. });
  2228. svr.wait_until_ready();
  2229. Client cli("localhost", PORT);
  2230. {
  2231. auto res = cli.Get("/exception");
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2234. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2235. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2236. }
  2237. {
  2238. auto res = cli.Get("/unknown");
  2239. ASSERT_TRUE(res);
  2240. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2241. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2242. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2243. }
  2244. }
  2245. TEST(ExceptionTest, WithExceptionHandler) {
  2246. Server svr;
  2247. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2248. std::exception_ptr ep) {
  2249. EXPECT_FALSE(ep == nullptr);
  2250. try {
  2251. std::rethrow_exception(ep);
  2252. } catch (std::exception &e) {
  2253. EXPECT_EQ("abc", std::string(e.what()));
  2254. } catch (...) {}
  2255. res.status = StatusCode::InternalServerError_500;
  2256. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2257. "text/html"); // <= Content-Length still 13 at this point
  2258. });
  2259. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2260. res.set_content("Hello World!\n", "text/plain");
  2261. throw std::runtime_error("abc");
  2262. });
  2263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2264. auto se = detail::scope_exit([&] {
  2265. svr.stop();
  2266. thread.join();
  2267. ASSERT_FALSE(svr.is_running());
  2268. });
  2269. svr.wait_until_ready();
  2270. for (size_t i = 0; i < 10; i++) {
  2271. Client cli(HOST, PORT);
  2272. for (size_t j = 0; j < 100; j++) {
  2273. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2274. ASSERT_TRUE(res);
  2275. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2277. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2279. }
  2280. cli.set_keep_alive(true);
  2281. for (size_t j = 0; j < 100; j++) {
  2282. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2283. ASSERT_TRUE(res);
  2284. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2285. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2286. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2288. }
  2289. }
  2290. }
  2291. TEST(ExceptionTest, AndErrorHandler) {
  2292. Server svr;
  2293. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2294. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2295. });
  2296. svr.set_exception_handler(
  2297. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2298. EXPECT_FALSE(ep == nullptr);
  2299. try {
  2300. std::rethrow_exception(ep);
  2301. } catch (std::exception &e) {
  2302. res.set_content(e.what(), "text/html");
  2303. } catch (...) {}
  2304. res.status = StatusCode::InternalServerError_500;
  2305. });
  2306. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2307. throw std::runtime_error("EXCEPTION");
  2308. });
  2309. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2310. res.set_content("ERROR", "text/html");
  2311. res.status = StatusCode::InternalServerError_500;
  2312. });
  2313. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2314. auto se = detail::scope_exit([&] {
  2315. svr.stop();
  2316. thread.join();
  2317. ASSERT_FALSE(svr.is_running());
  2318. });
  2319. svr.wait_until_ready();
  2320. Client cli(HOST, PORT);
  2321. {
  2322. auto res = cli.Get("/exception");
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2325. EXPECT_EQ("EXCEPTION", res->body);
  2326. }
  2327. {
  2328. auto res = cli.Get("/error");
  2329. ASSERT_TRUE(res);
  2330. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2331. EXPECT_EQ("ERROR", res->body);
  2332. }
  2333. {
  2334. auto res = cli.Get("/invalid");
  2335. ASSERT_TRUE(res);
  2336. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2337. EXPECT_EQ("NOT_FOUND", res->body);
  2338. }
  2339. }
  2340. #endif
  2341. TEST(NoContentTest, ContentLength) {
  2342. Server svr;
  2343. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2344. res.status = StatusCode::NoContent_204;
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. {
  2354. Client cli(HOST, PORT);
  2355. auto res = cli.Get("/hi");
  2356. ASSERT_TRUE(res);
  2357. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2358. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2359. }
  2360. }
  2361. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2362. #ifdef CPPHTTPLIB_SSL_ENABLED
  2363. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2364. ASSERT_TRUE(svr.is_valid());
  2365. #else
  2366. Server svr;
  2367. #endif
  2368. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2369. if (req.path == "/routing_handler") {
  2370. res.set_header("PRE_ROUTING", "on");
  2371. res.set_content("Routing Handler", "text/plain");
  2372. return httplib::Server::HandlerResponse::Handled;
  2373. }
  2374. return httplib::Server::HandlerResponse::Unhandled;
  2375. });
  2376. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2377. res.set_content("Error", "text/html");
  2378. });
  2379. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2380. if (req.path == "/routing_handler") {
  2381. res.set_header("POST_ROUTING", "on");
  2382. }
  2383. });
  2384. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2385. res.set_content("Hello World!\n", "text/plain");
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. {
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. SSLClient cli(HOST, PORT);
  2397. cli.enable_server_certificate_verification(false);
  2398. #else
  2399. Client cli(HOST, PORT);
  2400. #endif
  2401. auto res = cli.Get("/routing_handler");
  2402. ASSERT_TRUE(res);
  2403. EXPECT_EQ(StatusCode::OK_200, res->status);
  2404. EXPECT_EQ("Routing Handler", res->body);
  2405. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2406. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2407. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2408. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2409. }
  2410. {
  2411. #ifdef CPPHTTPLIB_SSL_ENABLED
  2412. SSLClient cli(HOST, PORT);
  2413. cli.enable_server_certificate_verification(false);
  2414. #else
  2415. Client cli(HOST, PORT);
  2416. #endif
  2417. auto res = cli.Get("/hi");
  2418. ASSERT_TRUE(res);
  2419. EXPECT_EQ(StatusCode::OK_200, res->status);
  2420. EXPECT_EQ("Hello World!\n", res->body);
  2421. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2422. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2423. }
  2424. {
  2425. #ifdef CPPHTTPLIB_SSL_ENABLED
  2426. SSLClient cli(HOST, PORT);
  2427. cli.enable_server_certificate_verification(false);
  2428. #else
  2429. Client cli(HOST, PORT);
  2430. #endif
  2431. auto res = cli.Get("/aaa");
  2432. ASSERT_TRUE(res);
  2433. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2434. EXPECT_EQ("Error", res->body);
  2435. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2436. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2437. }
  2438. }
  2439. TEST(RequestHandlerTest, PreRequestHandler) {
  2440. auto route_path = "/user/:user";
  2441. Server svr;
  2442. svr.Get("/hi", [](const Request &, Response &res) {
  2443. res.set_content("hi", "text/plain");
  2444. });
  2445. svr.Get(route_path, [](const Request &req, Response &res) {
  2446. res.set_content(req.path_params.at("user"), "text/plain");
  2447. });
  2448. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2449. if (req.matched_route == route_path) {
  2450. auto user = req.path_params.at("user");
  2451. if (user != "john") {
  2452. res.status = StatusCode::Forbidden_403;
  2453. res.set_content("error", "text/html");
  2454. return Server::HandlerResponse::Handled;
  2455. }
  2456. }
  2457. return Server::HandlerResponse::Unhandled;
  2458. });
  2459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2460. auto se = detail::scope_exit([&] {
  2461. svr.stop();
  2462. thread.join();
  2463. ASSERT_FALSE(svr.is_running());
  2464. });
  2465. svr.wait_until_ready();
  2466. Client cli(HOST, PORT);
  2467. {
  2468. auto res = cli.Get("/hi");
  2469. ASSERT_TRUE(res);
  2470. EXPECT_EQ(StatusCode::OK_200, res->status);
  2471. EXPECT_EQ("hi", res->body);
  2472. }
  2473. {
  2474. auto res = cli.Get("/user/john");
  2475. ASSERT_TRUE(res);
  2476. EXPECT_EQ(StatusCode::OK_200, res->status);
  2477. EXPECT_EQ("john", res->body);
  2478. }
  2479. {
  2480. auto res = cli.Get("/user/invalid-user");
  2481. ASSERT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2483. EXPECT_EQ("error", res->body);
  2484. }
  2485. }
  2486. TEST(InvalidFormatTest, StatusCode) {
  2487. Server svr;
  2488. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2489. res.set_content("Hello World!\n", "text/plain");
  2490. res.status = 9999; // Status should be a three-digit code...
  2491. });
  2492. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2493. auto se = detail::scope_exit([&] {
  2494. svr.stop();
  2495. thread.join();
  2496. ASSERT_FALSE(svr.is_running());
  2497. });
  2498. svr.wait_until_ready();
  2499. {
  2500. Client cli(HOST, PORT);
  2501. auto res = cli.Get("/hi");
  2502. ASSERT_FALSE(res);
  2503. }
  2504. }
  2505. TEST(URLFragmentTest, WithFragment) {
  2506. Server svr;
  2507. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2508. EXPECT_TRUE(req.target == "/hi");
  2509. });
  2510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2511. auto se = detail::scope_exit([&] {
  2512. svr.stop();
  2513. thread.join();
  2514. ASSERT_FALSE(svr.is_running());
  2515. });
  2516. svr.wait_until_ready();
  2517. {
  2518. Client cli(HOST, PORT);
  2519. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2520. EXPECT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. res = cli.Get("/hi%23key1=val1=key2=val2");
  2523. EXPECT_TRUE(res);
  2524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2525. }
  2526. }
  2527. TEST(HeaderWriter, SetHeaderWriter) {
  2528. Server svr;
  2529. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2530. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2531. return detail::write_headers(strm, hdrs);
  2532. });
  2533. svr.Get("/hi", [](const Request &req, Response &res) {
  2534. auto it = req.headers.find("CustomClientHeader");
  2535. EXPECT_TRUE(it != req.headers.end());
  2536. EXPECT_EQ(it->second, "CustomClientValue");
  2537. res.set_content("Hello World!\n", "text/plain");
  2538. });
  2539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2540. auto se = detail::scope_exit([&] {
  2541. svr.stop();
  2542. thread.join();
  2543. ASSERT_FALSE(svr.is_running());
  2544. });
  2545. svr.wait_until_ready();
  2546. {
  2547. Client cli(HOST, PORT);
  2548. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2549. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2550. return detail::write_headers(strm, hdrs);
  2551. });
  2552. auto res = cli.Get("/hi");
  2553. EXPECT_TRUE(res);
  2554. EXPECT_EQ(StatusCode::OK_200, res->status);
  2555. auto it = res->headers.find("CustomServerHeader");
  2556. EXPECT_TRUE(it != res->headers.end());
  2557. EXPECT_EQ(it->second, "CustomServerValue");
  2558. }
  2559. }
  2560. class ServerTest : public ::testing::Test {
  2561. protected:
  2562. ServerTest()
  2563. : cli_(HOST, PORT)
  2564. #ifdef CPPHTTPLIB_SSL_ENABLED
  2565. ,
  2566. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2567. #endif
  2568. {
  2569. #ifdef CPPHTTPLIB_SSL_ENABLED
  2570. cli_.enable_server_certificate_verification(false);
  2571. #endif
  2572. }
  2573. virtual void SetUp() {
  2574. svr_.set_mount_point("/", "./www");
  2575. svr_.set_mount_point("/mount", "./www2");
  2576. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2577. svr_.Get("/hi",
  2578. [&](const Request & /*req*/, Response &res) {
  2579. res.set_content("Hello World!", "text/plain");
  2580. })
  2581. .Get("/file_content",
  2582. [&](const Request & /*req*/, Response &res) {
  2583. res.set_file_content("./www/dir/test.html");
  2584. })
  2585. .Get("/file_content_with_content_type",
  2586. [&](const Request & /*req*/, Response &res) {
  2587. res.set_file_content("./www/file", "text/plain");
  2588. })
  2589. .Get("/invalid_file_content",
  2590. [&](const Request & /*req*/, Response &res) {
  2591. res.set_file_content("./www/dir/invalid_file_path");
  2592. })
  2593. .Get("/http_response_splitting",
  2594. [&](const Request & /*req*/, Response &res) {
  2595. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2596. EXPECT_EQ(0U, res.headers.size());
  2597. EXPECT_FALSE(res.has_header("a"));
  2598. res.set_header("a", "1\nSet-Cookie: a=1");
  2599. EXPECT_EQ(0U, res.headers.size());
  2600. EXPECT_FALSE(res.has_header("a"));
  2601. res.set_header("a", "1\rSet-Cookie: a=1");
  2602. EXPECT_EQ(0U, res.headers.size());
  2603. EXPECT_FALSE(res.has_header("a"));
  2604. res.set_header("a\r\nb", "0");
  2605. EXPECT_EQ(0U, res.headers.size());
  2606. EXPECT_FALSE(res.has_header("a"));
  2607. res.set_header("a\rb", "0");
  2608. EXPECT_EQ(0U, res.headers.size());
  2609. EXPECT_FALSE(res.has_header("a"));
  2610. res.set_header("a\nb", "0");
  2611. EXPECT_EQ(0U, res.headers.size());
  2612. EXPECT_FALSE(res.has_header("a"));
  2613. res.set_redirect("1\r\nSet-Cookie: a=1");
  2614. EXPECT_EQ(0U, res.headers.size());
  2615. EXPECT_FALSE(res.has_header("Location"));
  2616. })
  2617. .Get("/slow",
  2618. [&](const Request & /*req*/, Response &res) {
  2619. std::this_thread::sleep_for(std::chrono::seconds(2));
  2620. res.set_content("slow", "text/plain");
  2621. })
  2622. #if 0
  2623. .Post("/slowpost",
  2624. [&](const Request & /*req*/, Response &res) {
  2625. std::this_thread::sleep_for(std::chrono::seconds(2));
  2626. res.set_content("slow", "text/plain");
  2627. })
  2628. #endif
  2629. .Get("/remote_addr",
  2630. [&](const Request &req, Response &res) {
  2631. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2632. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2633. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2634. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2635. res.set_content(req.remote_addr, "text/plain");
  2636. })
  2637. .Get("/local_addr",
  2638. [&](const Request &req, Response &res) {
  2639. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2640. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2641. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2642. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2643. auto local_addr = req.local_addr;
  2644. auto local_port = std::to_string(req.local_port);
  2645. res.set_content(local_addr.append(":").append(local_port),
  2646. "text/plain");
  2647. })
  2648. .Get("/endwith%",
  2649. [&](const Request & /*req*/, Response &res) {
  2650. res.set_content("Hello World!", "text/plain");
  2651. })
  2652. .Get("/a\\+\\+b",
  2653. [&](const Request &req, Response &res) {
  2654. ASSERT_TRUE(req.has_param("a +b"));
  2655. auto val = req.get_param_value("a +b");
  2656. res.set_content(val, "text/plain");
  2657. })
  2658. .Get("/", [&](const Request & /*req*/,
  2659. Response &res) { res.set_redirect("/hi"); })
  2660. .Post("/1",
  2661. [](const Request & /*req*/, Response &res) {
  2662. res.set_redirect("/2", StatusCode::SeeOther_303);
  2663. })
  2664. .Get("/2",
  2665. [](const Request & /*req*/, Response &res) {
  2666. res.set_content("redirected.", "text/plain");
  2667. res.status = StatusCode::OK_200;
  2668. })
  2669. .Post("/person",
  2670. [&](const Request &req, Response &res) {
  2671. if (req.has_param("name") && req.has_param("note")) {
  2672. persons_[req.get_param_value("name")] =
  2673. req.get_param_value("note");
  2674. } else {
  2675. res.status = StatusCode::BadRequest_400;
  2676. }
  2677. })
  2678. .Put("/person",
  2679. [&](const Request &req, Response &res) {
  2680. if (req.has_param("name") && req.has_param("note")) {
  2681. persons_[req.get_param_value("name")] =
  2682. req.get_param_value("note");
  2683. } else {
  2684. res.status = StatusCode::BadRequest_400;
  2685. }
  2686. })
  2687. .Get("/person/(.*)",
  2688. [&](const Request &req, Response &res) {
  2689. string name = req.matches[1];
  2690. if (persons_.find(name) != persons_.end()) {
  2691. auto note = persons_[name];
  2692. res.set_content(note, "text/plain");
  2693. } else {
  2694. res.status = StatusCode::NotFound_404;
  2695. }
  2696. })
  2697. .Delete("/person",
  2698. [&](const Request &req, Response &res) {
  2699. if (req.has_param("name")) {
  2700. string name = req.get_param_value("name");
  2701. if (persons_.find(name) != persons_.end()) {
  2702. persons_.erase(name);
  2703. res.set_content("DELETED", "text/plain");
  2704. } else {
  2705. res.status = StatusCode::NotFound_404;
  2706. }
  2707. } else {
  2708. res.status = StatusCode::BadRequest_400;
  2709. }
  2710. })
  2711. .Post("/x-www-form-urlencoded-json",
  2712. [&](const Request &req, Response &res) {
  2713. auto json = req.get_param_value("json");
  2714. ASSERT_EQ(JSON_DATA, json);
  2715. res.set_content(json, "appliation/json");
  2716. res.status = StatusCode::OK_200;
  2717. })
  2718. .Get("/streamed-chunked",
  2719. [&](const Request & /*req*/, Response &res) {
  2720. res.set_chunked_content_provider(
  2721. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2722. sink.os << "123";
  2723. sink.os << "456";
  2724. sink.os << "789";
  2725. sink.done();
  2726. return true;
  2727. });
  2728. })
  2729. .Get("/streamed-chunked-with-prohibited-trailer",
  2730. [&](const Request & /*req*/, Response &res) {
  2731. auto i = new int(0);
  2732. // Declare both a prohibited trailer (Content-Length) and an
  2733. // allowed one
  2734. res.set_header("Trailer", "Content-Length, X-Allowed");
  2735. res.set_chunked_content_provider(
  2736. "text/plain",
  2737. [i](size_t /*offset*/, DataSink &sink) {
  2738. switch (*i) {
  2739. case 0: sink.os << "123"; break;
  2740. case 1: sink.os << "456"; break;
  2741. case 2: sink.os << "789"; break;
  2742. case 3: {
  2743. sink.done_with_trailer(
  2744. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2745. } break;
  2746. }
  2747. (*i)++;
  2748. return true;
  2749. },
  2750. [i](bool success) {
  2751. EXPECT_TRUE(success);
  2752. delete i;
  2753. });
  2754. })
  2755. .Get("/streamed-chunked2",
  2756. [&](const Request & /*req*/, Response &res) {
  2757. auto i = new int(0);
  2758. res.set_chunked_content_provider(
  2759. "text/plain",
  2760. [i](size_t /*offset*/, DataSink &sink) {
  2761. switch (*i) {
  2762. case 0: sink.os << "123"; break;
  2763. case 1: sink.os << "456"; break;
  2764. case 2: sink.os << "789"; break;
  2765. case 3: sink.done(); break;
  2766. }
  2767. (*i)++;
  2768. return true;
  2769. },
  2770. [i](bool success) {
  2771. EXPECT_TRUE(success);
  2772. delete i;
  2773. });
  2774. })
  2775. .Get("/streamed-chunked-with-trailer",
  2776. [&](const Request & /*req*/, Response &res) {
  2777. auto i = new int(0);
  2778. res.set_header("Trailer", "Dummy1, Dummy2");
  2779. res.set_chunked_content_provider(
  2780. "text/plain",
  2781. [i](size_t /*offset*/, DataSink &sink) {
  2782. switch (*i) {
  2783. case 0: sink.os << "123"; break;
  2784. case 1: sink.os << "456"; break;
  2785. case 2: sink.os << "789"; break;
  2786. case 3: {
  2787. sink.done_with_trailer(
  2788. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2789. } break;
  2790. }
  2791. (*i)++;
  2792. return true;
  2793. },
  2794. [i](bool success) {
  2795. EXPECT_TRUE(success);
  2796. delete i;
  2797. });
  2798. })
  2799. .Get("/streamed",
  2800. [&](const Request & /*req*/, Response &res) {
  2801. res.set_content_provider(
  2802. 6, "text/plain",
  2803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2804. sink.os << (offset < 3 ? "a" : "b");
  2805. return true;
  2806. });
  2807. })
  2808. .Get("/streamed-with-range",
  2809. [&](const Request &req, Response &res) {
  2810. auto data = new std::string("abcdefg");
  2811. res.set_content_provider(
  2812. data->size(), "text/plain",
  2813. [data](size_t offset, size_t length, DataSink &sink) {
  2814. size_t DATA_CHUNK_SIZE = 4;
  2815. const auto &d = *data;
  2816. auto out_len =
  2817. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2818. auto ret =
  2819. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2820. EXPECT_TRUE(ret);
  2821. return true;
  2822. },
  2823. [data, &req](bool success) {
  2824. EXPECT_EQ(success, !req.has_param("error"));
  2825. delete data;
  2826. });
  2827. })
  2828. .Get("/streamed-cancel",
  2829. [&](const Request & /*req*/, Response &res) {
  2830. res.set_content_provider(
  2831. size_t(-1), "text/plain",
  2832. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2833. sink.os << "data_chunk";
  2834. return true;
  2835. });
  2836. })
  2837. .Get("/regex-with-delimiter",
  2838. [&](const Request &req, Response & /*res*/) {
  2839. ASSERT_TRUE(req.has_param("key"));
  2840. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2841. })
  2842. .Get("/with-range",
  2843. [&](const Request & /*req*/, Response &res) {
  2844. res.set_content("abcdefg", "text/plain");
  2845. })
  2846. .Get("/test-start-time",
  2847. [&](const Request &req, Response & /*res*/) {
  2848. EXPECT_NE(req.start_time_,
  2849. std::chrono::steady_clock::time_point::min());
  2850. })
  2851. .Get("/with-range-customized-response",
  2852. [&](const Request & /*req*/, Response &res) {
  2853. res.status = StatusCode::BadRequest_400;
  2854. res.set_content(JSON_DATA, "application/json");
  2855. })
  2856. .Post("/chunked",
  2857. [&](const Request &req, Response & /*res*/) {
  2858. EXPECT_EQ(req.body, "dechunked post body");
  2859. })
  2860. .Post("/large-chunked",
  2861. [&](const Request &req, Response & /*res*/) {
  2862. std::string expected(6 * 30 * 1024u, 'a');
  2863. EXPECT_EQ(req.body, expected);
  2864. })
  2865. .Post("/multipart",
  2866. [&](const Request &req, Response & /*res*/) {
  2867. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2868. req.form.get_field_count("text2") +
  2869. req.form.get_field_count("file3") +
  2870. req.form.get_field_count("file4"));
  2871. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2872. req.form.get_file_count("file2"));
  2873. ASSERT_TRUE(!req.form.has_file("???"));
  2874. ASSERT_TRUE(!req.form.has_field("???"));
  2875. ASSERT_TRUE(req.body.empty());
  2876. {
  2877. const auto &text = req.form.get_field("text1");
  2878. EXPECT_EQ("text default", text);
  2879. }
  2880. {
  2881. const auto &text = req.form.get_field("text2");
  2882. EXPECT_EQ("aωb", text);
  2883. }
  2884. {
  2885. const auto &file = req.form.get_file("file1");
  2886. EXPECT_EQ("hello.txt", file.filename);
  2887. EXPECT_EQ("text/plain", file.content_type);
  2888. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2889. }
  2890. {
  2891. const auto &file = req.form.get_file("file2");
  2892. EXPECT_EQ("world.json", file.filename);
  2893. EXPECT_EQ("application/json", file.content_type);
  2894. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2895. }
  2896. {
  2897. const auto &text = req.form.get_field("file3");
  2898. EXPECT_EQ(0u, text.size());
  2899. }
  2900. {
  2901. const auto &text = req.form.get_field("file4");
  2902. EXPECT_EQ(0u, text.size());
  2903. }
  2904. })
  2905. .Post("/multipart/multi_file_values",
  2906. [&](const Request &req, Response & /*res*/) {
  2907. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2908. req.form.get_field_count("multi_text1"));
  2909. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2910. ASSERT_TRUE(!req.form.has_file("???"));
  2911. ASSERT_TRUE(!req.form.has_field("???"));
  2912. ASSERT_TRUE(req.body.empty());
  2913. {
  2914. const auto &text = req.form.get_field("text");
  2915. EXPECT_EQ("default text", text);
  2916. }
  2917. {
  2918. const auto &text1_values = req.form.get_fields("multi_text1");
  2919. EXPECT_EQ(2u, text1_values.size());
  2920. EXPECT_EQ("aaaaa", text1_values[0]);
  2921. EXPECT_EQ("bbbbb", text1_values[1]);
  2922. }
  2923. {
  2924. const auto &file1_values = req.form.get_files("multi_file1");
  2925. EXPECT_EQ(2u, file1_values.size());
  2926. auto file1 = file1_values[0];
  2927. EXPECT_EQ(file1.filename, "hello.txt");
  2928. EXPECT_EQ(file1.content_type, "text/plain");
  2929. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2930. auto file2 = file1_values[1];
  2931. EXPECT_EQ(file2.filename, "world.json");
  2932. EXPECT_EQ(file2.content_type, "application/json");
  2933. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2934. }
  2935. })
  2936. .Post("/empty",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "");
  2939. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2940. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2941. res.set_content("empty", "text/plain");
  2942. })
  2943. .Post("/empty-no-content-type",
  2944. [&](const Request &req, Response &res) {
  2945. EXPECT_EQ(req.body, "");
  2946. EXPECT_FALSE(req.has_header("Content-Type"));
  2947. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2948. res.set_content("empty-no-content-type", "text/plain");
  2949. })
  2950. .Post("/path-only",
  2951. [&](const Request &req, Response &res) {
  2952. EXPECT_EQ(req.body, "");
  2953. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2954. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2955. res.set_content("path-only", "text/plain");
  2956. })
  2957. .Post("/path-headers-only",
  2958. [&](const Request &req, Response &res) {
  2959. EXPECT_EQ(req.body, "");
  2960. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2961. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2962. EXPECT_EQ("world", req.get_header_value("hello"));
  2963. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2964. res.set_content("path-headers-only", "text/plain");
  2965. })
  2966. .Post("/post-large",
  2967. [&](const Request &req, Response &res) {
  2968. EXPECT_EQ(req.body, LARGE_DATA);
  2969. res.set_content(req.body, "text/plain");
  2970. })
  2971. .Post("/post-loopback",
  2972. [&](const Request &, Response &res,
  2973. ContentReader const &content_reader) {
  2974. std::string body;
  2975. content_reader([&](const char *data, size_t data_length) {
  2976. body.append(data, data_length);
  2977. return true;
  2978. });
  2979. res.set_content(body, "text/plain");
  2980. })
  2981. .Put("/put-loopback",
  2982. [&](const Request &, Response &res,
  2983. ContentReader const &content_reader) {
  2984. std::string body;
  2985. content_reader([&](const char *data, size_t data_length) {
  2986. body.append(data, data_length);
  2987. return true;
  2988. });
  2989. res.set_content(body, "text/plain");
  2990. })
  2991. .Patch("/patch-loopback",
  2992. [&](const Request &, Response &res,
  2993. ContentReader const &content_reader) {
  2994. std::string body;
  2995. content_reader([&](const char *data, size_t data_length) {
  2996. body.append(data, data_length);
  2997. return true;
  2998. });
  2999. res.set_content(body, "text/plain");
  3000. })
  3001. .Put("/empty-no-content-type",
  3002. [&](const Request &req, Response &res) {
  3003. EXPECT_EQ(req.body, "");
  3004. EXPECT_FALSE(req.has_header("Content-Type"));
  3005. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  3006. res.set_content("empty-no-content-type", "text/plain");
  3007. })
  3008. .Put("/put",
  3009. [&](const Request &req, Response &res) {
  3010. EXPECT_EQ(req.body, "PUT");
  3011. res.set_content(req.body, "text/plain");
  3012. })
  3013. .Put("/put-large",
  3014. [&](const Request &req, Response &res) {
  3015. EXPECT_EQ(req.body, LARGE_DATA);
  3016. res.set_content(req.body, "text/plain");
  3017. })
  3018. .Patch("/patch",
  3019. [&](const Request &req, Response &res) {
  3020. EXPECT_EQ(req.body, "PATCH");
  3021. res.set_content(req.body, "text/plain");
  3022. })
  3023. .Delete("/delete",
  3024. [&](const Request & /*req*/, Response &res) {
  3025. res.set_content("DELETE", "text/plain");
  3026. })
  3027. .Delete("/delete-body",
  3028. [&](const Request &req, Response &res) {
  3029. EXPECT_EQ(req.body, "content");
  3030. res.set_content(req.body, "text/plain");
  3031. })
  3032. .Options(R"(\*)",
  3033. [&](const Request & /*req*/, Response &res) {
  3034. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  3035. })
  3036. .Get("/request-target",
  3037. [&](const Request &req, Response & /*res*/) {
  3038. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  3039. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  3040. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  3041. })
  3042. .Get("/long-query-value",
  3043. [&](const Request &req, Response & /*res*/) {
  3044. EXPECT_EQ(LONG_QUERY_URL, req.target);
  3045. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  3046. })
  3047. .Get("/too-long-query-value",
  3048. [&](const Request &req, Response & /*res*/) {
  3049. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  3050. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  3051. })
  3052. .Get("/array-param",
  3053. [&](const Request &req, Response & /*res*/) {
  3054. EXPECT_EQ(3u, req.get_param_value_count("array"));
  3055. EXPECT_EQ("value1", req.get_param_value("array", 0));
  3056. EXPECT_EQ("value2", req.get_param_value("array", 1));
  3057. EXPECT_EQ("value3", req.get_param_value("array", 2));
  3058. })
  3059. .Post("/validate-no-multiple-headers",
  3060. [&](const Request &req, Response & /*res*/) {
  3061. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  3062. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  3063. })
  3064. .Post("/content_receiver",
  3065. [&](const Request &req, Response &res,
  3066. const ContentReader &content_reader) {
  3067. if (req.is_multipart_form_data()) {
  3068. std::vector<FormData> items;
  3069. content_reader(
  3070. [&](const FormData &file) {
  3071. items.push_back(file);
  3072. return true;
  3073. },
  3074. [&](const char *data, size_t data_length) {
  3075. items.back().content.append(data, data_length);
  3076. return true;
  3077. });
  3078. EXPECT_EQ(5u, items.size());
  3079. {
  3080. const auto &file = get_file_value(items, "text1");
  3081. EXPECT_TRUE(file.filename.empty());
  3082. EXPECT_EQ("text default", file.content);
  3083. }
  3084. {
  3085. const auto &file = get_file_value(items, "text2");
  3086. EXPECT_TRUE(file.filename.empty());
  3087. EXPECT_EQ("aωb", file.content);
  3088. }
  3089. {
  3090. const auto &file = get_file_value(items, "file1");
  3091. EXPECT_EQ("hello.txt", file.filename);
  3092. EXPECT_EQ("text/plain", file.content_type);
  3093. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3094. }
  3095. {
  3096. const auto &file = get_file_value(items, "file2");
  3097. EXPECT_EQ("world.json", file.filename);
  3098. EXPECT_EQ("application/json", file.content_type);
  3099. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3100. }
  3101. {
  3102. const auto &file = get_file_value(items, "file3");
  3103. EXPECT_TRUE(file.filename.empty());
  3104. EXPECT_EQ("application/octet-stream", file.content_type);
  3105. EXPECT_EQ(0u, file.content.size());
  3106. }
  3107. } else {
  3108. std::string body;
  3109. content_reader([&](const char *data, size_t data_length) {
  3110. EXPECT_EQ(7U, data_length);
  3111. body.append(data, data_length);
  3112. return true;
  3113. });
  3114. EXPECT_EQ(body, "content");
  3115. res.set_content(body, "text/plain");
  3116. }
  3117. })
  3118. .Put("/content_receiver",
  3119. [&](const Request & /*req*/, Response &res,
  3120. const ContentReader &content_reader) {
  3121. std::string body;
  3122. content_reader([&](const char *data, size_t data_length) {
  3123. body.append(data, data_length);
  3124. return true;
  3125. });
  3126. EXPECT_EQ(body, "content");
  3127. res.set_content(body, "text/plain");
  3128. })
  3129. .Patch("/content_receiver",
  3130. [&](const Request & /*req*/, Response &res,
  3131. const ContentReader &content_reader) {
  3132. std::string body;
  3133. content_reader([&](const char *data, size_t data_length) {
  3134. body.append(data, data_length);
  3135. return true;
  3136. });
  3137. EXPECT_EQ(body, "content");
  3138. res.set_content(body, "text/plain");
  3139. })
  3140. .Post("/query-string-and-body",
  3141. [&](const Request &req, Response & /*res*/) {
  3142. ASSERT_TRUE(req.has_param("key"));
  3143. EXPECT_EQ(req.get_param_value("key"), "value");
  3144. EXPECT_EQ(req.body, "content");
  3145. })
  3146. .Get("/last-request",
  3147. [&](const Request &req, Response & /*res*/) {
  3148. EXPECT_EQ("close", req.get_header_value("Connection"));
  3149. })
  3150. .Get(R"(/redirect/(\d+))",
  3151. [&](const Request &req, Response &res) {
  3152. auto num = std::stoi(req.matches[1]) + 1;
  3153. std::string url = "/redirect/" + std::to_string(num);
  3154. res.set_redirect(url);
  3155. })
  3156. .Post("/binary",
  3157. [&](const Request &req, Response &res) {
  3158. EXPECT_EQ(4U, req.body.size());
  3159. EXPECT_EQ("application/octet-stream",
  3160. req.get_header_value("Content-Type"));
  3161. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3162. res.set_content(req.body, "application/octet-stream");
  3163. })
  3164. .Put("/binary",
  3165. [&](const Request &req, Response &res) {
  3166. EXPECT_EQ(4U, req.body.size());
  3167. EXPECT_EQ("application/octet-stream",
  3168. req.get_header_value("Content-Type"));
  3169. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3170. res.set_content(req.body, "application/octet-stream");
  3171. })
  3172. .Patch("/binary",
  3173. [&](const Request &req, Response &res) {
  3174. EXPECT_EQ(4U, req.body.size());
  3175. EXPECT_EQ("application/octet-stream",
  3176. req.get_header_value("Content-Type"));
  3177. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3178. res.set_content(req.body, "application/octet-stream");
  3179. })
  3180. .Delete("/binary",
  3181. [&](const Request &req, Response &res) {
  3182. EXPECT_EQ(4U, req.body.size());
  3183. EXPECT_EQ("application/octet-stream",
  3184. req.get_header_value("Content-Type"));
  3185. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3186. res.set_content(req.body, "application/octet-stream");
  3187. })
  3188. .Get("/issue1772",
  3189. [&](const Request & /*req*/, Response &res) {
  3190. res.status = 401;
  3191. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3192. })
  3193. .Delete("/issue609",
  3194. [](const httplib::Request &, httplib::Response &res,
  3195. const httplib::ContentReader &) {
  3196. res.set_content("ok", "text/plain");
  3197. })
  3198. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3199. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3200. .Get("/compress",
  3201. [&](const Request & /*req*/, Response &res) {
  3202. res.set_content(
  3203. "12345678901234567890123456789012345678901234567890123456789"
  3204. "01234567890123456789012345678901234567890",
  3205. "text/plain");
  3206. })
  3207. .Get("/nocompress",
  3208. [&](const Request & /*req*/, Response &res) {
  3209. res.set_content(
  3210. "12345678901234567890123456789012345678901234567890123456789"
  3211. "01234567890123456789012345678901234567890",
  3212. "application/octet-stream");
  3213. })
  3214. .Post("/compress-multipart",
  3215. [&](const Request &req, Response & /*res*/) {
  3216. EXPECT_EQ(2u, req.form.fields.size());
  3217. ASSERT_TRUE(!req.form.has_field("???"));
  3218. {
  3219. const auto &text = req.form.get_field("key1");
  3220. EXPECT_EQ("test", text);
  3221. }
  3222. {
  3223. const auto &text = req.form.get_field("key2");
  3224. EXPECT_EQ("--abcdefg123", text);
  3225. }
  3226. })
  3227. #endif
  3228. ;
  3229. persons_["john"] = "programmer";
  3230. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3231. svr_.wait_until_ready();
  3232. }
  3233. virtual void TearDown() {
  3234. svr_.stop();
  3235. if (!request_threads_.empty()) {
  3236. std::this_thread::sleep_for(std::chrono::seconds(1));
  3237. for (auto &t : request_threads_) {
  3238. t.join();
  3239. }
  3240. }
  3241. t_.join();
  3242. }
  3243. map<string, string> persons_;
  3244. #ifdef CPPHTTPLIB_SSL_ENABLED
  3245. SSLClient cli_;
  3246. SSLServer svr_;
  3247. #else
  3248. Client cli_;
  3249. Server svr_;
  3250. #endif
  3251. thread t_;
  3252. std::vector<thread> request_threads_;
  3253. };
  3254. TEST_F(ServerTest, GetMethod200) {
  3255. auto res = cli_.Get("/hi");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ("HTTP/1.1", res->version);
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("OK", res->reason);
  3260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3261. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. TEST_F(ServerTest, GetEmptyFile) {
  3265. auto res = cli_.Get("/empty_file");
  3266. ASSERT_TRUE(res);
  3267. EXPECT_EQ(StatusCode::OK_200, res->status);
  3268. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3269. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3270. EXPECT_EQ("", res->body);
  3271. }
  3272. TEST_F(ServerTest, GetFileContent) {
  3273. auto res = cli_.Get("/file_content");
  3274. ASSERT_TRUE(res);
  3275. EXPECT_EQ(StatusCode::OK_200, res->status);
  3276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3277. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3278. EXPECT_EQ("test.html", res->body);
  3279. }
  3280. TEST_F(ServerTest, GetFileContentWithRange) {
  3281. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3282. ASSERT_TRUE(res);
  3283. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3284. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3285. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3286. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3287. EXPECT_EQ("est", res->body);
  3288. }
  3289. TEST_F(ServerTest, GetFileContentWithContentType) {
  3290. auto res = cli_.Get("/file_content_with_content_type");
  3291. ASSERT_TRUE(res);
  3292. EXPECT_EQ(StatusCode::OK_200, res->status);
  3293. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3294. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3295. EXPECT_EQ("file\n", res->body);
  3296. }
  3297. TEST_F(ServerTest, GetInvalidFileContent) {
  3298. auto res = cli_.Get("/invalid_file_content");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3301. }
  3302. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3303. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3304. ASSERT_TRUE(res);
  3305. EXPECT_EQ("HTTP/1.1", res->version);
  3306. EXPECT_EQ(StatusCode::OK_200, res->status);
  3307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3308. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3309. EXPECT_EQ("Hello World!", res->body);
  3310. }
  3311. TEST_F(ServerTest, GetMethod302) {
  3312. auto res = cli_.Get("/");
  3313. ASSERT_TRUE(res);
  3314. EXPECT_EQ(StatusCode::Found_302, res->status);
  3315. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3316. }
  3317. TEST_F(ServerTest, GetMethod302Redirect) {
  3318. cli_.set_follow_location(true);
  3319. auto res = cli_.Get("/");
  3320. ASSERT_TRUE(res);
  3321. EXPECT_EQ(StatusCode::OK_200, res->status);
  3322. EXPECT_EQ("Hello World!", res->body);
  3323. EXPECT_EQ("/hi", res->location);
  3324. }
  3325. TEST_F(ServerTest, GetMethod404) {
  3326. auto res = cli_.Get("/invalid");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3329. }
  3330. TEST_F(ServerTest, HeadMethod200) {
  3331. auto res = cli_.Head("/hi");
  3332. ASSERT_TRUE(res);
  3333. EXPECT_EQ(StatusCode::OK_200, res->status);
  3334. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3335. EXPECT_TRUE(res->body.empty());
  3336. }
  3337. TEST_F(ServerTest, HeadMethod200Static) {
  3338. auto res = cli_.Head("/mount/dir/index.html");
  3339. ASSERT_TRUE(res);
  3340. EXPECT_EQ(StatusCode::OK_200, res->status);
  3341. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3342. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3343. EXPECT_TRUE(res->body.empty());
  3344. }
  3345. TEST_F(ServerTest, HeadMethod404) {
  3346. auto res = cli_.Head("/invalid");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3349. EXPECT_TRUE(res->body.empty());
  3350. }
  3351. TEST_F(ServerTest, GetMethodPersonJohn) {
  3352. auto res = cli_.Get("/person/john");
  3353. ASSERT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::OK_200, res->status);
  3355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3356. EXPECT_EQ("programmer", res->body);
  3357. }
  3358. TEST_F(ServerTest, PostMethod1) {
  3359. auto res = cli_.Get("/person/john1");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3362. res = cli_.Post("/person", "name=john1&note=coder",
  3363. "application/x-www-form-urlencoded");
  3364. ASSERT_TRUE(res);
  3365. ASSERT_EQ(StatusCode::OK_200, res->status);
  3366. res = cli_.Get("/person/john1");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::OK_200, res->status);
  3369. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3370. ASSERT_EQ("coder", res->body);
  3371. }
  3372. TEST_F(ServerTest, PostMethod2) {
  3373. auto res = cli_.Get("/person/john2");
  3374. ASSERT_TRUE(res);
  3375. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3376. Params params;
  3377. params.emplace("name", "john2");
  3378. params.emplace("note", "coder");
  3379. res = cli_.Post("/person", params);
  3380. ASSERT_TRUE(res);
  3381. ASSERT_EQ(StatusCode::OK_200, res->status);
  3382. res = cli_.Get("/person/john2");
  3383. ASSERT_TRUE(res);
  3384. ASSERT_EQ(StatusCode::OK_200, res->status);
  3385. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3386. ASSERT_EQ("coder", res->body);
  3387. }
  3388. TEST_F(ServerTest, PutMethod3) {
  3389. auto res = cli_.Get("/person/john3");
  3390. ASSERT_TRUE(res);
  3391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3392. Params params;
  3393. params.emplace("name", "john3");
  3394. params.emplace("note", "coder");
  3395. res = cli_.Put("/person", params);
  3396. ASSERT_TRUE(res);
  3397. ASSERT_EQ(StatusCode::OK_200, res->status);
  3398. res = cli_.Get("/person/john3");
  3399. ASSERT_TRUE(res);
  3400. ASSERT_EQ(StatusCode::OK_200, res->status);
  3401. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3402. ASSERT_EQ("coder", res->body);
  3403. }
  3404. TEST_F(ServerTest, DeleteMethod1) {
  3405. auto res = cli_.Get("/person/john4");
  3406. ASSERT_TRUE(res);
  3407. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3408. Params params;
  3409. params.emplace("name", "john4");
  3410. params.emplace("note", "coder");
  3411. res = cli_.Post("/person", params);
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. res = cli_.Get("/person/john4");
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3418. ASSERT_EQ("coder", res->body);
  3419. Params delete_params;
  3420. delete_params.emplace("name", "john4");
  3421. res = cli_.Delete("/person", delete_params);
  3422. ASSERT_TRUE(res);
  3423. ASSERT_EQ(StatusCode::OK_200, res->status);
  3424. ASSERT_EQ("DELETED", res->body);
  3425. res = cli_.Get("/person/john4");
  3426. ASSERT_TRUE(res);
  3427. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3428. }
  3429. TEST_F(ServerTest, DeleteMethod2) {
  3430. auto res = cli_.Get("/person/john5");
  3431. ASSERT_TRUE(res);
  3432. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3433. Params params;
  3434. params.emplace("name", "john5");
  3435. params.emplace("note", "developer");
  3436. res = cli_.Post("/person", params);
  3437. ASSERT_TRUE(res);
  3438. ASSERT_EQ(StatusCode::OK_200, res->status);
  3439. res = cli_.Get("/person/john5");
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3443. ASSERT_EQ("developer", res->body);
  3444. Params delete_params;
  3445. delete_params.emplace("name", "john5");
  3446. Headers headers;
  3447. headers.emplace("Custom-Header", "test-value");
  3448. res = cli_.Delete("/person", headers, delete_params);
  3449. ASSERT_TRUE(res);
  3450. ASSERT_EQ(StatusCode::OK_200, res->status);
  3451. ASSERT_EQ("DELETED", res->body);
  3452. res = cli_.Get("/person/john5");
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3455. }
  3456. TEST_F(ServerTest, DeleteMethod3) {
  3457. auto res = cli_.Get("/person/john6");
  3458. ASSERT_TRUE(res);
  3459. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3460. Params params;
  3461. params.emplace("name", "john6");
  3462. params.emplace("note", "tester");
  3463. res = cli_.Post("/person", params);
  3464. ASSERT_TRUE(res);
  3465. ASSERT_EQ(StatusCode::OK_200, res->status);
  3466. res = cli_.Get("/person/john6");
  3467. ASSERT_TRUE(res);
  3468. ASSERT_EQ(StatusCode::OK_200, res->status);
  3469. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3470. ASSERT_EQ("tester", res->body);
  3471. Params delete_params;
  3472. delete_params.emplace("name", "john6");
  3473. Headers headers;
  3474. headers.emplace("Custom-Header", "test-value");
  3475. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3476. ASSERT_TRUE(res);
  3477. ASSERT_EQ(StatusCode::OK_200, res->status);
  3478. ASSERT_EQ("DELETED", res->body);
  3479. res = cli_.Get("/person/john6");
  3480. ASSERT_TRUE(res);
  3481. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3482. }
  3483. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3484. Params params;
  3485. params.emplace("json", JSON_DATA);
  3486. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3487. ASSERT_TRUE(res);
  3488. ASSERT_EQ(StatusCode::OK_200, res->status);
  3489. ASSERT_EQ(JSON_DATA, res->body);
  3490. }
  3491. TEST_F(ServerTest, PostEmptyContent) {
  3492. auto res = cli_.Post("/empty", "", "text/plain");
  3493. ASSERT_TRUE(res);
  3494. ASSERT_EQ(StatusCode::OK_200, res->status);
  3495. ASSERT_EQ("empty", res->body);
  3496. }
  3497. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3498. auto res = cli_.Post("/empty-no-content-type");
  3499. ASSERT_TRUE(res);
  3500. ASSERT_EQ(StatusCode::OK_200, res->status);
  3501. ASSERT_EQ("empty-no-content-type", res->body);
  3502. }
  3503. TEST_F(ServerTest, PostPathOnly) {
  3504. auto res = cli_.Post("/path-only");
  3505. ASSERT_TRUE(res);
  3506. ASSERT_EQ(StatusCode::OK_200, res->status);
  3507. ASSERT_EQ("path-only", res->body);
  3508. }
  3509. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3510. auto res = cli_.Post("/path-headers-only",
  3511. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3512. ASSERT_TRUE(res);
  3513. ASSERT_EQ(StatusCode::OK_200, res->status);
  3514. ASSERT_EQ("path-headers-only", res->body);
  3515. }
  3516. TEST_F(ServerTest, PostLarge) {
  3517. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3518. ASSERT_TRUE(res);
  3519. ASSERT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ(LARGE_DATA, res->body);
  3521. }
  3522. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3523. auto res = cli_.Put("/empty-no-content-type");
  3524. ASSERT_TRUE(res);
  3525. ASSERT_EQ(StatusCode::OK_200, res->status);
  3526. ASSERT_EQ("empty-no-content-type", res->body);
  3527. }
  3528. TEST_F(ServerTest, GetMethodDir) {
  3529. auto res = cli_.Get("/dir/");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3533. auto body = R"(<html>
  3534. <head>
  3535. </head>
  3536. <body>
  3537. <a href="/dir/test.html">Test</a>
  3538. <a href="/hi">hi</a>
  3539. </body>
  3540. </html>
  3541. )";
  3542. EXPECT_EQ(body, res->body);
  3543. }
  3544. TEST_F(ServerTest, GetMethodDirTest) {
  3545. auto res = cli_.Get("/dir/test.html");
  3546. ASSERT_TRUE(res);
  3547. EXPECT_EQ(StatusCode::OK_200, res->status);
  3548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3549. EXPECT_EQ("test.html", res->body);
  3550. }
  3551. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3552. auto res = cli_.Get("/dir/../dir/test.html");
  3553. ASSERT_TRUE(res);
  3554. EXPECT_EQ(StatusCode::OK_200, res->status);
  3555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3556. EXPECT_EQ("test.html", res->body);
  3557. }
  3558. TEST_F(ServerTest, GetMethodInvalidPath) {
  3559. auto res = cli_.Get("/dir/../test.html");
  3560. ASSERT_TRUE(res);
  3561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3562. }
  3563. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3564. auto res = cli_.Get("/../www/dir/test.html");
  3565. ASSERT_TRUE(res);
  3566. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3567. }
  3568. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3569. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3570. ASSERT_TRUE(res);
  3571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3572. }
  3573. TEST_F(ServerTest, GetMethodDirMountTest) {
  3574. auto res = cli_.Get("/mount/dir/test.html");
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3578. EXPECT_EQ("test.html", res->body);
  3579. }
  3580. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3581. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::OK_200, res->status);
  3584. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3585. EXPECT_EQ("test.html", res->body);
  3586. }
  3587. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3588. auto res = cli_.Get("/mount/dir/../test.html");
  3589. ASSERT_TRUE(res);
  3590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3591. }
  3592. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3593. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3596. }
  3597. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3598. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3599. ASSERT_TRUE(res);
  3600. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3601. }
  3602. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3603. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3604. ASSERT_TRUE(res);
  3605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3606. }
  3607. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3608. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3609. ASSERT_TRUE(res);
  3610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3611. }
  3612. TEST_F(ServerTest, PostMethod303) {
  3613. auto res = cli_.Post("/1", "body", "text/plain");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3616. EXPECT_EQ("/2", res->get_header_value("Location"));
  3617. }
  3618. TEST_F(ServerTest, PostMethod303Redirect) {
  3619. cli_.set_follow_location(true);
  3620. auto res = cli_.Post("/1", "body", "text/plain");
  3621. ASSERT_TRUE(res);
  3622. EXPECT_EQ(StatusCode::OK_200, res->status);
  3623. EXPECT_EQ("redirected.", res->body);
  3624. EXPECT_EQ("/2", res->location);
  3625. }
  3626. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3627. auto res = cli_.Get("/dir/test.abcde");
  3628. ASSERT_TRUE(res);
  3629. EXPECT_EQ(StatusCode::OK_200, res->status);
  3630. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3631. EXPECT_EQ("abcde", res->body);
  3632. }
  3633. TEST_F(ServerTest, StaticFileRange) {
  3634. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3635. ASSERT_TRUE(res);
  3636. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3637. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3638. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3639. EXPECT_EQ(true, res->has_header("Content-Range"));
  3640. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3641. EXPECT_EQ(std::string("cd"), res->body);
  3642. }
  3643. TEST_F(ServerTest, StaticFileRanges) {
  3644. auto res =
  3645. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3646. ASSERT_TRUE(res);
  3647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3648. EXPECT_TRUE(
  3649. res->get_header_value("Content-Type")
  3650. .find(
  3651. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3652. 0);
  3653. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3654. }
  3655. TEST_F(ServerTest, StaticFileRangeHead) {
  3656. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3657. ASSERT_TRUE(res);
  3658. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3659. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3660. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3661. EXPECT_EQ(true, res->has_header("Content-Range"));
  3662. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3663. }
  3664. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3665. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3668. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3669. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3670. EXPECT_EQ(true, res->has_header("Content-Range"));
  3671. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3672. res->get_header_value("Content-Range"));
  3673. EXPECT_EQ("LAST\n", res->body);
  3674. }
  3675. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3676. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3680. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3681. EXPECT_EQ(true, res->has_header("Content-Range"));
  3682. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3683. }
  3684. TEST_F(ServerTest, StaticFileBigFile) {
  3685. auto res = cli_.Get("/dir/1MB.txt");
  3686. ASSERT_TRUE(res);
  3687. EXPECT_EQ(StatusCode::OK_200, res->status);
  3688. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3689. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3690. }
  3691. TEST_F(ServerTest, InvalidBaseDirMount) {
  3692. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3693. }
  3694. TEST_F(ServerTest, Binary) {
  3695. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3696. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3697. "application/octet-stream");
  3698. ASSERT_TRUE(res);
  3699. ASSERT_EQ(StatusCode::OK_200, res->status);
  3700. ASSERT_EQ(4U, res->body.size());
  3701. res = cli_.Put("/binary", binary.data(), binary.size(),
  3702. "application/octet-stream");
  3703. ASSERT_TRUE(res);
  3704. ASSERT_EQ(StatusCode::OK_200, res->status);
  3705. ASSERT_EQ(4U, res->body.size());
  3706. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3707. "application/octet-stream");
  3708. ASSERT_TRUE(res);
  3709. ASSERT_EQ(StatusCode::OK_200, res->status);
  3710. ASSERT_EQ(4U, res->body.size());
  3711. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3712. "application/octet-stream");
  3713. ASSERT_TRUE(res);
  3714. ASSERT_EQ(StatusCode::OK_200, res->status);
  3715. ASSERT_EQ(4U, res->body.size());
  3716. }
  3717. TEST_F(ServerTest, BinaryString) {
  3718. auto binary = std::string("\x00\x01\x02\x03", 4);
  3719. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3720. ASSERT_TRUE(res);
  3721. ASSERT_EQ(StatusCode::OK_200, res->status);
  3722. ASSERT_EQ(4U, res->body.size());
  3723. res = cli_.Put("/binary", binary, "application/octet-stream");
  3724. ASSERT_TRUE(res);
  3725. ASSERT_EQ(StatusCode::OK_200, res->status);
  3726. ASSERT_EQ(4U, res->body.size());
  3727. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3728. ASSERT_TRUE(res);
  3729. ASSERT_EQ(StatusCode::OK_200, res->status);
  3730. ASSERT_EQ(4U, res->body.size());
  3731. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3732. ASSERT_TRUE(res);
  3733. ASSERT_EQ(StatusCode::OK_200, res->status);
  3734. ASSERT_EQ(4U, res->body.size());
  3735. }
  3736. TEST_F(ServerTest, EmptyRequest) {
  3737. auto res = cli_.Get("");
  3738. ASSERT_TRUE(!res);
  3739. EXPECT_EQ(Error::Connection, res.error());
  3740. }
  3741. TEST_F(ServerTest, LongRequest) {
  3742. std::string request;
  3743. for (size_t i = 0; i < 545; i++) {
  3744. request += "/TooLongRequest";
  3745. }
  3746. request += "OK";
  3747. auto res = cli_.Get(request.c_str());
  3748. ASSERT_TRUE(res);
  3749. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3750. }
  3751. TEST_F(ServerTest, TooLongRequest) {
  3752. std::string request;
  3753. for (size_t i = 0; i < 546; i++) {
  3754. request += "/TooLongRequest";
  3755. }
  3756. request += "_NG";
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(request.c_str());
  3760. auto end = std::chrono::high_resolution_clock::now();
  3761. auto elapsed =
  3762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3763. .count();
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3766. EXPECT_LE(elapsed, 100);
  3767. EXPECT_EQ("close", res->get_header_value("Connection"));
  3768. EXPECT_FALSE(cli_.is_socket_open());
  3769. }
  3770. TEST_F(ServerTest, AlmostTooLongRequest) {
  3771. // test for #2046 - URI length check shouldn't include other content on req
  3772. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3773. // leading /, space, HTTP/1.1)
  3774. std::string request =
  3775. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3776. auto res = cli_.Get(request.c_str());
  3777. ASSERT_TRUE(res);
  3778. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3779. }
  3780. TEST_F(ServerTest, LongHeader) {
  3781. Request req;
  3782. req.method = "GET";
  3783. req.path = "/hi";
  3784. std::string host_and_port;
  3785. host_and_port += HOST;
  3786. host_and_port += ":";
  3787. host_and_port += std::to_string(PORT);
  3788. req.headers.emplace("Host", host_and_port.c_str());
  3789. req.headers.emplace("Accept", "*/*");
  3790. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3791. req.headers.emplace(
  3792. "Header-Name",
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@");
  3822. auto res = std::make_shared<Response>();
  3823. auto error = Error::Success;
  3824. auto ret = cli_.send(req, *res, error);
  3825. ASSERT_TRUE(ret);
  3826. EXPECT_EQ(StatusCode::OK_200, res->status);
  3827. }
  3828. TEST_F(ServerTest, LongQueryValue) {
  3829. auto start = std::chrono::high_resolution_clock::now();
  3830. cli_.set_keep_alive(true);
  3831. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3832. auto end = std::chrono::high_resolution_clock::now();
  3833. auto elapsed =
  3834. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3835. .count();
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3838. EXPECT_LE(elapsed, 100);
  3839. EXPECT_EQ("close", res->get_header_value("Connection"));
  3840. EXPECT_FALSE(cli_.is_socket_open());
  3841. }
  3842. TEST_F(ServerTest, TooLongQueryValue) {
  3843. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3844. ASSERT_FALSE(res);
  3845. EXPECT_EQ(Error::Read, res.error());
  3846. }
  3847. TEST_F(ServerTest, TooLongHeader) {
  3848. Request req;
  3849. req.method = "GET";
  3850. req.path = "/hi";
  3851. std::string host_and_port;
  3852. host_and_port += HOST;
  3853. host_and_port += ":";
  3854. host_and_port += std::to_string(PORT);
  3855. req.headers.emplace("Host", host_and_port.c_str());
  3856. req.headers.emplace("Accept", "*/*");
  3857. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3858. req.headers.emplace(
  3859. "Header-Name",
  3860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3874. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3875. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3876. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3877. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3878. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3879. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3880. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3881. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3882. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3888. "@@@@@@@@@@@@@@@@@");
  3889. auto res = std::make_shared<Response>();
  3890. auto error = Error::Success;
  3891. auto ret = cli_.send(req, *res, error);
  3892. ASSERT_TRUE(ret);
  3893. EXPECT_EQ(StatusCode::OK_200, res->status);
  3894. }
  3895. TEST_F(ServerTest, HeaderCountAtLimit) {
  3896. // Test with headers just under the 100 limit
  3897. httplib::Headers headers;
  3898. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3899. // This should keep us just under the 100 header limit
  3900. for (int i = 0; i < 95; i++) {
  3901. std::string name = "X-Test-Header-" + std::to_string(i);
  3902. std::string value = "value" + std::to_string(i);
  3903. headers.emplace(name, value);
  3904. }
  3905. // This should work fine as we're under the limit
  3906. auto res = cli_.Get("/hi", headers);
  3907. EXPECT_TRUE(res);
  3908. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3909. }
  3910. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3911. // Test with many headers to exceed the 100 limit
  3912. httplib::Headers headers;
  3913. // Add 150 headers to definitely exceed the 100 limit
  3914. for (int i = 0; i < 150; i++) {
  3915. std::string name = "X-Test-Header-" + std::to_string(i);
  3916. std::string value = "value" + std::to_string(i);
  3917. headers.emplace(name, value);
  3918. }
  3919. // This should fail due to exceeding header count limit
  3920. cli_.set_keep_alive(true);
  3921. auto res = cli_.Get("/hi", headers);
  3922. // The request should either fail or return 400 Bad Request
  3923. if (res) {
  3924. // If we get a response, it should be 400 Bad Request
  3925. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3926. } else {
  3927. // Or the request should fail entirely
  3928. EXPECT_FALSE(res);
  3929. }
  3930. EXPECT_EQ("close", res->get_header_value("Connection"));
  3931. EXPECT_FALSE(cli_.is_socket_open());
  3932. }
  3933. TEST_F(ServerTest, PercentEncoding) {
  3934. auto res = cli_.Get("/e%6edwith%");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(StatusCode::OK_200, res->status);
  3937. }
  3938. TEST_F(ServerTest, PercentEncodingUnicode) {
  3939. auto res = cli_.Get("/e%u006edwith%");
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. }
  3943. TEST_F(ServerTest, InvalidPercentEncoding) {
  3944. auto res = cli_.Get("/%endwith%");
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3947. }
  3948. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3949. auto res = cli_.Get("/%uendwith%");
  3950. ASSERT_TRUE(res);
  3951. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3952. }
  3953. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3954. auto res = cli_.Get("/hello?aaa=bbb%");
  3955. ASSERT_TRUE(res);
  3956. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3957. }
  3958. TEST_F(ServerTest, PlusSignEncoding) {
  3959. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3960. ASSERT_TRUE(res);
  3961. EXPECT_EQ(StatusCode::OK_200, res->status);
  3962. EXPECT_EQ("a +b", res->body);
  3963. }
  3964. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3965. // This test simulates a potential DoS attack using many headers
  3966. // to verify our security fix prevents memory exhaustion
  3967. httplib::Headers attack_headers;
  3968. // Attempt to add many headers like an attacker would (200 headers to far
  3969. // exceed limit)
  3970. for (int i = 0; i < 200; i++) {
  3971. std::string name = "X-Attack-Header-" + std::to_string(i);
  3972. std::string value = "attack_payload_" + std::to_string(i);
  3973. attack_headers.emplace(name, value);
  3974. }
  3975. // Try to POST with excessive headers
  3976. cli_.set_keep_alive(true);
  3977. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3978. // Should either fail or return 400 Bad Request due to security limit
  3979. if (res) {
  3980. // If we get a response, it should be 400 Bad Request
  3981. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3982. } else {
  3983. // Request failed, which is the expected behavior for DoS protection
  3984. EXPECT_FALSE(res);
  3985. }
  3986. EXPECT_EQ("close", res->get_header_value("Connection"));
  3987. EXPECT_FALSE(cli_.is_socket_open());
  3988. }
  3989. TEST_F(ServerTest, MultipartFormData) {
  3990. UploadFormDataItems items = {
  3991. {"text1", "text default", "", ""},
  3992. {"text2", "aωb", "", ""},
  3993. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3994. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3995. {"file3", "", "", "application/octet-stream"},
  3996. {"file4", "", "", " application/json tmp-string "}};
  3997. auto res = cli_.Post("/multipart", items);
  3998. ASSERT_TRUE(res);
  3999. EXPECT_EQ(StatusCode::OK_200, res->status);
  4000. }
  4001. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  4002. UploadFormDataItems items = {
  4003. {"text", "default text", "", ""},
  4004. {"multi_text1", "aaaaa", "", ""},
  4005. {"multi_text1", "bbbbb", "", ""},
  4006. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4007. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  4008. "application/json"},
  4009. };
  4010. auto res = cli_.Post("/multipart/multi_file_values", items);
  4011. ASSERT_TRUE(res);
  4012. EXPECT_EQ(StatusCode::OK_200, res->status);
  4013. }
  4014. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  4015. auto res = cli_.Get("/hi");
  4016. ASSERT_TRUE(res);
  4017. EXPECT_EQ(StatusCode::OK_200, res->status);
  4018. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  4019. EXPECT_EQ("Hello World!", res->body);
  4020. }
  4021. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  4022. Request req;
  4023. req.method = "POST";
  4024. req.path = "/chunked";
  4025. std::string host_and_port;
  4026. host_and_port += HOST;
  4027. host_and_port += ":";
  4028. host_and_port += std::to_string(PORT);
  4029. req.headers.emplace("Host", host_and_port.c_str());
  4030. req.headers.emplace("Accept", "*/*");
  4031. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4032. req.headers.emplace("Content-Type", "text/plain");
  4033. req.headers.emplace("Content-Length", "0");
  4034. req.headers.emplace(
  4035. "Transfer-Encoding",
  4036. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  4037. // Client does not chunk, so make a chunked body manually.
  4038. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  4039. auto res = std::make_shared<Response>();
  4040. auto error = Error::Success;
  4041. auto ret = cli_.send(req, *res, error);
  4042. ASSERT_TRUE(ret);
  4043. EXPECT_EQ(StatusCode::OK_200, res->status);
  4044. }
  4045. TEST_F(ServerTest, GetStreamed2) {
  4046. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4049. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4050. EXPECT_EQ(true, res->has_header("Content-Range"));
  4051. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  4052. EXPECT_EQ(std::string("ab"), res->body);
  4053. }
  4054. TEST_F(ServerTest, GetStreamed) {
  4055. auto res = cli_.Get("/streamed");
  4056. ASSERT_TRUE(res);
  4057. EXPECT_EQ(StatusCode::OK_200, res->status);
  4058. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4059. EXPECT_EQ(std::string("aaabbb"), res->body);
  4060. }
  4061. TEST_F(ServerTest, GetStreamedWithRange1) {
  4062. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  4063. ASSERT_TRUE(res);
  4064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4065. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4066. EXPECT_EQ(true, res->has_header("Content-Range"));
  4067. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4068. EXPECT_EQ(std::string("def"), res->body);
  4069. }
  4070. TEST_F(ServerTest, GetStreamedWithRange2) {
  4071. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4072. ASSERT_TRUE(res);
  4073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4074. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4075. EXPECT_EQ(true, res->has_header("Content-Range"));
  4076. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4077. EXPECT_EQ(std::string("bcdefg"), res->body);
  4078. }
  4079. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4080. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4081. ASSERT_TRUE(res);
  4082. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4083. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4084. EXPECT_EQ(true, res->has_header("Content-Range"));
  4085. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4086. EXPECT_EQ(std::string("efg"), res->body);
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4089. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4092. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ(false, res->has_header("Content-Range"));
  4094. EXPECT_EQ(0U, res->body.size());
  4095. }
  4096. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4097. auto res = cli_.Get("/streamed-with-range",
  4098. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4099. "92233720368547758079223372036854775807"}});
  4100. ASSERT_TRUE(res);
  4101. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4102. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4103. EXPECT_EQ(false, res->has_header("Content-Range"));
  4104. EXPECT_EQ(0U, res->body.size());
  4105. }
  4106. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4107. auto res = cli_.Get(
  4108. "/with-range",
  4109. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4110. {"Accept-Encoding", ""}});
  4111. ASSERT_TRUE(res);
  4112. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4113. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ(true, res->has_header("Content-Range"));
  4115. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4116. EXPECT_EQ(std::string("abcdefg"), res->body);
  4117. }
  4118. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4119. auto res = cli_.Get("/with-range", {
  4120. {"Range", "bytes=0-"},
  4121. {"Accept-Encoding", ""},
  4122. });
  4123. ASSERT_TRUE(res);
  4124. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4125. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4126. EXPECT_EQ(true, res->has_header("Content-Range"));
  4127. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4128. EXPECT_EQ(std::string("abcdefg"), res->body);
  4129. }
  4130. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4131. auto res =
  4132. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4133. ASSERT_TRUE(res);
  4134. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4135. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4136. EXPECT_EQ(false, res->has_header("Content-Range"));
  4137. EXPECT_EQ(267U, res->body.size());
  4138. // Check that both range contents are present
  4139. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4140. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4141. // Check that Content-Range headers are present for both ranges
  4142. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4143. std::string::npos);
  4144. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4145. std::string::npos);
  4146. }
  4147. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4148. Ranges ranges;
  4149. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4150. ranges.emplace_back(0, -1);
  4151. }
  4152. auto res =
  4153. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4154. ASSERT_TRUE(res);
  4155. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4157. EXPECT_EQ(false, res->has_header("Content-Range"));
  4158. EXPECT_EQ(0U, res->body.size());
  4159. }
  4160. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4161. auto res =
  4162. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4163. ASSERT_TRUE(res);
  4164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4165. EXPECT_EQ(5U, res->body.size());
  4166. // Check that overlapping ranges are coalesced into a single range
  4167. EXPECT_EQ("bcdef", res->body);
  4168. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4169. // Should be single range, not multipart
  4170. EXPECT_TRUE(res->has_header("Content-Range"));
  4171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4172. }
  4173. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4174. auto res =
  4175. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4176. ASSERT_TRUE(res);
  4177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4178. EXPECT_EQ(268U, res->body.size());
  4179. // Check that both range contents are present
  4180. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4181. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4182. // Check that Content-Range headers are present for both ranges
  4183. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4184. std::string::npos);
  4185. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4186. std::string::npos);
  4187. }
  4188. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4189. auto res =
  4190. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ(269U, res->body.size());
  4194. // Check that both duplicate range contents are present
  4195. size_t first_abc = res->body.find("abc\r\n");
  4196. EXPECT_TRUE(first_abc != std::string::npos);
  4197. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4198. EXPECT_TRUE(second_abc != std::string::npos);
  4199. // Check that Content-Range headers are present for both ranges
  4200. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4201. EXPECT_TRUE(first_range != std::string::npos);
  4202. size_t second_range =
  4203. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4204. EXPECT_TRUE(second_range != std::string::npos);
  4205. }
  4206. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4207. auto res = cli_.Get("/streamed-with-range?error",
  4208. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4209. ASSERT_TRUE(res);
  4210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4212. EXPECT_EQ(false, res->has_header("Content-Range"));
  4213. EXPECT_EQ(0U, res->body.size());
  4214. }
  4215. TEST_F(ServerTest, GetStreamedEndless) {
  4216. uint64_t offset = 0;
  4217. auto res = cli_.Get("/streamed-cancel",
  4218. [&](const char * /*data*/, uint64_t data_length) {
  4219. if (offset < 100) {
  4220. offset += data_length;
  4221. return true;
  4222. }
  4223. return false;
  4224. });
  4225. ASSERT_TRUE(!res);
  4226. EXPECT_EQ(Error::Canceled, res.error());
  4227. }
  4228. TEST_F(ServerTest, ClientStop) {
  4229. std::atomic_size_t count{4};
  4230. std::vector<std::thread> threads;
  4231. for (auto i = count.load(); i != 0; --i) {
  4232. threads.emplace_back([&]() {
  4233. auto res = cli_.Get("/streamed-cancel",
  4234. [&](const char *, uint64_t) { return true; });
  4235. --count;
  4236. ASSERT_TRUE(!res);
  4237. EXPECT_TRUE(res.error() == Error::Canceled ||
  4238. res.error() == Error::Read || res.error() == Error::Write);
  4239. });
  4240. }
  4241. std::this_thread::sleep_for(std::chrono::seconds(2));
  4242. while (count != 0) {
  4243. cli_.stop();
  4244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4245. }
  4246. for (auto &t : threads) {
  4247. t.join();
  4248. }
  4249. }
  4250. TEST_F(ServerTest, GetWithRange1) {
  4251. auto res = cli_.Get("/with-range", {
  4252. make_range_header({{3, 5}}),
  4253. {"Accept-Encoding", ""},
  4254. });
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4258. EXPECT_EQ(true, res->has_header("Content-Range"));
  4259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4260. EXPECT_EQ(std::string("def"), res->body);
  4261. }
  4262. TEST_F(ServerTest, GetWithRange2) {
  4263. auto res = cli_.Get("/with-range", {
  4264. make_range_header({{1, -1}}),
  4265. {"Accept-Encoding", ""},
  4266. });
  4267. ASSERT_TRUE(res);
  4268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4270. EXPECT_EQ(true, res->has_header("Content-Range"));
  4271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4272. EXPECT_EQ(std::string("bcdefg"), res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRange3) {
  4275. auto res = cli_.Get("/with-range", {
  4276. make_range_header({{0, 0}}),
  4277. {"Accept-Encoding", ""},
  4278. });
  4279. ASSERT_TRUE(res);
  4280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4282. EXPECT_EQ(true, res->has_header("Content-Range"));
  4283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4284. EXPECT_EQ(std::string("a"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetWithRange4) {
  4287. auto res = cli_.Get("/with-range", {
  4288. make_range_header({{-1, 2}}),
  4289. {"Accept-Encoding", ""},
  4290. });
  4291. ASSERT_TRUE(res);
  4292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4294. EXPECT_EQ(true, res->has_header("Content-Range"));
  4295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4296. EXPECT_EQ(std::string("fg"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetWithRange5) {
  4299. auto res = cli_.Get("/with-range", {
  4300. make_range_header({{0, 5}}),
  4301. {"Accept-Encoding", ""},
  4302. });
  4303. ASSERT_TRUE(res);
  4304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4306. EXPECT_EQ(true, res->has_header("Content-Range"));
  4307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4308. EXPECT_EQ(std::string("abcdef"), res->body);
  4309. }
  4310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4311. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4314. }
  4315. TEST_F(ServerTest, GetWithRangeMultipart) {
  4316. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4317. ASSERT_TRUE(res);
  4318. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4319. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4320. EXPECT_EQ(false, res->has_header("Content-Range"));
  4321. EXPECT_EQ(267U, res->body.size());
  4322. }
  4323. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4324. auto res =
  4325. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4326. ASSERT_TRUE(res);
  4327. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4328. }
  4329. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4330. auto res = cli_.Get("/with-range-customized-response",
  4331. {{make_range_header({{1, 2}})}});
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4334. EXPECT_EQ(true, res->has_header("Content-Length"));
  4335. EXPECT_EQ(false, res->has_header("Content-Range"));
  4336. EXPECT_EQ(JSON_DATA, res->body);
  4337. }
  4338. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4339. auto res = cli_.Get("/with-range-customized-response",
  4340. {{make_range_header({{1, 2}, {4, 5}})}});
  4341. ASSERT_TRUE(res);
  4342. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4343. EXPECT_EQ(true, res->has_header("Content-Length"));
  4344. EXPECT_EQ(false, res->has_header("Content-Range"));
  4345. EXPECT_EQ(JSON_DATA, res->body);
  4346. }
  4347. TEST_F(ServerTest, Issue1772) {
  4348. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4349. ASSERT_TRUE(res);
  4350. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4351. }
  4352. TEST_F(ServerTest, Issue609) {
  4353. auto res = cli_.Delete("/issue609");
  4354. ASSERT_TRUE(res);
  4355. EXPECT_EQ(StatusCode::OK_200, res->status);
  4356. EXPECT_EQ(std::string("ok"), res->body);
  4357. }
  4358. TEST_F(ServerTest, GetStreamedChunked) {
  4359. auto res = cli_.Get("/streamed-chunked");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. EXPECT_EQ(std::string("123456789"), res->body);
  4363. }
  4364. TEST_F(ServerTest, GetStreamedChunked2) {
  4365. auto res = cli_.Get("/streamed-chunked2");
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. EXPECT_EQ(std::string("123456789"), res->body);
  4369. }
  4370. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4371. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. EXPECT_EQ(std::string("123456789"), res->body);
  4375. EXPECT_TRUE(res->has_header("Trailer"));
  4376. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4377. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4378. // Trailers are now stored separately from headers (security fix)
  4379. EXPECT_EQ(2U, res->trailers.size());
  4380. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4381. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4382. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4383. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4384. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4385. // Verify trailers are NOT in headers (security verification)
  4386. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4387. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4388. }
  4389. TEST_F(ServerTest, LargeChunkedPost) {
  4390. Request req;
  4391. req.method = "POST";
  4392. req.path = "/large-chunked";
  4393. std::string host_and_port;
  4394. host_and_port += HOST;
  4395. host_and_port += ":";
  4396. host_and_port += std::to_string(PORT);
  4397. req.headers.emplace("Host", host_and_port.c_str());
  4398. req.headers.emplace("Accept", "*/*");
  4399. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4400. req.headers.emplace("Content-Type", "text/plain");
  4401. req.headers.emplace("Content-Length", "0");
  4402. req.headers.emplace("Transfer-Encoding", "chunked");
  4403. std::string long_string(30 * 1024u, 'a');
  4404. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4405. // Attempt to make a large enough post to exceed OS buffers, to test that
  4406. // the server handles short reads if the full chunk data isn't available.
  4407. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4408. auto res = std::make_shared<Response>();
  4409. auto error = Error::Success;
  4410. auto ret = cli_.send(req, *res, error);
  4411. ASSERT_TRUE(ret);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. }
  4414. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4415. auto res = cli_.Get("/remote_addr");
  4416. ASSERT_TRUE(res);
  4417. EXPECT_EQ(StatusCode::OK_200, res->status);
  4418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4419. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4420. }
  4421. TEST_F(ServerTest, GetMethodLocalAddr) {
  4422. auto res = cli_.Get("/local_addr");
  4423. ASSERT_TRUE(res);
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4426. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4427. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4428. }
  4429. TEST_F(ServerTest, HTTPResponseSplitting) {
  4430. auto res = cli_.Get("/http_response_splitting");
  4431. ASSERT_TRUE(res);
  4432. EXPECT_EQ(StatusCode::OK_200, res->status);
  4433. }
  4434. TEST_F(ServerTest, SlowRequest) {
  4435. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4436. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4438. }
  4439. #if 0
  4440. TEST_F(ServerTest, SlowPost) {
  4441. char buffer[64 * 1024];
  4442. memset(buffer, 0x42, sizeof(buffer));
  4443. auto res = cli_.Post(
  4444. "/slowpost", 64 * 1024 * 1024,
  4445. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4446. auto ret = sink.write(buffer, sizeof(buffer));
  4447. EXPECT_TRUE(ret);
  4448. return true;
  4449. },
  4450. "text/plain");
  4451. ASSERT_TRUE(res);
  4452. EXPECT_EQ(StatusCode::OK_200, res->status);
  4453. }
  4454. TEST_F(ServerTest, SlowPostFail) {
  4455. char buffer[64 * 1024];
  4456. memset(buffer, 0x42, sizeof(buffer));
  4457. cli_.set_write_timeout(std::chrono::seconds(0));
  4458. auto res = cli_.Post(
  4459. "/slowpost", 64 * 1024 * 1024,
  4460. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4461. sink.write(buffer, sizeof(buffer));
  4462. return true;
  4463. },
  4464. "text/plain");
  4465. ASSERT_TRUE(!res);
  4466. EXPECT_EQ(Error::Write, res.error());
  4467. }
  4468. #endif
  4469. TEST_F(ServerTest, Put) {
  4470. auto res = cli_.Put("/put", "PUT", "text/plain");
  4471. ASSERT_TRUE(res);
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("PUT", res->body);
  4474. }
  4475. TEST_F(ServerTest, PutWithContentProvider) {
  4476. auto res = cli_.Put(
  4477. "/put", 3,
  4478. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4479. sink.os << "PUT";
  4480. return true;
  4481. },
  4482. "text/plain");
  4483. ASSERT_TRUE(res);
  4484. EXPECT_EQ(StatusCode::OK_200, res->status);
  4485. EXPECT_EQ("PUT", res->body);
  4486. }
  4487. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4488. auto res = cli_.Post(
  4489. "/post", 42,
  4490. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4491. return false;
  4492. },
  4493. "text/plain");
  4494. ASSERT_TRUE(!res);
  4495. EXPECT_EQ(Error::Canceled, res.error());
  4496. }
  4497. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  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, PostWithContentProviderWithoutLengthAbort) {
  4511. auto res = cli_.Post(
  4512. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4513. "text/plain");
  4514. ASSERT_TRUE(!res);
  4515. EXPECT_EQ(Error::Canceled, res.error());
  4516. }
  4517. TEST_F(ServerTest, PostLoopBack) {
  4518. std::string body;
  4519. auto res = cli_.Post(
  4520. "/post-loopback", 9,
  4521. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4522. EXPECT_EQ(9u, length);
  4523. sink.write("123", 3);
  4524. sink.write("456", 3);
  4525. sink.write("789", 3);
  4526. return true;
  4527. },
  4528. "text/plain",
  4529. [&body](const char *data, size_t data_length) {
  4530. body.append(data, data_length);
  4531. return true;
  4532. });
  4533. ASSERT_TRUE(res);
  4534. EXPECT_EQ(StatusCode::OK_200, res->status);
  4535. EXPECT_EQ("123456789", body);
  4536. }
  4537. TEST_F(ServerTest, PutLoopBack) {
  4538. std::string body;
  4539. auto res = cli_.Put(
  4540. "/put-loopback", 9,
  4541. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4542. EXPECT_EQ(9u, length);
  4543. sink.write("123", 3);
  4544. sink.write("456", 3);
  4545. sink.write("789", 3);
  4546. return true;
  4547. },
  4548. "text/plain",
  4549. [&body](const char *data, size_t data_length) {
  4550. body.append(data, data_length);
  4551. return true;
  4552. });
  4553. ASSERT_TRUE(res);
  4554. EXPECT_EQ(StatusCode::OK_200, res->status);
  4555. EXPECT_EQ("123456789", body);
  4556. }
  4557. TEST_F(ServerTest, PatchLoopBack) {
  4558. std::string body;
  4559. auto res = cli_.Patch(
  4560. "/patch-loopback", 9,
  4561. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4562. EXPECT_EQ(9u, length);
  4563. sink.write("123", 3);
  4564. sink.write("456", 3);
  4565. sink.write("789", 3);
  4566. return true;
  4567. },
  4568. "text/plain",
  4569. [&body](const char *data, size_t data_length) {
  4570. body.append(data, data_length);
  4571. return true;
  4572. });
  4573. ASSERT_TRUE(res);
  4574. EXPECT_EQ(StatusCode::OK_200, res->status);
  4575. EXPECT_EQ("123456789", body);
  4576. }
  4577. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4578. std::string body;
  4579. auto res = cli_.Post(
  4580. "/post-loopback",
  4581. [](size_t /*offset*/, DataSink &sink) {
  4582. sink.write("123", 3);
  4583. sink.write("456", 3);
  4584. sink.write("789", 3);
  4585. sink.done();
  4586. return true;
  4587. },
  4588. "text/plain",
  4589. [&body](const char *data, size_t data_length) {
  4590. body.append(data, data_length);
  4591. return true;
  4592. });
  4593. ASSERT_TRUE(res);
  4594. EXPECT_EQ(StatusCode::OK_200, res->status);
  4595. EXPECT_EQ("123456789", body);
  4596. }
  4597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4598. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4599. cli_.set_compress(true);
  4600. auto res = cli_.Put(
  4601. "/put", 3,
  4602. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4603. sink.os << "PUT";
  4604. return true;
  4605. },
  4606. "text/plain");
  4607. ASSERT_TRUE(res);
  4608. EXPECT_EQ(StatusCode::OK_200, res->status);
  4609. EXPECT_EQ("PUT", res->body);
  4610. }
  4611. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4612. cli_.set_compress(true);
  4613. auto res = cli_.Post(
  4614. "/post", 42,
  4615. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4616. return false;
  4617. },
  4618. "text/plain");
  4619. ASSERT_TRUE(!res);
  4620. EXPECT_EQ(Error::Canceled, res.error());
  4621. }
  4622. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4623. cli_.set_compress(true);
  4624. auto res = cli_.Put(
  4625. "/put",
  4626. [](size_t /*offset*/, DataSink &sink) {
  4627. sink.os << "PUT";
  4628. sink.done();
  4629. return true;
  4630. },
  4631. "text/plain");
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("PUT", res->body);
  4635. }
  4636. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4637. cli_.set_compress(true);
  4638. auto res = cli_.Post(
  4639. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4640. "text/plain");
  4641. ASSERT_TRUE(!res);
  4642. EXPECT_EQ(Error::Canceled, res.error());
  4643. }
  4644. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4645. cli_.set_compress(true);
  4646. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4647. ASSERT_TRUE(res);
  4648. EXPECT_EQ(StatusCode::OK_200, res->status);
  4649. EXPECT_EQ(LARGE_DATA, res->body);
  4650. }
  4651. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4652. #ifdef CPPHTTPLIB_SSL_ENABLED
  4653. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4654. Client cli(s.c_str());
  4655. cli.enable_server_certificate_verification(false);
  4656. #else
  4657. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4658. Client cli(s.c_str());
  4659. #endif
  4660. cli.set_compress(true);
  4661. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4662. ASSERT_TRUE(res);
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ(LARGE_DATA, res->body);
  4665. // The compressed size should be less than a 10th of the original. May vary
  4666. // depending on the zlib library.
  4667. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4668. static_cast<uint64_t>(10 * 1024 * 1024));
  4669. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4670. }
  4671. TEST_F(ServerTest, PutContentWithDeflate) {
  4672. cli_.set_compress(false);
  4673. Headers headers;
  4674. headers.emplace("Content-Encoding", "deflate");
  4675. // PUT in deflate format:
  4676. auto res = cli_.Put("/put", headers,
  4677. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4678. ASSERT_TRUE(res);
  4679. EXPECT_EQ(StatusCode::OK_200, res->status);
  4680. EXPECT_EQ("PUT", res->body);
  4681. }
  4682. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4683. Headers headers;
  4684. headers.emplace("Accept-Encoding", "gzip, deflate");
  4685. auto res = cli_.Get("/streamed-chunked", headers);
  4686. ASSERT_TRUE(res);
  4687. EXPECT_EQ(StatusCode::OK_200, res->status);
  4688. EXPECT_EQ(std::string("123456789"), res->body);
  4689. }
  4690. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4691. Headers headers;
  4692. headers.emplace("Accept-Encoding", "gzip, deflate");
  4693. auto res = cli_.Get("/streamed-chunked2", headers);
  4694. ASSERT_TRUE(res);
  4695. EXPECT_EQ(StatusCode::OK_200, res->status);
  4696. EXPECT_EQ(std::string("123456789"), res->body);
  4697. }
  4698. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4699. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4700. ASSERT_TRUE(res);
  4701. EXPECT_EQ(StatusCode::OK_200, res->status);
  4702. }
  4703. TEST(GzipDecompressor, ChunkedDecompression) {
  4704. std::string data;
  4705. for (size_t i = 0; i < 32 * 1024; ++i) {
  4706. data.push_back(static_cast<char>('a' + i % 26));
  4707. }
  4708. std::string compressed_data;
  4709. {
  4710. httplib::detail::gzip_compressor compressor;
  4711. bool result = compressor.compress(
  4712. data.data(), data.size(),
  4713. /*last=*/true,
  4714. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4715. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4716. compressed_data_size);
  4717. return true;
  4718. });
  4719. ASSERT_TRUE(result);
  4720. }
  4721. std::string decompressed_data;
  4722. {
  4723. httplib::detail::gzip_decompressor decompressor;
  4724. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4725. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4726. size_t chunk_size = 130;
  4727. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4728. chunk_begin += chunk_size) {
  4729. size_t current_chunk_size =
  4730. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4731. bool result = decompressor.decompress(
  4732. compressed_data.data() + chunk_begin, current_chunk_size,
  4733. [&](const char *decompressed_data_chunk,
  4734. size_t decompressed_data_chunk_size) {
  4735. decompressed_data.insert(decompressed_data.size(),
  4736. decompressed_data_chunk,
  4737. decompressed_data_chunk_size);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(result);
  4741. }
  4742. }
  4743. ASSERT_EQ(data, decompressed_data);
  4744. }
  4745. TEST(GzipDecompressor, DeflateDecompression) {
  4746. std::string original_text = "Raw deflate without gzip";
  4747. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4748. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4749. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4750. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4751. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4752. std::string decompressed_data;
  4753. {
  4754. httplib::detail::gzip_decompressor decompressor;
  4755. bool result = decompressor.decompress(
  4756. compressed_data.data(), compressed_data.size(),
  4757. [&](const char *decompressed_data_chunk,
  4758. size_t decompressed_data_chunk_size) {
  4759. decompressed_data.insert(decompressed_data.size(),
  4760. decompressed_data_chunk,
  4761. decompressed_data_chunk_size);
  4762. return true;
  4763. });
  4764. ASSERT_TRUE(result);
  4765. }
  4766. ASSERT_EQ(original_text, decompressed_data);
  4767. }
  4768. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4769. std::string original_text = "Raw deflate without gzip";
  4770. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4771. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4772. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4773. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4774. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4775. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4776. std::string decompressed_data;
  4777. {
  4778. httplib::detail::gzip_decompressor decompressor;
  4779. bool result = decompressor.decompress(
  4780. compressed_data.data(), compressed_data.size(),
  4781. [&](const char *decompressed_data_chunk,
  4782. size_t decompressed_data_chunk_size) {
  4783. decompressed_data.insert(decompressed_data.size(),
  4784. decompressed_data_chunk,
  4785. decompressed_data_chunk_size);
  4786. return true;
  4787. });
  4788. ASSERT_TRUE(result);
  4789. }
  4790. ASSERT_EQ(original_text, decompressed_data);
  4791. }
  4792. #ifdef _WIN32
  4793. TEST(GzipDecompressor, LargeRandomData) {
  4794. // prepare large random data that is difficult to be compressed and is
  4795. // expected to have large size even when compressed
  4796. std::random_device seed_gen;
  4797. std::mt19937 random(seed_gen());
  4798. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4799. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4800. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4801. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4802. // compress data over 4GiB
  4803. std::string compressed_data;
  4804. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4805. httplib::detail::gzip_compressor compressor;
  4806. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4807. data.size() * sizeof(std::uint32_t), true,
  4808. [&](const char *data, size_t size) {
  4809. compressed_data.insert(
  4810. compressed_data.size(), data, size);
  4811. return true;
  4812. });
  4813. ASSERT_TRUE(result);
  4814. // FIXME: compressed data size is expected to be greater than 4GiB,
  4815. // but there is no guarantee
  4816. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4817. // decompress data over 4GiB
  4818. std::string decompressed_data;
  4819. decompressed_data.reserve(data_size);
  4820. httplib::detail::gzip_decompressor decompressor;
  4821. result = decompressor.decompress(
  4822. compressed_data.data(), compressed_data.size(),
  4823. [&](const char *data, size_t size) {
  4824. decompressed_data.insert(decompressed_data.size(), data, size);
  4825. return true;
  4826. });
  4827. ASSERT_TRUE(result);
  4828. // compare
  4829. ASSERT_EQ(data_size, decompressed_data.size());
  4830. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4831. 0);
  4832. }
  4833. #endif
  4834. #endif
  4835. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4836. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4837. Headers headers;
  4838. headers.emplace("Accept-Encoding", "br");
  4839. auto res = cli_.Get("/streamed-chunked", headers);
  4840. ASSERT_TRUE(res);
  4841. EXPECT_EQ(StatusCode::OK_200, res->status);
  4842. EXPECT_EQ(std::string("123456789"), res->body);
  4843. }
  4844. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4845. Headers headers;
  4846. headers.emplace("Accept-Encoding", "br");
  4847. auto res = cli_.Get("/streamed-chunked2", headers);
  4848. ASSERT_TRUE(res);
  4849. EXPECT_EQ(StatusCode::OK_200, res->status);
  4850. EXPECT_EQ(std::string("123456789"), res->body);
  4851. }
  4852. #endif
  4853. TEST_F(ServerTest, Patch) {
  4854. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4855. ASSERT_TRUE(res);
  4856. EXPECT_EQ(StatusCode::OK_200, res->status);
  4857. EXPECT_EQ("PATCH", res->body);
  4858. }
  4859. TEST_F(ServerTest, Delete) {
  4860. auto res = cli_.Delete("/delete");
  4861. ASSERT_TRUE(res);
  4862. EXPECT_EQ(StatusCode::OK_200, res->status);
  4863. EXPECT_EQ("DELETE", res->body);
  4864. }
  4865. TEST_F(ServerTest, DeleteContentReceiver) {
  4866. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ("content", res->body);
  4870. }
  4871. TEST_F(ServerTest, Options) {
  4872. auto res = cli_.Options("*");
  4873. ASSERT_TRUE(res);
  4874. EXPECT_EQ(StatusCode::OK_200, res->status);
  4875. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4876. EXPECT_TRUE(res->body.empty());
  4877. }
  4878. TEST_F(ServerTest, URL) {
  4879. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4880. ASSERT_TRUE(res);
  4881. EXPECT_EQ(StatusCode::OK_200, res->status);
  4882. }
  4883. TEST_F(ServerTest, ArrayParam) {
  4884. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4885. ASSERT_TRUE(res);
  4886. EXPECT_EQ(StatusCode::OK_200, res->status);
  4887. }
  4888. TEST_F(ServerTest, NoMultipleHeaders) {
  4889. Headers headers = {{"Content-Length", "5"}};
  4890. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4891. "text/plain");
  4892. ASSERT_TRUE(res);
  4893. EXPECT_EQ(StatusCode::OK_200, res->status);
  4894. }
  4895. TEST_F(ServerTest, PostContentReceiver) {
  4896. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4897. ASSERT_TRUE(res);
  4898. ASSERT_EQ(StatusCode::OK_200, res->status);
  4899. ASSERT_EQ("content", res->body);
  4900. }
  4901. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4902. UploadFormDataItems items = {
  4903. {"text1", "text default", "", ""},
  4904. {"text2", "aωb", "", ""},
  4905. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4906. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4907. {"file3", "", "", "application/octet-stream"},
  4908. };
  4909. auto res = cli_.Post("/content_receiver", items);
  4910. ASSERT_TRUE(res);
  4911. EXPECT_EQ(StatusCode::OK_200, res->status);
  4912. }
  4913. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4914. UploadFormDataItems items = {
  4915. {"text1", "text default", "", ""},
  4916. {"text2", "aωb", "", ""},
  4917. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4918. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4919. {"file3", "", "", "application/octet-stream"},
  4920. };
  4921. auto boundary = std::string("+++++");
  4922. std::string body;
  4923. for (const auto &item : items) {
  4924. body += "--" + boundary + "\r\n";
  4925. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4926. if (!item.filename.empty()) {
  4927. body += "; filename=\"" + item.filename + "\"";
  4928. }
  4929. body += "\r\n";
  4930. if (!item.content_type.empty()) {
  4931. body += "Content-Type: " + item.content_type + "\r\n";
  4932. }
  4933. body += "\r\n";
  4934. body += item.content + "\r\n";
  4935. }
  4936. body += "--" + boundary + "--\r\n";
  4937. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4938. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4939. ASSERT_TRUE(res);
  4940. EXPECT_EQ(StatusCode::OK_200, res->status);
  4941. }
  4942. TEST_F(ServerTest, PostContentReceiverGzip) {
  4943. cli_.set_compress(true);
  4944. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4945. ASSERT_TRUE(res);
  4946. ASSERT_EQ(StatusCode::OK_200, res->status);
  4947. ASSERT_EQ("content", res->body);
  4948. }
  4949. TEST_F(ServerTest, PutContentReceiver) {
  4950. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4951. ASSERT_TRUE(res);
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. ASSERT_EQ("content", res->body);
  4954. }
  4955. TEST_F(ServerTest, PatchContentReceiver) {
  4956. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4957. ASSERT_TRUE(res);
  4958. ASSERT_EQ(StatusCode::OK_200, res->status);
  4959. ASSERT_EQ("content", res->body);
  4960. }
  4961. template <typename ClientType>
  4962. void TestWithHeadersAndContentReceiver(
  4963. ClientType &cli,
  4964. std::function<Result(ClientType &, const std::string &, const Headers &,
  4965. const std::string &, const std::string &,
  4966. ContentReceiver, DownloadProgress)>
  4967. request_func) {
  4968. Headers headers;
  4969. headers.emplace("X-Custom-Header", "test-value");
  4970. std::string received_body;
  4971. auto res = request_func(
  4972. cli, "/content_receiver", headers, "content", "application/json",
  4973. [&](const char *data, size_t data_length) {
  4974. received_body.append(data, data_length);
  4975. return true;
  4976. },
  4977. nullptr);
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("content", received_body);
  4981. }
  4982. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4983. #ifdef CPPHTTPLIB_SSL_ENABLED
  4984. using ClientT = SSLClient;
  4985. #else
  4986. using ClientT = Client;
  4987. #endif
  4988. TestWithHeadersAndContentReceiver<ClientT>(
  4989. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4990. const std::string &body, const std::string &content_type,
  4991. ContentReceiver receiver, DownloadProgress progress) {
  4992. return cli.Post(path, headers, body, content_type, receiver, progress);
  4993. });
  4994. }
  4995. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4996. #ifdef CPPHTTPLIB_SSL_ENABLED
  4997. using ClientT = SSLClient;
  4998. #else
  4999. using ClientT = Client;
  5000. #endif
  5001. TestWithHeadersAndContentReceiver<ClientT>(
  5002. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5003. const std::string &body, const std::string &content_type,
  5004. ContentReceiver receiver, DownloadProgress progress) {
  5005. return cli.Put(path, headers, body, content_type, receiver, progress);
  5006. });
  5007. }
  5008. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  5009. #ifdef CPPHTTPLIB_SSL_ENABLED
  5010. using ClientT = SSLClient;
  5011. #else
  5012. using ClientT = Client;
  5013. #endif
  5014. TestWithHeadersAndContentReceiver<ClientT>(
  5015. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5016. const std::string &body, const std::string &content_type,
  5017. ContentReceiver receiver, DownloadProgress progress) {
  5018. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5019. });
  5020. }
  5021. template <typename ClientType>
  5022. void TestWithHeadersAndContentReceiverWithProgress(
  5023. ClientType &cli,
  5024. std::function<Result(ClientType &, const std::string &, const Headers &,
  5025. const std::string &, const std::string &,
  5026. ContentReceiver, DownloadProgress)>
  5027. request_func) {
  5028. Headers headers;
  5029. headers.emplace("X-Test-Header", "progress-test");
  5030. std::string received_body;
  5031. auto progress_called = false;
  5032. auto res = request_func(
  5033. cli, "/content_receiver", headers, "content", "text/plain",
  5034. [&](const char *data, size_t data_length) {
  5035. received_body.append(data, data_length);
  5036. return true;
  5037. },
  5038. [&](uint64_t /*current*/, uint64_t /*total*/) {
  5039. progress_called = true;
  5040. return true;
  5041. });
  5042. ASSERT_TRUE(res);
  5043. EXPECT_EQ(StatusCode::OK_200, res->status);
  5044. EXPECT_EQ("content", received_body);
  5045. EXPECT_TRUE(progress_called);
  5046. }
  5047. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  5048. #ifdef CPPHTTPLIB_SSL_ENABLED
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5055. const std::string &body, const std::string &content_type,
  5056. ContentReceiver receiver, DownloadProgress progress) {
  5057. return cli.Post(path, headers, body, content_type, receiver, progress);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  5061. #ifdef CPPHTTPLIB_SSL_ENABLED
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5068. const std::string &body, const std::string &content_type,
  5069. ContentReceiver receiver, DownloadProgress progress) {
  5070. return cli.Put(path, headers, body, content_type, receiver, progress);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5074. #ifdef CPPHTTPLIB_SSL_ENABLED
  5075. using ClientT = SSLClient;
  5076. #else
  5077. using ClientT = Client;
  5078. #endif
  5079. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5080. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5081. const std::string &body, const std::string &content_type,
  5082. ContentReceiver receiver, DownloadProgress progress) {
  5083. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5084. });
  5085. }
  5086. template <typename ClientType>
  5087. void TestWithHeadersAndContentReceiverError(
  5088. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5089. const Headers &, const std::string &,
  5090. const std::string &, ContentReceiver)>
  5091. request_func) {
  5092. Headers headers;
  5093. headers.emplace("X-Error-Test", "true");
  5094. std::string received_body;
  5095. auto receiver_failed = false;
  5096. auto res =
  5097. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5098. [&](const char *data, size_t data_length) {
  5099. received_body.append(data, data_length);
  5100. receiver_failed = true;
  5101. return false;
  5102. });
  5103. ASSERT_FALSE(res);
  5104. EXPECT_TRUE(receiver_failed);
  5105. }
  5106. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5107. #ifdef CPPHTTPLIB_SSL_ENABLED
  5108. using ClientT = SSLClient;
  5109. #else
  5110. using ClientT = Client;
  5111. #endif
  5112. TestWithHeadersAndContentReceiverError<ClientT>(
  5113. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5114. const std::string &body, const std::string &content_type,
  5115. ContentReceiver receiver) {
  5116. return cli.Post(path, headers, body, content_type, receiver);
  5117. });
  5118. }
  5119. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5120. #ifdef CPPHTTPLIB_SSL_ENABLED
  5121. using ClientT = SSLClient;
  5122. #else
  5123. using ClientT = Client;
  5124. #endif
  5125. TestWithHeadersAndContentReceiverError<ClientT>(
  5126. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5127. const std::string &body, const std::string &content_type,
  5128. ContentReceiver receiver) {
  5129. return cli.Put(path, headers, body, content_type, receiver);
  5130. });
  5131. }
  5132. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5133. #ifdef CPPHTTPLIB_SSL_ENABLED
  5134. using ClientT = SSLClient;
  5135. #else
  5136. using ClientT = Client;
  5137. #endif
  5138. TestWithHeadersAndContentReceiverError<ClientT>(
  5139. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5140. const std::string &body, const std::string &content_type,
  5141. ContentReceiver receiver) {
  5142. return cli.Patch(path, headers, body, content_type, receiver);
  5143. });
  5144. }
  5145. TEST_F(ServerTest, PostQueryStringAndBody) {
  5146. auto res =
  5147. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5148. ASSERT_TRUE(res);
  5149. ASSERT_EQ(StatusCode::OK_200, res->status);
  5150. }
  5151. TEST_F(ServerTest, HTTP2Magic) {
  5152. Request req;
  5153. req.method = "PRI";
  5154. req.path = "*";
  5155. req.body = "SM";
  5156. auto res = std::make_shared<Response>();
  5157. auto error = Error::Success;
  5158. auto ret = cli_.send(req, *res, error);
  5159. ASSERT_TRUE(ret);
  5160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5161. }
  5162. TEST_F(ServerTest, KeepAlive) {
  5163. auto res = cli_.Get("/hi");
  5164. ASSERT_TRUE(res);
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("Hello World!", res->body);
  5168. res = cli_.Get("/hi");
  5169. ASSERT_TRUE(res);
  5170. EXPECT_EQ(StatusCode::OK_200, res->status);
  5171. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5172. EXPECT_EQ("Hello World!", res->body);
  5173. res = cli_.Get("/hi");
  5174. ASSERT_TRUE(res);
  5175. EXPECT_EQ(StatusCode::OK_200, res->status);
  5176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5177. EXPECT_EQ("Hello World!", res->body);
  5178. res = cli_.Get("/not-exist");
  5179. ASSERT_TRUE(res);
  5180. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5181. res = cli_.Post("/empty", "", "text/plain");
  5182. ASSERT_TRUE(res);
  5183. EXPECT_EQ(StatusCode::OK_200, res->status);
  5184. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5185. EXPECT_EQ("empty", res->body);
  5186. EXPECT_EQ("close", res->get_header_value("Connection"));
  5187. res = cli_.Post(
  5188. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5189. "text/plain");
  5190. ASSERT_TRUE(res);
  5191. EXPECT_EQ(StatusCode::OK_200, res->status);
  5192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5193. EXPECT_EQ("empty", res->body);
  5194. cli_.set_keep_alive(false);
  5195. res = cli_.Get("/last-request");
  5196. ASSERT_TRUE(res);
  5197. EXPECT_EQ(StatusCode::OK_200, res->status);
  5198. EXPECT_EQ("close", res->get_header_value("Connection"));
  5199. }
  5200. TEST_F(ServerTest, TooManyRedirect) {
  5201. cli_.set_follow_location(true);
  5202. auto res = cli_.Get("/redirect/0");
  5203. ASSERT_TRUE(!res);
  5204. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5205. }
  5206. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5207. Request req;
  5208. req.method = "FOOBAR";
  5209. req.path = "/hi";
  5210. cli_.set_keep_alive(true);
  5211. auto res = cli_.send(req);
  5212. ASSERT_TRUE(res);
  5213. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5214. EXPECT_EQ("close", res->get_header_value("Connection"));
  5215. EXPECT_FALSE(cli_.is_socket_open());
  5216. }
  5217. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5218. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5219. TEST_F(ServerTest, Gzip) {
  5220. Headers headers;
  5221. headers.emplace("Accept-Encoding", "gzip, deflate");
  5222. auto res = cli_.Get("/compress", headers);
  5223. ASSERT_TRUE(res);
  5224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5226. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5228. "7890123456789012345678901234567890",
  5229. res->body);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. }
  5232. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5233. Headers headers;
  5234. headers.emplace("Accept-Encoding", "");
  5235. auto res = cli_.Get("/compress", headers);
  5236. ASSERT_TRUE(res);
  5237. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5238. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5239. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5240. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5241. "7890123456789012345678901234567890",
  5242. res->body);
  5243. EXPECT_EQ(StatusCode::OK_200, res->status);
  5244. }
  5245. TEST_F(ServerTest, GzipWithContentReceiver) {
  5246. Headers headers;
  5247. headers.emplace("Accept-Encoding", "gzip, deflate");
  5248. std::string body;
  5249. auto res = cli_.Get("/compress", headers,
  5250. [&](const char *data, uint64_t data_length) {
  5251. EXPECT_EQ(100U, data_length);
  5252. body.append(data, data_length);
  5253. return true;
  5254. });
  5255. ASSERT_TRUE(res);
  5256. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5257. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5258. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5259. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5260. "7890123456789012345678901234567890",
  5261. body);
  5262. EXPECT_EQ(StatusCode::OK_200, res->status);
  5263. }
  5264. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5265. Headers headers;
  5266. headers.emplace("Accept-Encoding", "gzip, deflate");
  5267. cli_.set_decompress(false);
  5268. auto res = cli_.Get("/compress", headers);
  5269. ASSERT_TRUE(res);
  5270. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5271. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5272. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5273. EXPECT_EQ(33U, res->body.size());
  5274. EXPECT_EQ(StatusCode::OK_200, res->status);
  5275. }
  5276. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5277. Headers headers;
  5278. headers.emplace("Accept-Encoding", "");
  5279. std::string body;
  5280. auto res = cli_.Get("/compress", headers,
  5281. [&](const char *data, uint64_t data_length) {
  5282. EXPECT_EQ(100U, data_length);
  5283. body.append(data, data_length);
  5284. return true;
  5285. });
  5286. ASSERT_TRUE(res);
  5287. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, NoGzip) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "gzip, deflate");
  5298. auto res = cli_.Get("/nocompress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5301. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "gzip, deflate");
  5311. std::string body;
  5312. auto res = cli_.Get("/nocompress", headers,
  5313. [&](const char *data, uint64_t data_length) {
  5314. EXPECT_EQ(100U, data_length);
  5315. body.append(data, data_length);
  5316. return true;
  5317. });
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5320. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5323. "7890123456789012345678901234567890",
  5324. body);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, MultipartFormDataGzip) {
  5328. UploadFormDataItems items = {
  5329. {"key1", "test", "", ""},
  5330. {"key2", "--abcdefg123", "", ""},
  5331. };
  5332. cli_.set_compress(true);
  5333. auto res = cli_.Post("/compress-multipart", items);
  5334. ASSERT_TRUE(res);
  5335. EXPECT_EQ(StatusCode::OK_200, res->status);
  5336. }
  5337. #endif
  5338. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5339. TEST_F(ServerTest, Brotli) {
  5340. Headers headers;
  5341. headers.emplace("Accept-Encoding", "br");
  5342. auto res = cli_.Get("/compress", headers);
  5343. ASSERT_TRUE(res);
  5344. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5345. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5346. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5347. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5348. "7890123456789012345678901234567890",
  5349. res->body);
  5350. EXPECT_EQ(StatusCode::OK_200, res->status);
  5351. }
  5352. #endif
  5353. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5354. TEST_F(ServerTest, Zstd) {
  5355. Headers headers;
  5356. headers.emplace("Accept-Encoding", "zstd");
  5357. auto res = cli_.Get("/compress", headers);
  5358. ASSERT_TRUE(res);
  5359. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5360. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5361. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5362. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5363. "7890123456789012345678901234567890",
  5364. res->body);
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. }
  5367. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5368. Headers headers;
  5369. headers.emplace("Accept-Encoding", "");
  5370. auto res = cli_.Get("/compress", headers);
  5371. ASSERT_TRUE(res);
  5372. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5373. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5374. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5375. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5376. "7890123456789012345678901234567890",
  5377. res->body);
  5378. EXPECT_EQ(StatusCode::OK_200, res->status);
  5379. }
  5380. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5381. Headers headers;
  5382. headers.emplace("Accept-Encoding", "zstd");
  5383. std::string body;
  5384. auto res = cli_.Get("/compress", headers,
  5385. [&](const char *data, uint64_t data_length) {
  5386. EXPECT_EQ(100U, data_length);
  5387. body.append(data, data_length);
  5388. return true;
  5389. });
  5390. ASSERT_TRUE(res);
  5391. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5393. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5394. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5395. "7890123456789012345678901234567890",
  5396. body);
  5397. EXPECT_EQ(StatusCode::OK_200, res->status);
  5398. }
  5399. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5400. Headers headers;
  5401. headers.emplace("Accept-Encoding", "zstd");
  5402. cli_.set_decompress(false);
  5403. auto res = cli_.Get("/compress", headers);
  5404. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5405. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5406. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5407. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5410. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5411. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5412. EXPECT_EQ(StatusCode::OK_200, res->status);
  5413. ASSERT_EQ(26U, res->body.size());
  5414. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5415. 0);
  5416. }
  5417. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "");
  5420. std::string body;
  5421. auto res = cli_.Get("/compress", headers,
  5422. [&](const char *data, uint64_t data_length) {
  5423. EXPECT_EQ(100U, data_length);
  5424. body.append(data, data_length);
  5425. return true;
  5426. });
  5427. ASSERT_TRUE(res);
  5428. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5429. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5430. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5431. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5432. "7890123456789012345678901234567890",
  5433. body);
  5434. EXPECT_EQ(StatusCode::OK_200, res->status);
  5435. }
  5436. TEST_F(ServerTest, NoZstd) {
  5437. Headers headers;
  5438. headers.emplace("Accept-Encoding", "zstd");
  5439. auto res = cli_.Get("/nocompress", headers);
  5440. ASSERT_TRUE(res);
  5441. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5442. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5443. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5444. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5445. "7890123456789012345678901234567890",
  5446. res->body);
  5447. EXPECT_EQ(StatusCode::OK_200, res->status);
  5448. }
  5449. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5450. Headers headers;
  5451. headers.emplace("Accept-Encoding", "zstd");
  5452. std::string body;
  5453. auto res = cli_.Get("/nocompress", headers,
  5454. [&](const char *data, uint64_t data_length) {
  5455. EXPECT_EQ(100U, data_length);
  5456. body.append(data, data_length);
  5457. return true;
  5458. });
  5459. ASSERT_TRUE(res);
  5460. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5461. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5462. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5463. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5464. "7890123456789012345678901234567890",
  5465. body);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. }
  5468. // TODO: How to enable zstd ??
  5469. TEST_F(ServerTest, MultipartFormDataZstd) {
  5470. UploadFormDataItems items = {
  5471. {"key1", "test", "", ""},
  5472. {"key2", "--abcdefg123", "", ""},
  5473. };
  5474. Headers headers;
  5475. headers.emplace("Accept-Encoding", "zstd");
  5476. cli_.set_compress(true);
  5477. auto res = cli_.Post("/compress-multipart", headers, items);
  5478. ASSERT_TRUE(res);
  5479. EXPECT_EQ(StatusCode::OK_200, res->status);
  5480. }
  5481. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5482. Headers headers;
  5483. headers.emplace("Accept-Encoding", "zstd");
  5484. cli_.set_compress(true);
  5485. auto res = cli_.Put(
  5486. "/put", headers, 3,
  5487. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5488. sink.os << "PUT";
  5489. return true;
  5490. },
  5491. "text/plain");
  5492. ASSERT_TRUE(res);
  5493. EXPECT_EQ(StatusCode::OK_200, res->status);
  5494. EXPECT_EQ("PUT", res->body);
  5495. }
  5496. // Pre-compression logging tests
  5497. TEST_F(ServerTest, PreCompressionLogging) {
  5498. // Test data for compression (matches the actual /compress endpoint content)
  5499. const std::string test_content =
  5500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5501. "3456789012345678901234567890";
  5502. // Variables to capture logging data
  5503. std::string pre_compression_body;
  5504. std::string pre_compression_content_type;
  5505. std::string pre_compression_content_encoding;
  5506. std::string post_compression_body;
  5507. std::string post_compression_content_type;
  5508. std::string post_compression_content_encoding;
  5509. // Set up pre-compression logger
  5510. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5511. const Response &res) {
  5512. pre_compression_body = res.body;
  5513. pre_compression_content_type = res.get_header_value("Content-Type");
  5514. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5515. });
  5516. // Set up post-compression logger
  5517. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5518. post_compression_body = res.body;
  5519. post_compression_content_type = res.get_header_value("Content-Type");
  5520. post_compression_content_encoding =
  5521. res.get_header_value("Content-Encoding");
  5522. });
  5523. // Test with gzip compression
  5524. Headers headers;
  5525. headers.emplace("Accept-Encoding", "gzip");
  5526. auto res = cli_.Get("/compress", headers);
  5527. // Verify response was compressed
  5528. ASSERT_TRUE(res);
  5529. EXPECT_EQ(StatusCode::OK_200, res->status);
  5530. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5531. // Verify pre-compression logger captured uncompressed content
  5532. EXPECT_EQ(test_content, pre_compression_body);
  5533. EXPECT_EQ("text/plain", pre_compression_content_type);
  5534. EXPECT_TRUE(pre_compression_content_encoding
  5535. .empty()); // No encoding header before compression
  5536. // Verify post-compression logger captured compressed content
  5537. EXPECT_NE(test_content,
  5538. post_compression_body); // Should be different after compression
  5539. EXPECT_EQ("text/plain", post_compression_content_type);
  5540. EXPECT_EQ("gzip", post_compression_content_encoding);
  5541. // Verify compressed content is smaller
  5542. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5543. }
  5544. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5545. const std::string test_content =
  5546. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5547. "3456789012345678901234567890";
  5548. std::string pre_compression_body;
  5549. std::string post_compression_body;
  5550. svr_.set_pre_compression_logger(
  5551. [&](const Request & /*req*/, const Response &res) {
  5552. pre_compression_body = res.body;
  5553. });
  5554. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5555. post_compression_body = res.body;
  5556. });
  5557. Headers headers;
  5558. headers.emplace("Accept-Encoding", "br");
  5559. auto res = cli_.Get("/compress", headers);
  5560. ASSERT_TRUE(res);
  5561. EXPECT_EQ(StatusCode::OK_200, res->status);
  5562. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5563. // Verify pre-compression content is uncompressed
  5564. EXPECT_EQ(test_content, pre_compression_body);
  5565. // Verify post-compression content is compressed
  5566. EXPECT_NE(test_content, post_compression_body);
  5567. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5568. }
  5569. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5570. const std::string test_content =
  5571. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5572. "3456789012345678901234567890";
  5573. std::string pre_compression_body;
  5574. std::string post_compression_body;
  5575. svr_.set_pre_compression_logger(
  5576. [&](const Request & /*req*/, const Response &res) {
  5577. pre_compression_body = res.body;
  5578. });
  5579. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5580. post_compression_body = res.body;
  5581. });
  5582. // Request without compression (use /nocompress endpoint)
  5583. Headers headers;
  5584. auto res = cli_.Get("/nocompress", headers);
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5588. // Pre-compression logger should not be called when no compression is applied
  5589. EXPECT_TRUE(
  5590. pre_compression_body.empty()); // Pre-compression logger not called
  5591. EXPECT_EQ(
  5592. test_content,
  5593. post_compression_body); // Post-compression logger captures final content
  5594. }
  5595. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5596. const std::string test_content =
  5597. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5598. "3456789012345678901234567890";
  5599. std::string pre_compression_body;
  5600. bool pre_logger_called = false;
  5601. // Set only pre-compression logger
  5602. svr_.set_pre_compression_logger(
  5603. [&](const Request & /*req*/, const Response &res) {
  5604. pre_compression_body = res.body;
  5605. pre_logger_called = true;
  5606. });
  5607. Headers headers;
  5608. headers.emplace("Accept-Encoding", "gzip");
  5609. auto res = cli_.Get("/compress", headers);
  5610. ASSERT_TRUE(res);
  5611. EXPECT_EQ(StatusCode::OK_200, res->status);
  5612. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5613. // Verify pre-compression logger was called
  5614. EXPECT_TRUE(pre_logger_called);
  5615. EXPECT_EQ(test_content, pre_compression_body);
  5616. }
  5617. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5618. {
  5619. // Test with Expect: 100-continue header - success case
  5620. // Server returns 100 Continue, client sends body, server returns 200 OK
  5621. Request req;
  5622. req.method = "POST";
  5623. req.path = "/post-large";
  5624. req.set_header("Expect", "100-continue");
  5625. req.body = LARGE_DATA;
  5626. Response res;
  5627. auto error = Error::Success;
  5628. cli_.set_keep_alive(true);
  5629. auto ret = cli_.send(req, res, error);
  5630. EXPECT_TRUE(ret);
  5631. EXPECT_EQ(StatusCode::OK_200, res.status);
  5632. EXPECT_EQ(LARGE_DATA, res.body);
  5633. }
  5634. {
  5635. // Test with Expect: 100-continue header - error case
  5636. // Client should not send the body when server returns an error
  5637. Request req;
  5638. req.method = "POST";
  5639. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5640. req.set_header("Expect", "100-continue");
  5641. req.body = LARGE_DATA;
  5642. Response res;
  5643. auto error = Error::Success;
  5644. auto start = std::chrono::high_resolution_clock::now();
  5645. cli_.set_keep_alive(true);
  5646. auto ret = cli_.send(req, res, error);
  5647. auto end = std::chrono::high_resolution_clock::now();
  5648. auto elapsed =
  5649. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5650. .count();
  5651. // With Expect: 100-continue, request completes successfully but with error
  5652. EXPECT_TRUE(ret);
  5653. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5654. EXPECT_EQ("close", res.get_header_value("Connection"));
  5655. EXPECT_FALSE(cli_.is_socket_open());
  5656. EXPECT_LE(elapsed, 200);
  5657. }
  5658. {
  5659. // Send an extra GET request to ensure error recovery without hanging
  5660. Request req;
  5661. req.method = "GET";
  5662. req.path = "/hi";
  5663. auto start = std::chrono::high_resolution_clock::now();
  5664. auto res = cli_.send(req);
  5665. auto end = std::chrono::high_resolution_clock::now();
  5666. auto elapsed =
  5667. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5668. .count();
  5669. ASSERT_TRUE(res);
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("Hello World!", res->body);
  5672. EXPECT_LE(elapsed, 100);
  5673. }
  5674. }
  5675. TEST(ZstdDecompressor, ChunkedDecompression) {
  5676. std::string data;
  5677. for (size_t i = 0; i < 32 * 1024; ++i) {
  5678. data.push_back(static_cast<char>('a' + i % 26));
  5679. }
  5680. std::string compressed_data;
  5681. {
  5682. httplib::detail::zstd_compressor compressor;
  5683. bool result = compressor.compress(
  5684. data.data(), data.size(),
  5685. /*last=*/true,
  5686. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5687. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5688. compressed_data_size);
  5689. return true;
  5690. });
  5691. ASSERT_TRUE(result);
  5692. }
  5693. std::string decompressed_data;
  5694. {
  5695. httplib::detail::zstd_decompressor decompressor;
  5696. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5697. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5698. size_t chunk_size = 130;
  5699. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5700. chunk_begin += chunk_size) {
  5701. size_t current_chunk_size =
  5702. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5703. bool result = decompressor.decompress(
  5704. compressed_data.data() + chunk_begin, current_chunk_size,
  5705. [&](const char *decompressed_data_chunk,
  5706. size_t decompressed_data_chunk_size) {
  5707. decompressed_data.insert(decompressed_data.size(),
  5708. decompressed_data_chunk,
  5709. decompressed_data_chunk_size);
  5710. return true;
  5711. });
  5712. ASSERT_TRUE(result);
  5713. }
  5714. }
  5715. ASSERT_EQ(data, decompressed_data);
  5716. }
  5717. TEST(ZstdDecompressor, Decompress) {
  5718. std::string original_text = "Compressed with ZSTD";
  5719. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5720. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5721. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5722. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5723. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5724. std::string decompressed_data;
  5725. {
  5726. httplib::detail::zstd_decompressor decompressor;
  5727. bool result = decompressor.decompress(
  5728. compressed_data.data(), compressed_data.size(),
  5729. [&](const char *decompressed_data_chunk,
  5730. size_t decompressed_data_chunk_size) {
  5731. decompressed_data.insert(decompressed_data.size(),
  5732. decompressed_data_chunk,
  5733. decompressed_data_chunk_size);
  5734. return true;
  5735. });
  5736. ASSERT_TRUE(result);
  5737. }
  5738. ASSERT_EQ(original_text, decompressed_data);
  5739. }
  5740. #endif
  5741. // Sends a raw request to a server listening at HOST:PORT.
  5742. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5743. std::string *resp = nullptr) {
  5744. auto error = Error::Success;
  5745. auto client_sock = detail::create_client_socket(
  5746. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5747. /*connection_timeout_sec=*/5, 0,
  5748. /*read_timeout_sec=*/5, 0,
  5749. /*write_timeout_sec=*/5, 0, std::string(), error);
  5750. if (client_sock == INVALID_SOCKET) { return false; }
  5751. auto ret = detail::process_client_socket(
  5752. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5753. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5754. if (req.size() !=
  5755. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5756. return false;
  5757. }
  5758. char buf[512];
  5759. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5760. while (line_reader.getline()) {
  5761. if (resp) { *resp += line_reader.ptr(); }
  5762. }
  5763. return true;
  5764. });
  5765. detail::close_socket(client_sock);
  5766. return ret;
  5767. }
  5768. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5769. Server svr;
  5770. std::string header_value;
  5771. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5772. header_value = req.get_header_value("foo");
  5773. res.set_content("ok", "text/plain");
  5774. });
  5775. thread t = thread([&] { svr.listen(HOST, PORT); });
  5776. auto se = detail::scope_exit([&] {
  5777. svr.stop();
  5778. t.join();
  5779. ASSERT_FALSE(svr.is_running());
  5780. });
  5781. svr.wait_until_ready();
  5782. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5783. // like characters are not treated the same - use vertical tab and escape.
  5784. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5785. "foo: \t \v bar \x1B\t \r\n"
  5786. "Connection: close\r\n"
  5787. "\r\n";
  5788. std::string res;
  5789. ASSERT_TRUE(send_request(5, req, &res));
  5790. EXPECT_EQ(header_value, "");
  5791. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5792. }
  5793. // Sends a raw request and verifies that there isn't a crash or exception.
  5794. static void test_raw_request(const std::string &req,
  5795. std::string *out = nullptr) {
  5796. Server svr;
  5797. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5798. res.set_content("ok", "text/plain");
  5799. });
  5800. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5801. res.set_content("ok", "text/plain");
  5802. });
  5803. svr.Get("/header_field_value_check",
  5804. [&](const Request & /*req*/, Response &res) {
  5805. res.set_content("ok", "text/plain");
  5806. });
  5807. // Server read timeout must be longer than the client read timeout for the
  5808. // bug to reproduce, probably to force the server to process a request
  5809. // without a trailing blank line.
  5810. const time_t client_read_timeout_sec = 1;
  5811. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5812. bool listen_thread_ok = false;
  5813. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5814. auto se = detail::scope_exit([&] {
  5815. svr.stop();
  5816. t.join();
  5817. ASSERT_FALSE(svr.is_running());
  5818. EXPECT_TRUE(listen_thread_ok);
  5819. });
  5820. svr.wait_until_ready();
  5821. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5822. }
  5823. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5824. // A certain header line causes an exception if the header property is parsed
  5825. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5826. test_raw_request(
  5827. "GET /hi HTTP/1.1\r\n"
  5828. " : "
  5829. " "
  5830. " ");
  5831. }
  5832. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5833. // A certain header line causes an exception if the header property *name* is
  5834. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5835. // greedy matcher and requires backtracking when there are a lot of ":"
  5836. // characters.
  5837. // This occurs with libc++ but not libstdc++.
  5838. test_raw_request(
  5839. "GET /hi HTTP/1.1\r\n"
  5840. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5841. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5842. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5843. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5844. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5845. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5846. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5847. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5848. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5849. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5850. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5851. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5852. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5853. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5854. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5855. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5856. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5857. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5858. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5859. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5860. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5861. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5862. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5863. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5864. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5865. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5866. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5867. "&&&%%%");
  5868. }
  5869. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5870. // Make sure this doesn't crash the server.
  5871. // In a previous version of the header line regex, the "\r" rendered the line
  5872. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5873. // a new position where the leading white space ended and the field value
  5874. // began.
  5875. // The crash occurs with libc++ but not libstdc++.
  5876. test_raw_request("GET /hi HTTP/1.1\r\n"
  5877. "a:" +
  5878. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5879. "\r\n"
  5880. "\r\n");
  5881. }
  5882. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5883. std::string out;
  5884. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5885. "Content-Type: text/plain\r\n"
  5886. "Transfer-Encoding: chunked\r\n"
  5887. "\r\n"
  5888. "nothex\r\n",
  5889. &out);
  5890. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5891. }
  5892. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5893. std::string out;
  5894. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5895. "Content-Type: text/plain\r\n"
  5896. "Transfer-Encoding: chunked\r\n"
  5897. "\r\n"
  5898. "3\r\n"
  5899. "xyz\r\n"
  5900. "NaN\r\n",
  5901. &out);
  5902. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5903. }
  5904. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5905. std::string out;
  5906. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5907. "Content-Type: text/plain\r\n"
  5908. "Transfer-Encoding: chunked\r\n"
  5909. "\r\n"
  5910. // Length is too large for 64 bits.
  5911. "1ffffffffffffffff\r\n"
  5912. "xyz\r\n",
  5913. &out);
  5914. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5915. }
  5916. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5917. test_raw_request("GET /hi HTTP/1.1\r\n"
  5918. "Content-Type: text/plain\r\n\r");
  5919. }
  5920. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5921. std::string out;
  5922. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5923. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5924. }
  5925. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5926. Server svr;
  5927. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5928. EXPECT_TRUE(!req.remote_addr.empty());
  5929. });
  5930. thread t = thread([&] { svr.listen(HOST, PORT); });
  5931. auto se = detail::scope_exit([&] {
  5932. svr.stop();
  5933. t.join();
  5934. ASSERT_FALSE(svr.is_running());
  5935. });
  5936. svr.wait_until_ready();
  5937. // Send an invalid request line to trigger Bad Request
  5938. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5939. std::string out;
  5940. ASSERT_TRUE(send_request(5, bad_req, &out));
  5941. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5942. }
  5943. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5944. std::string out;
  5945. std::string request(
  5946. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5947. test_raw_request(request, &out);
  5948. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5949. }
  5950. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5951. std::string out;
  5952. std::string request(
  5953. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5954. test_raw_request(request, &out);
  5955. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5956. }
  5957. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5958. std::string out;
  5959. std::string request(
  5960. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5961. test_raw_request(request, &out);
  5962. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5963. }
  5964. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5965. std::string out;
  5966. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5967. "Test: \r\n\r\n",
  5968. &out);
  5969. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5970. }
  5971. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5972. Server svr;
  5973. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5974. res.set_header("Cache-Control", "no-cache");
  5975. res.set_chunked_content_provider(
  5976. "text/event-stream", [](size_t offset, DataSink &sink) {
  5977. std::string s = "data:";
  5978. s += std::to_string(offset);
  5979. s += "\n\n";
  5980. auto ret = sink.write(s.data(), s.size());
  5981. EXPECT_TRUE(ret);
  5982. std::this_thread::sleep_for(std::chrono::seconds(1));
  5983. return true;
  5984. });
  5985. });
  5986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5987. svr.wait_until_ready();
  5988. Client client(HOST, PORT);
  5989. const Headers headers = {{"Accept", "text/event-stream"}};
  5990. auto get_thread = std::thread([&client, &headers]() {
  5991. auto res = client.Get(
  5992. "/events", headers,
  5993. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5994. });
  5995. auto se = detail::scope_exit([&] {
  5996. svr.stop();
  5997. get_thread.join();
  5998. listen_thread.join();
  5999. ASSERT_FALSE(svr.is_running());
  6000. });
  6001. // Give GET time to get a few messages.
  6002. std::this_thread::sleep_for(std::chrono::seconds(2));
  6003. }
  6004. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  6005. httplib::Server svr;
  6006. svr.Post("/hi",
  6007. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  6008. res.status = StatusCode::OK_200;
  6009. });
  6010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. auto res = cli.Post("/hi", "data", "text/plain");
  6014. ASSERT_TRUE(res);
  6015. EXPECT_EQ(StatusCode::OK_200, res->status);
  6016. svr.stop();
  6017. thread.join();
  6018. ASSERT_FALSE(svr.is_running());
  6019. res = cli.Post("/hi", "data", "text/plain");
  6020. ASSERT_FALSE(res);
  6021. }
  6022. TEST(ServerStopTest, ListenFailure) {
  6023. Server svr;
  6024. auto t = thread([&]() {
  6025. auto ret = svr.listen("????", PORT);
  6026. EXPECT_FALSE(ret);
  6027. });
  6028. svr.wait_until_ready();
  6029. svr.stop();
  6030. t.join();
  6031. }
  6032. TEST(ServerStopTest, Decommision) {
  6033. Server svr;
  6034. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  6035. for (int i = 0; i < 4; i++) {
  6036. auto is_even = !(i % 2);
  6037. std::thread t{[&] {
  6038. try {
  6039. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  6040. if (is_even) {
  6041. throw std::runtime_error("Some thing that happens to go wrong.");
  6042. }
  6043. svr.listen(HOST, PORT);
  6044. } catch (...) { svr.decommission(); }
  6045. }};
  6046. svr.wait_until_ready();
  6047. // Server is up
  6048. {
  6049. Client cli(HOST, PORT);
  6050. auto res = cli.Get("/hi");
  6051. if (is_even) {
  6052. EXPECT_FALSE(res);
  6053. } else {
  6054. EXPECT_TRUE(res);
  6055. EXPECT_EQ("hi...", res->body);
  6056. }
  6057. }
  6058. svr.stop();
  6059. t.join();
  6060. // Server is down...
  6061. {
  6062. Client cli(HOST, PORT);
  6063. auto res = cli.Get("/hi");
  6064. EXPECT_FALSE(res);
  6065. }
  6066. }
  6067. }
  6068. // Helper function for string body upload progress tests
  6069. template <typename SetupHandler, typename ClientCall>
  6070. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  6071. ClientCall &&client_call,
  6072. const string &body) {
  6073. Server svr;
  6074. setup_handler(svr);
  6075. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6076. auto se = detail::scope_exit([&] {
  6077. svr.stop();
  6078. t.join();
  6079. });
  6080. svr.wait_until_ready();
  6081. Client cli(HOST, PORT);
  6082. vector<uint64_t> progress_values;
  6083. bool progress_called = false;
  6084. auto res =
  6085. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6086. progress_values.push_back(current);
  6087. progress_called = true;
  6088. return true;
  6089. });
  6090. ASSERT_TRUE(res);
  6091. EXPECT_EQ(200, res->status);
  6092. EXPECT_TRUE(progress_called);
  6093. }
  6094. TEST(UploadProgressTest, PostStringBodyBasic) {
  6095. TestStringBodyUploadProgress(
  6096. [](Server &svr) {
  6097. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6098. res.set_content("received", "text/plain");
  6099. });
  6100. },
  6101. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6102. return cli.Post("/test", body, "text/plain", progress_callback);
  6103. },
  6104. "test data for upload progress");
  6105. }
  6106. TEST(UploadProgressTest, PutStringBodyBasic) {
  6107. TestStringBodyUploadProgress(
  6108. [](Server &svr) {
  6109. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6110. res.set_content("put received", "text/plain");
  6111. });
  6112. },
  6113. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6114. return cli.Put("/test", body, "text/plain", progress_callback);
  6115. },
  6116. "put test data for upload progress");
  6117. }
  6118. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6119. TestStringBodyUploadProgress(
  6120. [](Server &svr) {
  6121. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6122. res.set_content("patch received", "text/plain");
  6123. });
  6124. },
  6125. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6126. return cli.Patch("/test", body, "text/plain", progress_callback);
  6127. },
  6128. "patch test data for upload progress");
  6129. }
  6130. // Helper function for content provider upload progress tests
  6131. template <typename SetupHandler, typename ClientCall>
  6132. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6133. ClientCall &&client_call) {
  6134. Server svr;
  6135. setup_handler(svr);
  6136. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6137. auto se = detail::scope_exit([&] {
  6138. svr.stop();
  6139. t.join();
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli(HOST, PORT);
  6143. vector<uint64_t> progress_values;
  6144. auto res =
  6145. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(res);
  6150. EXPECT_EQ(200, res->status);
  6151. EXPECT_FALSE(progress_values.empty());
  6152. }
  6153. TEST(UploadProgressTest, PostContentProviderProgress) {
  6154. TestContentProviderUploadProgress(
  6155. [](Server &svr) {
  6156. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6157. res.set_content("provider received", "text/plain");
  6158. });
  6159. },
  6160. [](Client &cli, UploadProgress progress_callback) {
  6161. return cli.Post(
  6162. "/test", 10,
  6163. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6164. sink.os << "test data";
  6165. return true;
  6166. },
  6167. "text/plain", progress_callback);
  6168. });
  6169. }
  6170. // Helper function for multipart upload progress tests
  6171. template <typename SetupHandler, typename ClientCall>
  6172. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6173. ClientCall &&client_call,
  6174. const string &endpoint) {
  6175. Server svr;
  6176. setup_handler(svr);
  6177. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6178. auto se = detail::scope_exit([&] {
  6179. svr.stop();
  6180. t.join();
  6181. });
  6182. svr.wait_until_ready();
  6183. Client cli(HOST, PORT);
  6184. vector<uint64_t> progress_values;
  6185. UploadFormDataItems items = {
  6186. {"field1", "value1", "", ""},
  6187. {"field2", "longer value for progress tracking test", "", ""},
  6188. {"file1", "file content data for upload progress", "test.txt",
  6189. "text/plain"}};
  6190. auto res = client_call(cli, endpoint, items,
  6191. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6192. progress_values.push_back(current);
  6193. return true;
  6194. });
  6195. ASSERT_TRUE(res);
  6196. EXPECT_EQ(200, res->status);
  6197. EXPECT_FALSE(progress_values.empty());
  6198. }
  6199. TEST(UploadProgressTest, PostMultipartProgress) {
  6200. TestMultipartUploadProgress(
  6201. [](Server &svr) {
  6202. svr.Post("/multipart", [](const Request &req, Response &res) {
  6203. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6204. res.set_content("multipart received", "text/plain");
  6205. });
  6206. },
  6207. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6208. UploadProgress progress_callback) {
  6209. return cli.Post(endpoint, items, progress_callback);
  6210. },
  6211. "/multipart");
  6212. }
  6213. // Helper function for basic download progress tests
  6214. template <typename SetupHandler, typename ClientCall>
  6215. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6216. ClientCall &&client_call, const string &endpoint,
  6217. size_t expected_content_size) {
  6218. Server svr;
  6219. setup_handler(svr);
  6220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6221. auto se = detail::scope_exit([&] {
  6222. svr.stop();
  6223. t.join();
  6224. });
  6225. svr.wait_until_ready();
  6226. Client cli(HOST, PORT);
  6227. vector<uint64_t> progress_values;
  6228. auto res = client_call(cli, endpoint,
  6229. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6230. progress_values.push_back(current);
  6231. return true;
  6232. });
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(200, res->status);
  6235. EXPECT_FALSE(progress_values.empty());
  6236. EXPECT_EQ(expected_content_size, res->body.size());
  6237. }
  6238. TEST(DownloadProgressTest, GetBasic) {
  6239. TestBasicDownloadProgress(
  6240. [](Server &svr) {
  6241. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6242. string content(1000, 'D');
  6243. res.set_content(content, "text/plain");
  6244. });
  6245. },
  6246. [](Client &cli, const string &endpoint,
  6247. DownloadProgress progress_callback) {
  6248. return cli.Get(endpoint, progress_callback);
  6249. },
  6250. "/download", 1000u);
  6251. }
  6252. // Helper function for content receiver download progress tests
  6253. template <typename SetupHandler, typename ClientCall>
  6254. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6255. ClientCall &&client_call,
  6256. const string &endpoint,
  6257. size_t expected_content_size) {
  6258. Server svr;
  6259. setup_handler(svr);
  6260. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6261. auto se = detail::scope_exit([&] {
  6262. svr.stop();
  6263. t.join();
  6264. });
  6265. svr.wait_until_ready();
  6266. Client cli(HOST, PORT);
  6267. vector<uint64_t> progress_values;
  6268. string received_body;
  6269. auto res = client_call(
  6270. cli, endpoint,
  6271. [&](const char *data, size_t data_length) -> bool {
  6272. received_body.append(data, data_length);
  6273. return true;
  6274. },
  6275. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6276. progress_values.push_back(current);
  6277. return true;
  6278. });
  6279. ASSERT_TRUE(res);
  6280. EXPECT_EQ(200, res->status);
  6281. EXPECT_FALSE(progress_values.empty());
  6282. EXPECT_EQ(expected_content_size, received_body.size());
  6283. EXPECT_TRUE(res->body.empty());
  6284. }
  6285. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6286. TestContentReceiverDownloadProgress(
  6287. [](Server &svr) {
  6288. svr.Get("/download-receiver",
  6289. [](const Request & /*req*/, Response &res) {
  6290. string content(2000, 'R');
  6291. res.set_content(content, "text/plain");
  6292. });
  6293. },
  6294. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6295. DownloadProgress progress_callback) {
  6296. return cli.Get(endpoint, content_receiver, progress_callback);
  6297. },
  6298. "/download-receiver", 2000u);
  6299. }
  6300. TEST(StreamingTest, NoContentLengthStreaming) {
  6301. Server svr;
  6302. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6303. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6304. if (offset < 6) {
  6305. sink.os << (offset < 3 ? "a" : "b");
  6306. } else {
  6307. sink.done();
  6308. }
  6309. return true;
  6310. });
  6311. });
  6312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6313. auto listen_se = detail::scope_exit([&] {
  6314. svr.stop();
  6315. listen_thread.join();
  6316. ASSERT_FALSE(svr.is_running());
  6317. });
  6318. svr.wait_until_ready();
  6319. Client client(HOST, PORT);
  6320. auto get_thread = std::thread([&client]() {
  6321. std::string s;
  6322. auto res =
  6323. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6324. s += std::string(data, len);
  6325. return true;
  6326. });
  6327. ASSERT_TRUE(res);
  6328. EXPECT_EQ(StatusCode::OK_200, res->status);
  6329. EXPECT_EQ("aaabbb", s);
  6330. });
  6331. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6332. // Give GET time to get a few messages.
  6333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6334. }
  6335. TEST(MountTest, Unmount) {
  6336. Server svr;
  6337. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6338. auto se = detail::scope_exit([&] {
  6339. svr.stop();
  6340. listen_thread.join();
  6341. ASSERT_FALSE(svr.is_running());
  6342. });
  6343. svr.wait_until_ready();
  6344. Client cli("localhost", PORT);
  6345. svr.set_mount_point("/mount2", "./www2");
  6346. auto res = cli.Get("/");
  6347. ASSERT_TRUE(res);
  6348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6349. res = cli.Get("/mount2/dir/test.html");
  6350. ASSERT_TRUE(res);
  6351. EXPECT_EQ(StatusCode::OK_200, res->status);
  6352. svr.set_mount_point("/", "./www");
  6353. res = cli.Get("/dir/");
  6354. ASSERT_TRUE(res);
  6355. EXPECT_EQ(StatusCode::OK_200, res->status);
  6356. svr.remove_mount_point("/");
  6357. res = cli.Get("/dir/");
  6358. ASSERT_TRUE(res);
  6359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6360. svr.remove_mount_point("/mount2");
  6361. res = cli.Get("/mount2/dir/test.html");
  6362. ASSERT_TRUE(res);
  6363. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6364. }
  6365. TEST(MountTest, Redicect) {
  6366. Server svr;
  6367. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6368. auto se = detail::scope_exit([&] {
  6369. svr.stop();
  6370. listen_thread.join();
  6371. ASSERT_FALSE(svr.is_running());
  6372. });
  6373. svr.set_mount_point("/", "./www");
  6374. svr.wait_until_ready();
  6375. Client cli("localhost", PORT);
  6376. auto res = cli.Get("/dir/");
  6377. ASSERT_TRUE(res);
  6378. EXPECT_EQ(StatusCode::OK_200, res->status);
  6379. res = cli.Get("/dir");
  6380. ASSERT_TRUE(res);
  6381. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6382. res = cli.Get("/file");
  6383. ASSERT_TRUE(res);
  6384. EXPECT_EQ(StatusCode::OK_200, res->status);
  6385. res = cli.Get("/file/");
  6386. ASSERT_TRUE(res);
  6387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6388. cli.set_follow_location(true);
  6389. res = cli.Get("/dir");
  6390. ASSERT_TRUE(res);
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. }
  6393. TEST(MountTest, MultibytesPathName) {
  6394. Server svr;
  6395. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6396. auto se = detail::scope_exit([&] {
  6397. svr.stop();
  6398. listen_thread.join();
  6399. ASSERT_FALSE(svr.is_running());
  6400. });
  6401. svr.set_mount_point("/", "./www");
  6402. svr.wait_until_ready();
  6403. Client cli("localhost", PORT);
  6404. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6405. ASSERT_TRUE(res);
  6406. EXPECT_EQ(StatusCode::OK_200, res->status);
  6407. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6408. }
  6409. TEST(KeepAliveTest, ReadTimeout) {
  6410. Server svr;
  6411. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6412. std::this_thread::sleep_for(std::chrono::seconds(2));
  6413. res.set_content("a", "text/plain");
  6414. });
  6415. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6416. res.set_content("b", "text/plain");
  6417. });
  6418. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6419. auto se = detail::scope_exit([&] {
  6420. svr.stop();
  6421. listen_thread.join();
  6422. ASSERT_FALSE(svr.is_running());
  6423. });
  6424. svr.wait_until_ready();
  6425. Client cli("localhost", PORT);
  6426. cli.set_keep_alive(true);
  6427. cli.set_read_timeout(std::chrono::seconds(1));
  6428. auto resa = cli.Get("/a");
  6429. ASSERT_FALSE(resa);
  6430. EXPECT_EQ(Error::Read, resa.error());
  6431. auto resb = cli.Get("/b");
  6432. ASSERT_TRUE(resb);
  6433. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6434. EXPECT_EQ("b", resb->body);
  6435. }
  6436. TEST(KeepAliveTest, MaxCount) {
  6437. size_t keep_alive_max_count = 3;
  6438. Server svr;
  6439. svr.set_keep_alive_max_count(keep_alive_max_count);
  6440. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6441. res.set_content("Hello World!", "text/plain");
  6442. });
  6443. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6444. auto se = detail::scope_exit([&] {
  6445. svr.stop();
  6446. listen_thread.join();
  6447. ASSERT_FALSE(svr.is_running());
  6448. });
  6449. svr.wait_until_ready();
  6450. Client cli(HOST, PORT);
  6451. cli.set_keep_alive(true);
  6452. for (size_t i = 0; i < 5; i++) {
  6453. auto result = cli.Get("/hi");
  6454. ASSERT_TRUE(result);
  6455. EXPECT_EQ(StatusCode::OK_200, result->status);
  6456. if (i == keep_alive_max_count - 1) {
  6457. EXPECT_EQ("close", result->get_header_value("Connection"));
  6458. } else {
  6459. EXPECT_FALSE(result->has_header("Connection"));
  6460. }
  6461. }
  6462. }
  6463. TEST(KeepAliveTest, Issue1041) {
  6464. Server svr;
  6465. svr.set_keep_alive_timeout(3);
  6466. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6467. res.set_content("Hello World!", "text/plain");
  6468. });
  6469. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6470. auto se = detail::scope_exit([&] {
  6471. svr.stop();
  6472. listen_thread.join();
  6473. ASSERT_FALSE(svr.is_running());
  6474. });
  6475. svr.wait_until_ready();
  6476. Client cli(HOST, PORT);
  6477. cli.set_keep_alive(true);
  6478. auto result = cli.Get("/hi");
  6479. ASSERT_TRUE(result);
  6480. EXPECT_EQ(StatusCode::OK_200, result->status);
  6481. std::this_thread::sleep_for(std::chrono::seconds(5));
  6482. result = cli.Get("/hi");
  6483. ASSERT_TRUE(result);
  6484. EXPECT_EQ(StatusCode::OK_200, result->status);
  6485. }
  6486. TEST(KeepAliveTest, Issue1959) {
  6487. Server svr;
  6488. svr.set_keep_alive_timeout(5);
  6489. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6490. res.set_content("a", "text/plain");
  6491. });
  6492. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6493. auto se = detail::scope_exit([&] {
  6494. if (!svr.is_running()) return;
  6495. svr.stop();
  6496. listen_thread.join();
  6497. ASSERT_FALSE(svr.is_running());
  6498. });
  6499. svr.wait_until_ready();
  6500. Client cli("localhost", PORT);
  6501. cli.set_keep_alive(true);
  6502. using namespace std::chrono;
  6503. auto start = steady_clock::now();
  6504. cli.Get("/a");
  6505. svr.stop();
  6506. listen_thread.join();
  6507. auto end = steady_clock::now();
  6508. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6509. EXPECT_LT(elapsed, 5000);
  6510. }
  6511. #ifdef CPPHTTPLIB_SSL_ENABLED
  6512. TEST(KeepAliveTest, SSLClientReconnection) {
  6513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6514. ASSERT_TRUE(svr.is_valid());
  6515. svr.set_keep_alive_timeout(1);
  6516. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6517. res.set_content("Hello World!", "text/plain");
  6518. });
  6519. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6520. auto se = detail::scope_exit([&] {
  6521. svr.stop();
  6522. listen_thread.join();
  6523. ASSERT_FALSE(svr.is_running());
  6524. });
  6525. svr.wait_until_ready();
  6526. SSLClient cli(HOST, PORT);
  6527. cli.enable_server_certificate_verification(false);
  6528. cli.set_keep_alive(true);
  6529. auto result = cli.Get("/hi");
  6530. ASSERT_TRUE(result);
  6531. EXPECT_EQ(StatusCode::OK_200, result->status);
  6532. result = cli.Get("/hi");
  6533. ASSERT_TRUE(result);
  6534. EXPECT_EQ(StatusCode::OK_200, result->status);
  6535. std::this_thread::sleep_for(std::chrono::seconds(2));
  6536. // Recoonect
  6537. result = cli.Get("/hi");
  6538. ASSERT_TRUE(result);
  6539. EXPECT_EQ(StatusCode::OK_200, result->status);
  6540. result = cli.Get("/hi");
  6541. ASSERT_TRUE(result);
  6542. EXPECT_EQ(StatusCode::OK_200, result->status);
  6543. }
  6544. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6546. ASSERT_TRUE(svr.is_valid());
  6547. svr.set_keep_alive_timeout(1);
  6548. std::string content = "reconnect";
  6549. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6550. res.set_content("Hello World!", "text/plain");
  6551. });
  6552. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6553. auto se = detail::scope_exit([&] {
  6554. svr.stop();
  6555. listen_thread.join();
  6556. ASSERT_FALSE(svr.is_running());
  6557. });
  6558. svr.wait_until_ready();
  6559. SSLClient cli(HOST, PORT);
  6560. cli.enable_server_certificate_verification(false);
  6561. cli.set_keep_alive(true);
  6562. auto result = cli.Post(
  6563. "/hi", content.size(),
  6564. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6565. sink.write(content.c_str(), content.size());
  6566. return true;
  6567. },
  6568. "text/plain");
  6569. ASSERT_TRUE(result);
  6570. EXPECT_EQ(200, result->status);
  6571. std::this_thread::sleep_for(std::chrono::seconds(2));
  6572. // Recoonect
  6573. result = cli.Post(
  6574. "/hi", content.size(),
  6575. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6576. sink.write(content.c_str(), content.size());
  6577. return true;
  6578. },
  6579. "text/plain");
  6580. ASSERT_TRUE(result);
  6581. EXPECT_EQ(200, result->status);
  6582. result = cli.Post(
  6583. "/hi", content.size(),
  6584. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6585. sink.write(content.c_str(), content.size());
  6586. return true;
  6587. },
  6588. "text/plain");
  6589. ASSERT_TRUE(result);
  6590. EXPECT_EQ(200, result->status);
  6591. }
  6592. #endif
  6593. #ifdef CPPHTTPLIB_SSL_ENABLED
  6594. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6595. using namespace httplib::detail::tls;
  6596. {
  6597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6598. ASSERT_TRUE(svr.is_valid());
  6599. svr.Get("/sni", [&](const Request &req, Response &res) {
  6600. std::string expected;
  6601. if (req.ssl) {
  6602. // Use backend-agnostic TLS API to get SNI
  6603. if (const char *sni = tls_get_sni(const_cast<void *>(req.ssl))) {
  6604. expected = sni;
  6605. }
  6606. }
  6607. EXPECT_EQ(expected, req.get_param_value("expected"));
  6608. res.set_content("ok", "text/plain");
  6609. });
  6610. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6611. auto se = detail::scope_exit([&] {
  6612. svr.stop();
  6613. listen_thread.join();
  6614. ASSERT_FALSE(svr.is_running());
  6615. });
  6616. svr.wait_until_ready();
  6617. {
  6618. SSLClient cli("localhost", PORT);
  6619. cli.enable_server_certificate_verification(false);
  6620. auto res = cli.Get("/sni?expected=localhost");
  6621. ASSERT_TRUE(res);
  6622. }
  6623. {
  6624. SSLClient cli("::1", PORT);
  6625. cli.enable_server_certificate_verification(false);
  6626. auto res = cli.Get("/sni?expected=");
  6627. // NOTE: This may fail if the server is listening on IPv4 only
  6628. // (e.g., when localhost resolves to 127.0.0.1 only)
  6629. if (res) {
  6630. EXPECT_EQ(StatusCode::OK_200, res->status);
  6631. } else {
  6632. EXPECT_EQ(Error::Connection, res.error());
  6633. }
  6634. }
  6635. }
  6636. }
  6637. #endif
  6638. TEST(ClientProblemDetectionTest, ContentProvider) {
  6639. Server svr;
  6640. size_t content_length = 1024 * 1024;
  6641. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6642. res.set_content_provider(
  6643. content_length, "text/plain",
  6644. [&](size_t offset, size_t length, DataSink &sink) {
  6645. auto out_len = std::min(length, static_cast<size_t>(1024));
  6646. std::string out(out_len, '@');
  6647. sink.write(out.data(), out_len);
  6648. return offset < 4096;
  6649. },
  6650. [](bool success) { ASSERT_FALSE(success); });
  6651. });
  6652. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6653. res.set_content_provider(
  6654. 0, "text/plain",
  6655. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6656. EXPECT_TRUE(false);
  6657. return true;
  6658. },
  6659. [](bool success) { ASSERT_FALSE(success); });
  6660. });
  6661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6662. auto se = detail::scope_exit([&] {
  6663. svr.stop();
  6664. listen_thread.join();
  6665. ASSERT_FALSE(svr.is_running());
  6666. });
  6667. svr.wait_until_ready();
  6668. Client cli("localhost", PORT);
  6669. {
  6670. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6671. size_t /*data_length*/) { return false; });
  6672. ASSERT_FALSE(res);
  6673. }
  6674. {
  6675. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6676. size_t /*data_length*/) { return false; });
  6677. ASSERT_TRUE(res);
  6678. }
  6679. }
  6680. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6681. Server svr;
  6682. svr.set_error_handler([](Request const &, Response &res) -> void {
  6683. res.set_chunked_content_provider(
  6684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6685. sink.os << "hello";
  6686. sink.os << "world";
  6687. sink.done();
  6688. return true;
  6689. });
  6690. });
  6691. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6692. auto se = detail::scope_exit([&] {
  6693. svr.stop();
  6694. listen_thread.join();
  6695. ASSERT_FALSE(svr.is_running());
  6696. });
  6697. svr.wait_until_ready();
  6698. Client cli("localhost", PORT);
  6699. auto res = cli.Get("/");
  6700. ASSERT_TRUE(res);
  6701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6702. EXPECT_EQ("helloworld", res->body);
  6703. }
  6704. TEST(LongPollingTest, ClientCloseDetection) {
  6705. Server svr;
  6706. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6707. res.set_chunked_content_provider(
  6708. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6709. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6710. sink.os << "hello";
  6711. auto count = 10;
  6712. while (count > 0 && sink.is_writable()) {
  6713. this_thread::sleep_for(chrono::milliseconds(10));
  6714. count--;
  6715. }
  6716. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6717. return true;
  6718. });
  6719. });
  6720. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6721. auto se = detail::scope_exit([&] {
  6722. svr.stop();
  6723. listen_thread.join();
  6724. ASSERT_FALSE(svr.is_running());
  6725. });
  6726. svr.wait_until_ready();
  6727. Client cli("localhost", PORT);
  6728. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6729. EXPECT_EQ("hello", string(data, data_length));
  6730. return false; // close the socket immediately.
  6731. });
  6732. ASSERT_FALSE(res);
  6733. }
  6734. TEST(GetWithParametersTest, GetWithParameters) {
  6735. Server svr;
  6736. svr.Get("/", [&](const Request &req, Response &) {
  6737. EXPECT_EQ("world", req.get_param_value("hello"));
  6738. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6739. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6740. });
  6741. svr.Get("/params", [&](const Request &req, Response &) {
  6742. EXPECT_EQ("world", req.get_param_value("hello"));
  6743. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6744. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6745. });
  6746. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6747. EXPECT_EQ("resource-id", req.matches[1]);
  6748. EXPECT_EQ("foo", req.get_param_value("param1"));
  6749. EXPECT_EQ("bar", req.get_param_value("param2"));
  6750. });
  6751. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6752. EXPECT_EQ("user-id", req.path_params.at("id"));
  6753. EXPECT_EQ("foo", req.get_param_value("param1"));
  6754. EXPECT_EQ("bar", req.get_param_value("param2"));
  6755. });
  6756. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6757. auto se = detail::scope_exit([&] {
  6758. svr.stop();
  6759. listen_thread.join();
  6760. ASSERT_FALSE(svr.is_running());
  6761. });
  6762. svr.wait_until_ready();
  6763. {
  6764. Client cli(HOST, PORT);
  6765. Params params;
  6766. params.emplace("hello", "world");
  6767. params.emplace("hello2", "world2");
  6768. params.emplace("hello3", "world3");
  6769. auto res = cli.Get("/", params, Headers{});
  6770. ASSERT_TRUE(res);
  6771. EXPECT_EQ(StatusCode::OK_200, res->status);
  6772. }
  6773. {
  6774. Client cli(HOST, PORT);
  6775. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6776. ASSERT_TRUE(res);
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. }
  6779. {
  6780. Client cli(HOST, PORT);
  6781. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6782. ASSERT_TRUE(res);
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. }
  6785. {
  6786. Client cli(HOST, PORT);
  6787. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6788. ASSERT_TRUE(res);
  6789. EXPECT_EQ(StatusCode::OK_200, res->status);
  6790. }
  6791. }
  6792. TEST(GetWithParametersTest, GetWithParameters2) {
  6793. Server svr;
  6794. svr.Get("/", [&](const Request &req, Response &res) {
  6795. auto text = req.get_param_value("hello");
  6796. res.set_content(text, "text/plain");
  6797. });
  6798. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6799. auto se = detail::scope_exit([&] {
  6800. svr.stop();
  6801. listen_thread.join();
  6802. ASSERT_FALSE(svr.is_running());
  6803. });
  6804. svr.wait_until_ready();
  6805. Client cli("localhost", PORT);
  6806. Params params;
  6807. params.emplace("hello", "world");
  6808. std::string body;
  6809. auto res = cli.Get("/", params, Headers{},
  6810. [&](const char *data, size_t data_length) {
  6811. body.append(data, data_length);
  6812. return true;
  6813. });
  6814. ASSERT_TRUE(res);
  6815. EXPECT_EQ(StatusCode::OK_200, res->status);
  6816. EXPECT_EQ("world", body);
  6817. }
  6818. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6819. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6820. auto host = "httpcan.org";
  6821. auto path = std::string{"/range/32"};
  6822. #else
  6823. auto host = "nghttp2.org";
  6824. auto path = std::string{"/httpbin/range/32"};
  6825. #endif
  6826. #ifdef CPPHTTPLIB_SSL_ENABLED
  6827. SSLClient cli(host);
  6828. #else
  6829. Client cli(host);
  6830. #endif
  6831. cli.set_default_headers({make_range_header({{1, 10}})});
  6832. cli.set_connection_timeout(5);
  6833. {
  6834. auto res = cli.Get(path);
  6835. ASSERT_TRUE(res);
  6836. EXPECT_EQ("bcdefghijk", res->body);
  6837. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6838. }
  6839. {
  6840. auto res = cli.Get(path);
  6841. ASSERT_TRUE(res);
  6842. EXPECT_EQ("bcdefghijk", res->body);
  6843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6844. }
  6845. }
  6846. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6847. Server svr;
  6848. svr.set_default_headers({{"Hello", "World"}});
  6849. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6850. res.set_content("ok", "text/plain");
  6851. });
  6852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6853. auto se = detail::scope_exit([&] {
  6854. svr.stop();
  6855. listen_thread.join();
  6856. ASSERT_FALSE(svr.is_running());
  6857. });
  6858. svr.wait_until_ready();
  6859. Client cli("localhost", PORT);
  6860. auto res = cli.Get("/");
  6861. ASSERT_TRUE(res);
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("ok", res->body);
  6864. EXPECT_EQ("World", res->get_header_value("Hello"));
  6865. }
  6866. #ifdef CPPHTTPLIB_SSL_ENABLED
  6867. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6869. ASSERT_TRUE(svr.is_valid());
  6870. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6871. std::this_thread::sleep_for(std::chrono::seconds(2));
  6872. res.set_content("a", "text/plain");
  6873. });
  6874. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6875. res.set_content("b", "text/plain");
  6876. });
  6877. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6878. auto se = detail::scope_exit([&] {
  6879. svr.stop();
  6880. listen_thread.join();
  6881. ASSERT_FALSE(svr.is_running());
  6882. });
  6883. svr.wait_until_ready();
  6884. SSLClient cli("localhost", PORT);
  6885. cli.enable_server_certificate_verification(false);
  6886. cli.set_keep_alive(true);
  6887. cli.set_read_timeout(std::chrono::seconds(1));
  6888. auto resa = cli.Get("/a");
  6889. ASSERT_TRUE(!resa);
  6890. EXPECT_EQ(Error::Read, resa.error());
  6891. auto resb = cli.Get("/b");
  6892. ASSERT_TRUE(resb);
  6893. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6894. EXPECT_EQ("b", resb->body);
  6895. }
  6896. #endif
  6897. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6898. protected:
  6899. ServerTestWithAI_PASSIVE()
  6900. : cli_(HOST, PORT)
  6901. #ifdef CPPHTTPLIB_SSL_ENABLED
  6902. ,
  6903. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6904. #endif
  6905. {
  6906. #ifdef CPPHTTPLIB_SSL_ENABLED
  6907. cli_.enable_server_certificate_verification(false);
  6908. #endif
  6909. }
  6910. virtual void SetUp() {
  6911. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6912. res.set_content("Hello World!", "text/plain");
  6913. });
  6914. t_ = thread(
  6915. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6916. svr_.wait_until_ready();
  6917. }
  6918. virtual void TearDown() {
  6919. svr_.stop();
  6920. t_.join();
  6921. }
  6922. #ifdef CPPHTTPLIB_SSL_ENABLED
  6923. SSLClient cli_;
  6924. SSLServer svr_;
  6925. #else
  6926. Client cli_;
  6927. Server svr_;
  6928. #endif
  6929. thread t_;
  6930. };
  6931. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6932. auto res = cli_.Get("/hi");
  6933. ASSERT_TRUE(res);
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6936. EXPECT_EQ("Hello World!", res->body);
  6937. }
  6938. class ServerUpDownTest : public ::testing::Test {
  6939. protected:
  6940. ServerUpDownTest() : cli_(HOST, PORT) {}
  6941. virtual void SetUp() {
  6942. t_ = thread([&]() {
  6943. svr_.bind_to_any_port(HOST);
  6944. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6945. ASSERT_TRUE(svr_.listen_after_bind());
  6946. });
  6947. svr_.wait_until_ready();
  6948. }
  6949. virtual void TearDown() {
  6950. svr_.stop();
  6951. t_.join();
  6952. }
  6953. Client cli_;
  6954. Server svr_;
  6955. thread t_;
  6956. };
  6957. TEST_F(ServerUpDownTest, QuickStartStop) {
  6958. // Should not crash, especially when run with
  6959. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6960. }
  6961. class PayloadMaxLengthTest : public ::testing::Test {
  6962. protected:
  6963. PayloadMaxLengthTest()
  6964. : cli_(HOST, PORT)
  6965. #ifdef CPPHTTPLIB_SSL_ENABLED
  6966. ,
  6967. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6968. #endif
  6969. {
  6970. #ifdef CPPHTTPLIB_SSL_ENABLED
  6971. cli_.enable_server_certificate_verification(false);
  6972. #endif
  6973. }
  6974. virtual void SetUp() {
  6975. svr_.set_payload_max_length(8);
  6976. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6977. res.set_content("test", "text/plain");
  6978. });
  6979. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6980. svr_.wait_until_ready();
  6981. }
  6982. virtual void TearDown() {
  6983. svr_.stop();
  6984. t_.join();
  6985. }
  6986. #ifdef CPPHTTPLIB_SSL_ENABLED
  6987. SSLClient cli_;
  6988. SSLServer svr_;
  6989. #else
  6990. Client cli_;
  6991. Server svr_;
  6992. #endif
  6993. thread t_;
  6994. };
  6995. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6996. auto res = cli_.Post("/test", "123456789", "text/plain");
  6997. ASSERT_TRUE(res);
  6998. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6999. res = cli_.Post("/test", "12345678", "text/plain");
  7000. ASSERT_TRUE(res);
  7001. EXPECT_EQ(StatusCode::OK_200, res->status);
  7002. }
  7003. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  7004. // Test chunked encoding with payload exceeding the 8-byte limit
  7005. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  7006. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7009. }
  7010. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  7011. // Test chunked encoding with payload within the 8-byte limit
  7012. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  7013. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  7014. ASSERT_TRUE(res);
  7015. EXPECT_EQ(StatusCode::OK_200, res->status);
  7016. }
  7017. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  7018. // Test using send_request to send chunked data exceeding payload limit
  7019. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  7020. "Host: " +
  7021. std::string(HOST) + ":" + std::to_string(PORT) +
  7022. "\r\n"
  7023. "Transfer-Encoding: chunked\r\n"
  7024. "Connection: close\r\n"
  7025. "\r\n"
  7026. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  7027. "0123456789\r\n"
  7028. "0\r\n" // End chunk
  7029. "\r\n";
  7030. std::string response;
  7031. bool result = send_request(1, chunked_request, &response);
  7032. if (!result) {
  7033. // If send_request fails, it might be because the server closed the
  7034. // connection due to payload limit enforcement, which is acceptable
  7035. SUCCEED()
  7036. << "Server rejected oversized chunked request (connection closed)";
  7037. } else {
  7038. // If we got a response, check if it's an error response or connection was
  7039. // closed early Short response length indicates connection was closed due to
  7040. // payload limit
  7041. if (response.length() <= 10) {
  7042. SUCCEED() << "Server closed connection for oversized chunked request";
  7043. } else {
  7044. // Check for error status codes
  7045. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7046. response.find("Payload Too Large") != std::string::npos ||
  7047. response.find("400") != std::string::npos);
  7048. }
  7049. }
  7050. }
  7051. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  7052. // Test request without Content-Length header exceeding payload limit
  7053. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7054. "Host: " +
  7055. std::string(HOST) + ":" +
  7056. std::to_string(PORT) +
  7057. "\r\n"
  7058. "Connection: close\r\n"
  7059. "\r\n";
  7060. // Add payload exceeding the 8-byte limit
  7061. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  7062. request_without_content_length += large_payload;
  7063. std::string response;
  7064. bool result = send_request(1, request_without_content_length, &response);
  7065. if (!result) {
  7066. // If send_request fails, server likely closed connection due to payload
  7067. // limit
  7068. SUCCEED() << "Server rejected oversized request without Content-Length "
  7069. "(connection closed)";
  7070. } else {
  7071. // Check if server responded with error or closed connection early
  7072. if (response.length() <= 10) {
  7073. SUCCEED() << "Server closed connection for oversized request without "
  7074. "Content-Length";
  7075. } else {
  7076. // Check for error status codes
  7077. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7078. response.find("Payload Too Large") != std::string::npos ||
  7079. response.find("400") != std::string::npos);
  7080. }
  7081. }
  7082. }
  7083. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  7084. // Test request without Content-Length header within payload limit
  7085. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7086. "Host: " +
  7087. std::string(HOST) + ":" +
  7088. std::to_string(PORT) +
  7089. "\r\n"
  7090. "Connection: close\r\n"
  7091. "\r\n";
  7092. // Add payload within the 8-byte limit
  7093. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7094. request_without_content_length += small_payload;
  7095. std::string response;
  7096. bool result = send_request(1, request_without_content_length, &response);
  7097. // For requests without Content-Length, the server may have different behavior
  7098. // The key is that it should not reject due to payload limit for small
  7099. // payloads
  7100. if (result) {
  7101. // Check for any HTTP response (success or error, but not connection closed)
  7102. if (response.length() > 10) {
  7103. SUCCEED()
  7104. << "Server processed request without Content-Length within limit";
  7105. } else {
  7106. // Short response might indicate connection closed, which is acceptable
  7107. SUCCEED() << "Server closed connection for request without "
  7108. "Content-Length (acceptable behavior)";
  7109. }
  7110. } else {
  7111. // Connection failure might be due to protocol requirements
  7112. SUCCEED() << "Connection issue with request without Content-Length "
  7113. "(environment-specific)";
  7114. }
  7115. }
  7116. class LargePayloadMaxLengthTest : public ::testing::Test {
  7117. protected:
  7118. LargePayloadMaxLengthTest()
  7119. : cli_(HOST, PORT)
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. ,
  7122. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7123. #endif
  7124. {
  7125. #ifdef CPPHTTPLIB_SSL_ENABLED
  7126. cli_.enable_server_certificate_verification(false);
  7127. #endif
  7128. }
  7129. virtual void SetUp() {
  7130. // Set 10MB payload limit
  7131. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7132. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7133. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7134. res.set_content("Large payload test", "text/plain");
  7135. });
  7136. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7137. svr_.wait_until_ready();
  7138. }
  7139. virtual void TearDown() {
  7140. svr_.stop();
  7141. t_.join();
  7142. }
  7143. #ifdef CPPHTTPLIB_SSL_ENABLED
  7144. SSLClient cli_;
  7145. SSLServer svr_;
  7146. #else
  7147. Client cli_;
  7148. Server svr_;
  7149. #endif
  7150. thread t_;
  7151. };
  7152. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7153. // Test chunked encoding with payload within 10MB limit
  7154. std::string medium_payload(5 * 1024 * 1024,
  7155. 'A'); // 5MB payload, within 10MB limit
  7156. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7157. ASSERT_TRUE(res);
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. }
  7160. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7161. // Test chunked encoding with payload exceeding 10MB limit
  7162. std::string large_payload(12 * 1024 * 1024,
  7163. 'B'); // 12MB payload, exceeds 10MB limit
  7164. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7165. ASSERT_TRUE(res);
  7166. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7167. }
  7168. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7169. // Test request without Content-Length header within 10MB limit
  7170. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7171. "Host: " +
  7172. std::string(HOST) + ":" +
  7173. std::to_string(PORT) +
  7174. "\r\n"
  7175. "Connection: close\r\n"
  7176. "\r\n";
  7177. // Add 1MB payload (within 10MB limit)
  7178. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7179. request_without_content_length += medium_payload;
  7180. std::string response;
  7181. bool result = send_request(5, request_without_content_length, &response);
  7182. if (result) {
  7183. // Should get a proper HTTP response for payloads within limit
  7184. if (response.length() > 10) {
  7185. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7186. "10MB limit";
  7187. } else {
  7188. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7189. "Content-Length)";
  7190. }
  7191. } else {
  7192. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7193. }
  7194. }
  7195. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7196. // Test request without Content-Length header exceeding 10MB limit
  7197. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7198. "Host: " +
  7199. std::string(HOST) + ":" +
  7200. std::to_string(PORT) +
  7201. "\r\n"
  7202. "Connection: close\r\n"
  7203. "\r\n";
  7204. // Add 12MB payload (exceeds 10MB limit)
  7205. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7206. request_without_content_length += large_payload;
  7207. std::string response;
  7208. bool result = send_request(10, request_without_content_length, &response);
  7209. if (!result) {
  7210. // Server should close connection due to payload limit
  7211. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7212. "(connection closed)";
  7213. } else {
  7214. // Check for error response
  7215. if (response.length() <= 10) {
  7216. SUCCEED()
  7217. << "Server closed connection for 12MB request exceeding 10MB limit";
  7218. } else {
  7219. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7220. response.find("Payload Too Large") != std::string::npos ||
  7221. response.find("400") != std::string::npos);
  7222. }
  7223. }
  7224. }
  7225. TEST(HostAndPortPropertiesTest, NoSSL) {
  7226. httplib::Client cli("www.google.com", 1234);
  7227. ASSERT_EQ("www.google.com", cli.host());
  7228. ASSERT_EQ(1234, cli.port());
  7229. }
  7230. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7231. httplib::Client cli("www.google.com:1234");
  7232. ASSERT_EQ("www.google.com", cli.host());
  7233. ASSERT_EQ(1234, cli.port());
  7234. }
  7235. #ifdef CPPHTTPLIB_SSL_ENABLED
  7236. TEST(HostAndPortPropertiesTest, SSL) {
  7237. httplib::SSLClient cli("www.google.com");
  7238. ASSERT_EQ("www.google.com", cli.host());
  7239. ASSERT_EQ(443, cli.port());
  7240. }
  7241. #endif
  7242. #ifdef CPPHTTPLIB_SSL_ENABLED
  7243. TEST(SSLClientTest, UpdateCAStoreWithPem) {
  7244. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  7245. // This is the backend-agnostic equivalent of UpdateCAStore test
  7246. std::string cert;
  7247. read_file(CA_CERT_FILE, cert);
  7248. httplib::SSLClient httplib_client("www.google.com");
  7249. // Load CA store first time
  7250. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7251. // Load CA store second time (update)
  7252. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  7253. // Verify client is still valid and can make connections
  7254. httplib_client.enable_server_certificate_verification(true);
  7255. auto res = httplib_client.Get("/");
  7256. ASSERT_TRUE(res);
  7257. // Google may return 200 or 301 depending on various factors
  7258. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  7259. res->status == StatusCode::MovedPermanently_301);
  7260. }
  7261. #endif
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. TEST(SSLClientTest, ServerNameIndication_Online) {
  7264. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7265. auto host = "httpcan.org";
  7266. auto path = std::string{"/get"};
  7267. #else
  7268. auto host = "nghttp2.org";
  7269. auto path = std::string{"/httpbin/get"};
  7270. #endif
  7271. SSLClient cli(host, 443);
  7272. auto res = cli.Get(path);
  7273. ASSERT_TRUE(res);
  7274. ASSERT_EQ(StatusCode::OK_200, res->status);
  7275. }
  7276. #endif
  7277. #ifdef CPPHTTPLIB_SSL_ENABLED
  7278. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7279. // Use a site that will cause SSL verification failure due to self-signed cert
  7280. SSLClient cli("self-signed.badssl.com", 443);
  7281. cli.enable_server_certificate_verification(true);
  7282. auto res = cli.Get("/");
  7283. ASSERT_TRUE(!res);
  7284. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7285. // Verify backend error is captured for SSLServerVerification
  7286. // This occurs when certificate verification fails
  7287. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  7288. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  7289. EXPECT_NE(0UL, res.ssl_backend_error());
  7290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7291. // For OpenSSL, ssl_error is 0 for verification errors
  7292. EXPECT_EQ(0, res.ssl_error());
  7293. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7294. res.ssl_openssl_error());
  7295. #endif
  7296. }
  7297. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7298. // Use a site where hostname doesn't match the certificate
  7299. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7300. SSLClient cli("wrong.host.badssl.com", 443);
  7301. cli.enable_server_certificate_verification(true);
  7302. cli.enable_server_hostname_verification(true);
  7303. auto res = cli.Get("/");
  7304. ASSERT_TRUE(!res);
  7305. // The error type depends on when hostname verification occurs:
  7306. // - OpenSSL: SSLServerHostnameVerification (post-handshake verification)
  7307. // - Mbed TLS: SSLServerVerification (during handshake)
  7308. EXPECT_TRUE(res.error() == Error::SSLServerHostnameVerification ||
  7309. res.error() == Error::SSLServerVerification);
  7310. // Verify backend error is captured for hostname verification failure
  7311. EXPECT_NE(0UL, res.ssl_backend_error());
  7312. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7313. // For OpenSSL, ssl_error is 0 for verification errors
  7314. EXPECT_EQ(0, res.ssl_error());
  7315. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7316. res.ssl_openssl_error());
  7317. #endif
  7318. }
  7319. #endif
  7320. #ifdef CPPHTTPLIB_SSL_ENABLED
  7321. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7322. Client cli("https://google.com");
  7323. auto res = cli.Get("/");
  7324. ASSERT_TRUE(res);
  7325. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7326. }
  7327. #endif
  7328. #ifdef CPPHTTPLIB_SSL_ENABLED
  7329. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7330. SSLClient cli("google.com");
  7331. cli.set_ca_cert_path(CA_CERT_FILE);
  7332. auto res = cli.Get("/");
  7333. ASSERT_TRUE(res);
  7334. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7335. }
  7336. #endif
  7337. #ifdef CPPHTTPLIB_SSL_ENABLED
  7338. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7339. SSLClient cli("google.com");
  7340. cli.enable_server_certificate_verification(true);
  7341. cli.set_ca_cert_path("hello");
  7342. auto res = cli.Get("/");
  7343. ASSERT_TRUE(!res);
  7344. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7345. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  7346. // should be set
  7347. EXPECT_EQ(0, res.ssl_error());
  7348. // Verify backend error is captured for SSLLoadingCerts
  7349. // This error occurs when loading CA certificates fails
  7350. EXPECT_NE(0UL, res.ssl_backend_error());
  7351. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7352. // OpenSSL specific error codes:
  7353. // > openssl errstr 0x80000002
  7354. // error:80000002:system library::No such file or directory
  7355. // > openssl errstr 0xA000126
  7356. // error:0A000126:SSL routines::unexpected eof while reading
  7357. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7358. res.ssl_openssl_error() == 0xA000126);
  7359. #endif
  7360. }
  7361. #endif
  7362. #ifdef CPPHTTPLIB_SSL_ENABLED
  7363. TEST(SSLClientTest, ServerCertificateVerification4) {
  7364. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7365. ASSERT_TRUE(svr.is_valid());
  7366. svr.Get("/test", [&](const Request &, Response &res) {
  7367. res.set_content("test", "text/plain");
  7368. svr.stop();
  7369. ASSERT_TRUE(true);
  7370. });
  7371. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7372. auto se = detail::scope_exit([&] {
  7373. t.join();
  7374. ASSERT_FALSE(svr.is_running());
  7375. });
  7376. svr.wait_until_ready();
  7377. SSLClient cli("127.0.0.1", PORT);
  7378. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7379. cli.enable_server_certificate_verification(true);
  7380. cli.set_connection_timeout(30);
  7381. auto res = cli.Get("/test");
  7382. ASSERT_TRUE(res);
  7383. ASSERT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7386. std::string cert;
  7387. read_file(CA_CERT_FILE, cert);
  7388. SSLClient cli("google.com");
  7389. cli.load_ca_cert_store(cert.data(), cert.size());
  7390. const auto res = cli.Get("/");
  7391. ASSERT_TRUE(res);
  7392. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7393. }
  7394. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7395. // clang-format off
  7396. static constexpr char cert[] =
  7397. "GlobalSign Root CA\n"
  7398. "==================\n"
  7399. "-----BEGIN CERTIFICATE-----\n"
  7400. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7401. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7402. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7403. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7404. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7405. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7406. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7407. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7408. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7409. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7410. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7411. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7412. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7413. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7414. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7415. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7416. "-----END CERTIFICATE-----\n";
  7417. // clang-format on
  7418. SSLClient cli("google.com");
  7419. cli.load_ca_cert_store(cert, sizeof(cert));
  7420. const auto res = cli.Get("/");
  7421. ASSERT_TRUE(res);
  7422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7423. }
  7424. TEST(SSLClientTest, Issue2004_Online) {
  7425. Client client("https://google.com");
  7426. client.set_follow_location(true);
  7427. auto res = client.Get("/");
  7428. ASSERT_TRUE(res);
  7429. ASSERT_EQ(StatusCode::OK_200, res->status);
  7430. auto body = res->body;
  7431. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7432. }
  7433. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7434. // Create SSLClient with invalid cert/key to make is_valid() return false
  7435. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7436. "nonexistent_key.pem");
  7437. // is_valid() should be false due to cert loading failure
  7438. ASSERT_FALSE(cli.is_valid());
  7439. auto res = cli.Get("/");
  7440. ASSERT_FALSE(res);
  7441. EXPECT_EQ(Error::SSLConnection, res.error());
  7442. }
  7443. #endif
  7444. #ifdef CPPHTTPLIB_SSL_ENABLED
  7445. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7446. SSLClient cli("www.youtube.com");
  7447. cli.set_ca_cert_path(CA_CERT_FILE);
  7448. cli.enable_server_certificate_verification(true);
  7449. cli.set_follow_location(true);
  7450. auto res = cli.Get("/");
  7451. ASSERT_TRUE(res);
  7452. ASSERT_EQ(StatusCode::OK_200, res->status);
  7453. }
  7454. #endif
  7455. #ifdef CPPHTTPLIB_SSL_ENABLED
  7456. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7457. // Test for Issue #2251: SSL error not properly reported when client cert
  7458. // and key paths are swapped or mismatched
  7459. // This simulates the scenario where user accidentally swaps the cert and key
  7460. // files
  7461. // Using client cert file as private key and vice versa (completely wrong)
  7462. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7463. // Should fail validation due to cert/key mismatch
  7464. ASSERT_FALSE(cli.is_valid());
  7465. // Attempt to make a request should fail with proper error
  7466. auto res = cli.Get("/");
  7467. ASSERT_FALSE(res);
  7468. EXPECT_EQ(Error::SSLConnection, res.error());
  7469. // SSL error should be recorded in the Result object (this is the key fix for
  7470. // Issue #2251)
  7471. auto backend_error = res.ssl_backend_error();
  7472. EXPECT_NE(0u, backend_error);
  7473. }
  7474. // Backend-agnostic test using abstract TLS API
  7475. // Tests cert/key mismatch detection at the TLS context level
  7476. TEST(TlsApiTest, ClientCertKeyMismatch) {
  7477. using namespace httplib::detail::tls;
  7478. // Create client context
  7479. auto ctx = tls_create_client_context();
  7480. ASSERT_NE(nullptr, ctx);
  7481. // Try to set mismatched cert/key (client.cert.pem with key.pem from cert2)
  7482. // The behavior differs by backend:
  7483. // - OpenSSL: tls_set_client_cert_file returns false immediately
  7484. // - Mbed TLS: succeeds here but fails during handshake
  7485. bool result =
  7486. tls_set_client_cert_file(ctx, "client.cert.pem", "key.pem", nullptr);
  7487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7488. // OpenSSL checks key consistency in SSL_CTX_use_PrivateKey_file
  7489. // by calling SSL_CTX_check_private_key internally after loading.
  7490. EXPECT_FALSE(result);
  7491. auto err = tls_get_error();
  7492. EXPECT_NE(0u, err);
  7493. #endif
  7494. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7495. // Mbed TLS doesn't perform cert/key consistency check until handshake.
  7496. // The mismatch is tested at connection time by
  7497. // Issue2251_SwappedClientCertAndKey
  7498. EXPECT_TRUE(result);
  7499. #endif
  7500. tls_free_context(ctx);
  7501. }
  7502. #endif
  7503. #if 0
  7504. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7505. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7506. ASSERT_TRUE(cli != nullptr);
  7507. cli->set_address_family(AF_INET6);
  7508. cli->set_interface("en0");
  7509. auto res = cli->Get("/get");
  7510. ASSERT_TRUE(res);
  7511. ASSERT_EQ(StatusCode::OK_200, res->status);
  7512. }
  7513. #endif
  7514. // ClientCertPresent uses tls_get_peer_cert() - works with all TLS backends
  7515. #ifdef CPPHTTPLIB_SSL_ENABLED
  7516. void ClientCertPresent(
  7517. const std::string &client_cert_file,
  7518. const std::string &client_private_key_file,
  7519. const std::string &client_encrypted_private_key_pass = std::string()) {
  7520. using namespace httplib::detail::tls;
  7521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7522. CLIENT_CA_CERT_DIR);
  7523. ASSERT_TRUE(svr.is_valid());
  7524. svr.Get("/test", [&](const Request &req, Response &res) {
  7525. res.set_content("test", "text/plain");
  7526. // Cast away const for tls_get_peer_cert (session is not modified)
  7527. auto peer_cert = tls_get_peer_cert(const_cast<void *>(req.ssl));
  7528. ASSERT_TRUE(peer_cert != nullptr);
  7529. std::string common_name = tls_get_cert_subject_cn(peer_cert);
  7530. EXPECT_EQ("Common Name", common_name);
  7531. tls_free_cert(peer_cert);
  7532. });
  7533. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7534. auto se = detail::scope_exit([&] {
  7535. svr.stop();
  7536. t.join();
  7537. ASSERT_FALSE(svr.is_running());
  7538. });
  7539. svr.wait_until_ready();
  7540. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7541. client_encrypted_private_key_pass);
  7542. cli.enable_server_certificate_verification(false);
  7543. cli.set_connection_timeout(30);
  7544. auto res = cli.Get("/test");
  7545. ASSERT_TRUE(res);
  7546. ASSERT_EQ(StatusCode::OK_200, res->status);
  7547. }
  7548. TEST(SSLClientServerTest, ClientCertPresent) {
  7549. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7550. }
  7551. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7552. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7553. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7554. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7555. }
  7556. #endif
  7557. #ifdef CPPHTTPLIB_SSL_ENABLED
  7558. // PEM memory-based constructor tests (works with all TLS backends)
  7559. void PemMemoryClientCertPresent(
  7560. const std::string &client_cert_file,
  7561. const std::string &client_private_key_file,
  7562. const std::string &client_encrypted_private_key_pass = std::string()) {
  7563. // Read PEM files into memory
  7564. std::string server_cert_pem, server_key_pem;
  7565. std::string client_ca_pem;
  7566. std::string client_cert_pem, client_key_pem;
  7567. read_file(SERVER_CERT_FILE, server_cert_pem);
  7568. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  7569. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  7570. read_file(client_cert_file, client_cert_pem);
  7571. read_file(client_private_key_file, client_key_pem);
  7572. // Create server with PEM memory
  7573. SSLServer::PemMemory server_pem = {
  7574. server_cert_pem.c_str(),
  7575. server_cert_pem.size(),
  7576. server_key_pem.c_str(),
  7577. server_key_pem.size(),
  7578. client_ca_pem.c_str(),
  7579. client_ca_pem.size(),
  7580. nullptr // no password for server key
  7581. };
  7582. SSLServer svr(server_pem);
  7583. ASSERT_TRUE(svr.is_valid());
  7584. svr.Get("/test", [&](const Request &, Response &res) {
  7585. res.set_content("test", "text/plain");
  7586. });
  7587. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7588. auto se = detail::scope_exit([&] {
  7589. svr.stop();
  7590. t.join();
  7591. ASSERT_FALSE(svr.is_running());
  7592. });
  7593. svr.wait_until_ready();
  7594. // Create client with PEM memory
  7595. const char *password = client_encrypted_private_key_pass.empty()
  7596. ? nullptr
  7597. : client_encrypted_private_key_pass.c_str();
  7598. SSLClient::PemMemory client_pem = {
  7599. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  7600. client_key_pem.size(), password};
  7601. SSLClient cli(HOST, PORT, client_pem);
  7602. cli.enable_server_certificate_verification(false);
  7603. cli.set_connection_timeout(30);
  7604. auto res = cli.Get("/test");
  7605. ASSERT_TRUE(res);
  7606. ASSERT_EQ(StatusCode::OK_200, res->status);
  7607. }
  7608. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  7609. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7610. }
  7611. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  7612. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7613. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7614. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7615. }
  7616. #endif
  7617. #ifdef CPPHTTPLIB_SSL_ENABLED
  7618. TEST(SSLClientServerTest, ClientCertMissing) {
  7619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7620. CLIENT_CA_CERT_DIR);
  7621. ASSERT_TRUE(svr.is_valid());
  7622. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7624. auto se = detail::scope_exit([&] {
  7625. svr.stop();
  7626. t.join();
  7627. ASSERT_FALSE(svr.is_running());
  7628. });
  7629. svr.wait_until_ready();
  7630. SSLClient cli(HOST, PORT);
  7631. cli.set_connection_timeout(30);
  7632. auto res = cli.Get("/test");
  7633. ASSERT_TRUE(!res);
  7634. // When client cert is missing and server requires it, connection fails
  7635. // Error type depends on backend implementation
  7636. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  7637. res.error() == Error::SSLConnection);
  7638. // Verify backend error is captured
  7639. // Note: This test may have different error codes depending on the exact
  7640. // verification failure
  7641. EXPECT_NE(0UL, res.ssl_backend_error());
  7642. }
  7643. TEST(SSLClientServerTest, TrustDirOptional) {
  7644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7645. ASSERT_TRUE(svr.is_valid());
  7646. svr.Get("/test", [&](const Request &, Response &res) {
  7647. res.set_content("test", "text/plain");
  7648. });
  7649. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7650. auto se = detail::scope_exit([&] {
  7651. svr.stop();
  7652. t.join();
  7653. ASSERT_FALSE(svr.is_running());
  7654. });
  7655. svr.wait_until_ready();
  7656. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7657. cli.enable_server_certificate_verification(false);
  7658. cli.set_connection_timeout(30);
  7659. auto res = cli.Get("/test");
  7660. ASSERT_TRUE(res);
  7661. ASSERT_EQ(StatusCode::OK_200, res->status);
  7662. }
  7663. #endif
  7664. #ifdef CPPHTTPLIB_SSL_ENABLED
  7665. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7666. class NoListenSSLServer : public SSLServer {
  7667. public:
  7668. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7669. const char *client_ca_cert_file_path,
  7670. const char *client_ca_cert_dir_path = nullptr)
  7671. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7672. client_ca_cert_dir_path),
  7673. stop_(false) {}
  7674. std::atomic_bool stop_;
  7675. private:
  7676. bool process_and_close_socket(socket_t /*sock*/) override {
  7677. // Don't create SSL context
  7678. while (!stop_.load()) {
  7679. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7680. }
  7681. return true;
  7682. }
  7683. };
  7684. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7685. CLIENT_CA_CERT_FILE);
  7686. ASSERT_TRUE(svr.is_valid());
  7687. svr.Get("/test", [&](const Request &, Response &res) {
  7688. res.set_content("test", "text/plain");
  7689. });
  7690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7691. auto se = detail::scope_exit([&] {
  7692. svr.stop_ = true;
  7693. svr.stop();
  7694. t.join();
  7695. ASSERT_FALSE(svr.is_running());
  7696. });
  7697. svr.wait_until_ready();
  7698. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7699. cli.enable_server_certificate_verification(false);
  7700. cli.set_connection_timeout(1);
  7701. auto res = cli.Get("/test");
  7702. ASSERT_TRUE(!res);
  7703. EXPECT_EQ(Error::SSLConnection, res.error());
  7704. // Timeout results in WantRead error code (maps to backend-specific value)
  7705. EXPECT_NE(0, res.ssl_error());
  7706. }
  7707. #endif
  7708. // Backend-agnostic equivalent of CustomizeServerSSLCtx test
  7709. // Uses void* callback constructor and detail::tls API
  7710. #ifdef CPPHTTPLIB_SSL_ENABLED
  7711. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  7712. using namespace httplib::detail::tls;
  7713. auto setup_callback = [](void *ctx) {
  7714. // Load server certificate and key using backend-agnostic API
  7715. if (!tls_set_server_cert_file(static_cast<tls_ctx_t>(ctx), SERVER_CERT_FILE,
  7716. SERVER_PRIVATE_KEY_FILE, nullptr)) {
  7717. return false;
  7718. }
  7719. // Set up client certificate verification
  7720. if (!tls_set_client_ca_file(static_cast<tls_ctx_t>(ctx),
  7721. CLIENT_CA_CERT_FILE, CLIENT_CA_CERT_DIR)) {
  7722. return false;
  7723. }
  7724. tls_set_verify_client(static_cast<tls_ctx_t>(ctx), true);
  7725. return true;
  7726. };
  7727. SSLServer svr(setup_callback);
  7728. ASSERT_TRUE(svr.is_valid());
  7729. svr.Get("/test", [&](const Request &req, Response &res) {
  7730. res.set_content("test", "text/plain");
  7731. // Get peer certificate using backend-agnostic API
  7732. // Note: req.ssl is const void*, need const_cast for API compatibility
  7733. auto peer_cert = tls_get_peer_cert(const_cast<tls_session_t>(req.ssl));
  7734. ASSERT_TRUE(peer_cert != nullptr);
  7735. // Verify common name using backend-agnostic API
  7736. auto common_name = tls_get_cert_subject_cn(peer_cert);
  7737. EXPECT_EQ("Common Name", common_name);
  7738. tls_free_cert(peer_cert);
  7739. });
  7740. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7741. auto se = detail::scope_exit([&] {
  7742. svr.stop();
  7743. t.join();
  7744. ASSERT_FALSE(svr.is_running());
  7745. });
  7746. svr.wait_until_ready();
  7747. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7748. cli.enable_server_certificate_verification(false);
  7749. cli.set_connection_timeout(30);
  7750. auto res = cli.Get("/test");
  7751. ASSERT_TRUE(res);
  7752. ASSERT_EQ(StatusCode::OK_200, res->status);
  7753. }
  7754. #endif
  7755. // mbedTLS-specific callback constructor test
  7756. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  7757. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  7758. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  7759. using namespace httplib::detail::tls;
  7760. // Track if callback was invoked
  7761. bool callback_invoked = false;
  7762. // The callback receives void* ctx which is actually MbedTlsContext*
  7763. // We can access the mbedtls_ssl_config via the context
  7764. auto setup_callback = [&callback_invoked](void *ctx) {
  7765. callback_invoked = true;
  7766. // Cast to MbedTlsContext* to access the ssl config
  7767. auto *mbedtls_ctx =
  7768. static_cast<httplib::detail::tls::MbedTlsContext *>(ctx);
  7769. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  7770. // Use static variables to hold certificate data (simplified for test)
  7771. static mbedtls_x509_crt own_cert;
  7772. static mbedtls_pk_context own_key;
  7773. static mbedtls_x509_crt ca_chain;
  7774. static bool initialized = false;
  7775. if (!initialized) {
  7776. mbedtls_x509_crt_init(&own_cert);
  7777. mbedtls_pk_init(&own_key);
  7778. mbedtls_x509_crt_init(&ca_chain);
  7779. // Load server certificate
  7780. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  7781. return false;
  7782. }
  7783. // Load server private key
  7784. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  7785. #if MBEDTLS_VERSION_MAJOR >= 3
  7786. ,
  7787. mbedtls_ctr_drbg_random, nullptr
  7788. #endif
  7789. ) != 0) {
  7790. return false;
  7791. }
  7792. // Load CA chain for client verification
  7793. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  7794. return false;
  7795. }
  7796. initialized = true;
  7797. }
  7798. // Configure the SSL config
  7799. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  7800. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  7801. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  7802. // Set minimum TLS version using mbedTLS native API
  7803. #if MBEDTLS_VERSION_MAJOR >= 3
  7804. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  7805. #else
  7806. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  7807. MBEDTLS_SSL_MINOR_VERSION_3);
  7808. #endif
  7809. return true;
  7810. };
  7811. SSLServer svr(setup_callback);
  7812. ASSERT_TRUE(svr.is_valid());
  7813. ASSERT_TRUE(callback_invoked);
  7814. svr.Get("/test", [&](const Request &req, Response &res) {
  7815. res.set_content("test", "text/plain");
  7816. // Get peer certificate using backend-agnostic API
  7817. auto peer_cert = tls_get_peer_cert(const_cast<tls_session_t>(req.ssl));
  7818. ASSERT_TRUE(peer_cert != nullptr);
  7819. auto common_name = tls_get_cert_subject_cn(peer_cert);
  7820. EXPECT_EQ("Common Name", common_name);
  7821. tls_free_cert(peer_cert);
  7822. });
  7823. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7824. auto se = detail::scope_exit([&] {
  7825. svr.stop();
  7826. t.join();
  7827. ASSERT_FALSE(svr.is_running());
  7828. });
  7829. svr.wait_until_ready();
  7830. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7831. cli.enable_server_certificate_verification(false);
  7832. cli.set_connection_timeout(30);
  7833. auto res = cli.Get("/test");
  7834. ASSERT_TRUE(res);
  7835. ASSERT_EQ(StatusCode::OK_200, res->status);
  7836. }
  7837. #endif
  7838. #ifdef CPPHTTPLIB_SSL_ENABLED
  7839. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7840. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7841. ASSERT_TRUE(svr.is_valid());
  7842. // Set up a handler to verify client certificate is present
  7843. bool client_cert_verified = false;
  7844. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7845. // Verify that client certificate was provided
  7846. client_cert_verified = true;
  7847. res.set_content("success", "text/plain");
  7848. });
  7849. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7850. auto se = detail::scope_exit([&] {
  7851. svr.stop();
  7852. t.join();
  7853. ASSERT_FALSE(svr.is_running());
  7854. });
  7855. svr.wait_until_ready();
  7856. // Client with certificate
  7857. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7858. cli.enable_server_certificate_verification(false);
  7859. cli.set_connection_timeout(30);
  7860. auto res = cli.Get("/test");
  7861. ASSERT_TRUE(res);
  7862. ASSERT_EQ(StatusCode::OK_200, res->status);
  7863. ASSERT_TRUE(client_cert_verified);
  7864. EXPECT_EQ("success", res->body);
  7865. }
  7866. #endif
  7867. // ClientCAListSetInContext uses tls_get_peer_cert() - works with all TLS
  7868. // backends
  7869. #ifdef CPPHTTPLIB_SSL_ENABLED
  7870. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7871. using namespace httplib::detail::tls;
  7872. // Test that when client CA cert file is provided,
  7873. // the server properly requests and validates client certificates
  7874. // Create a server with client authentication
  7875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7876. ASSERT_TRUE(svr.is_valid());
  7877. bool handler_called = false;
  7878. svr.Get("/test", [&](const Request &req, Response &res) {
  7879. handler_called = true;
  7880. // Verify that a client certificate was provided
  7881. // Cast away const for tls_get_peer_cert (session is not modified)
  7882. auto peer_cert = tls_get_peer_cert(const_cast<void *>(req.ssl));
  7883. ASSERT_TRUE(peer_cert != nullptr);
  7884. // Get the issuer name
  7885. std::string issuer_str = tls_get_cert_issuer_name(peer_cert);
  7886. ASSERT_FALSE(issuer_str.empty());
  7887. // The client certificate should be issued by our test CA
  7888. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7889. tls_free_cert(peer_cert);
  7890. res.set_content("authenticated", "text/plain");
  7891. });
  7892. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7893. auto se = detail::scope_exit([&] {
  7894. svr.stop();
  7895. t.join();
  7896. ASSERT_FALSE(svr.is_running());
  7897. });
  7898. svr.wait_until_ready();
  7899. // Connect with a client certificate issued by the CA
  7900. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7901. cli.enable_server_certificate_verification(false);
  7902. cli.set_connection_timeout(30);
  7903. auto res = cli.Get("/test");
  7904. ASSERT_TRUE(res);
  7905. ASSERT_EQ(StatusCode::OK_200, res->status);
  7906. ASSERT_TRUE(handler_called);
  7907. EXPECT_EQ("authenticated", res->body);
  7908. }
  7909. #endif
  7910. #ifdef CPPHTTPLIB_SSL_ENABLED
  7911. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  7912. using namespace httplib::detail::tls;
  7913. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7914. ASSERT_TRUE(svr.is_valid());
  7915. svr.Get("/test", [](const Request &, Response &res) {
  7916. res.set_content("ok", "text/plain");
  7917. });
  7918. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7919. auto se = detail::scope_exit([&] {
  7920. svr.stop();
  7921. t.join();
  7922. });
  7923. svr.wait_until_ready();
  7924. SSLClient cli(HOST, PORT);
  7925. cli.enable_server_certificate_verification(false);
  7926. cli.set_connection_timeout(30);
  7927. bool cert_checked = false;
  7928. cli.set_server_certificate_verifier(
  7929. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  7930. (void)session;
  7931. if (peer_cert) {
  7932. std::vector<TlsSanEntry> sans;
  7933. bool result = tls_get_cert_sans(peer_cert, sans);
  7934. // tls_get_cert_sans should return true even if no SANs exist
  7935. EXPECT_TRUE(result);
  7936. // Test certificate may or may not have SANs - just verify the API
  7937. // works If SANs exist, verify the types are valid
  7938. for (const auto &san : sans) {
  7939. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  7940. san.type == SanType::EMAIL ||
  7941. san.type == SanType::URI || san.type == SanType::OTHER);
  7942. EXPECT_FALSE(san.value.empty());
  7943. }
  7944. cert_checked = true;
  7945. }
  7946. return true;
  7947. });
  7948. auto res = cli.Get("/test");
  7949. ASSERT_TRUE(res);
  7950. EXPECT_TRUE(cert_checked);
  7951. }
  7952. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  7953. using namespace httplib::detail::tls;
  7954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7955. ASSERT_TRUE(svr.is_valid());
  7956. svr.Get("/test", [](const Request &, Response &res) {
  7957. res.set_content("ok", "text/plain");
  7958. });
  7959. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7960. auto se = detail::scope_exit([&] {
  7961. svr.stop();
  7962. t.join();
  7963. });
  7964. svr.wait_until_ready();
  7965. SSLClient cli(HOST, PORT);
  7966. cli.enable_server_certificate_verification(false);
  7967. cli.set_connection_timeout(30);
  7968. bool validity_checked = false;
  7969. cli.set_server_certificate_verifier(
  7970. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  7971. (void)session;
  7972. if (peer_cert) {
  7973. time_t not_before = 0, not_after = 0;
  7974. bool result = tls_get_cert_validity(peer_cert, not_before, not_after);
  7975. EXPECT_TRUE(result);
  7976. // Verify that not_before < now < not_after for a valid cert
  7977. time_t now = time(nullptr);
  7978. EXPECT_LT(not_before, now);
  7979. EXPECT_GT(not_after, now);
  7980. validity_checked = true;
  7981. }
  7982. return true;
  7983. });
  7984. auto res = cli.Get("/test");
  7985. ASSERT_TRUE(res);
  7986. EXPECT_TRUE(validity_checked);
  7987. }
  7988. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  7989. using namespace httplib::detail::tls;
  7990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7991. ASSERT_TRUE(svr.is_valid());
  7992. svr.Get("/test", [](const Request &, Response &res) {
  7993. res.set_content("ok", "text/plain");
  7994. });
  7995. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7996. auto se = detail::scope_exit([&] {
  7997. svr.stop();
  7998. t.join();
  7999. });
  8000. svr.wait_until_ready();
  8001. SSLClient cli(HOST, PORT);
  8002. cli.enable_server_certificate_verification(false);
  8003. cli.set_connection_timeout(30);
  8004. bool serial_checked = false;
  8005. cli.set_server_certificate_verifier(
  8006. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  8007. (void)session;
  8008. if (peer_cert) {
  8009. std::string serial = tls_get_cert_serial(peer_cert);
  8010. EXPECT_FALSE(serial.empty());
  8011. // Serial should be a hex string
  8012. for (char c : serial) {
  8013. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  8014. (c >= 'a' && c <= 'f'));
  8015. }
  8016. serial_checked = true;
  8017. }
  8018. return true;
  8019. });
  8020. auto res = cli.Get("/test");
  8021. ASSERT_TRUE(res);
  8022. EXPECT_TRUE(serial_checked);
  8023. }
  8024. #endif
  8025. #ifdef CPPHTTPLIB_SSL_ENABLED
  8026. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  8027. // Test 1: Valid CA file - no error should be recorded
  8028. {
  8029. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  8030. CLIENT_CA_CERT_FILE);
  8031. ASSERT_TRUE(svr.is_valid());
  8032. // With valid setup, last_ssl_error should be 0
  8033. EXPECT_EQ(0, svr.ssl_last_error());
  8034. }
  8035. // Test 2: Invalid CA file content
  8036. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  8037. {
  8038. // Create a temporary file with completely invalid content
  8039. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  8040. {
  8041. std::ofstream ofs(temp_invalid_ca);
  8042. ofs << "This is not a certificate file at all\n";
  8043. ofs << "Just plain text content\n";
  8044. }
  8045. // Create server with invalid CA file
  8046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  8047. // Clean up temporary file
  8048. std::remove(temp_invalid_ca);
  8049. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  8050. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  8051. // Note: SSL_CTX_load_verify_locations typically fails first,
  8052. // but our error handling code path is still exercised
  8053. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  8054. }
  8055. }
  8056. #endif
  8057. #ifdef CPPHTTPLIB_SSL_ENABLED
  8058. TEST(TlsVerifyCallbackExTest, ExtendedCallback) {
  8059. using namespace httplib::detail::tls;
  8060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8061. ASSERT_TRUE(svr.is_valid());
  8062. svr.Get("/test", [](const Request &, Response &res) {
  8063. res.set_content("ok", "text/plain");
  8064. });
  8065. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8066. auto se = detail::scope_exit([&] {
  8067. svr.stop();
  8068. t.join();
  8069. });
  8070. svr.wait_until_ready();
  8071. SSLClient cli(HOST, PORT);
  8072. cli.enable_server_certificate_verification(false);
  8073. cli.set_connection_timeout(30);
  8074. int callback_count = 0;
  8075. bool saw_leaf_cert = false;
  8076. // Use the new extended callback via the context directly
  8077. // Note: This tests the internal API, real usage would be through
  8078. // set_server_certificate_verifier
  8079. cli.set_server_certificate_verifier(
  8080. [&](tls_session_t session, tls_cert_t peer_cert) -> bool {
  8081. (void)session;
  8082. if (peer_cert) {
  8083. callback_count++;
  8084. // We should see at least one certificate (the leaf)
  8085. std::string cn = tls_get_cert_subject_cn(peer_cert);
  8086. if (!cn.empty()) { saw_leaf_cert = true; }
  8087. }
  8088. return true;
  8089. });
  8090. auto res = cli.Get("/test");
  8091. ASSERT_TRUE(res);
  8092. EXPECT_GT(callback_count, 0);
  8093. EXPECT_TRUE(saw_leaf_cert);
  8094. }
  8095. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  8096. using namespace httplib::detail::tls;
  8097. // Test that tls_verify_error_string returns empty for success
  8098. std::string success_str = tls_verify_error_string(0);
  8099. EXPECT_TRUE(success_str.empty());
  8100. // Test that tls_verify_error_string returns non-empty for error codes
  8101. // Using a common error code (certificate expired)
  8102. std::string error_str =
  8103. tls_verify_error_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  8104. EXPECT_FALSE(error_str.empty());
  8105. }
  8106. #endif
  8107. #ifdef CPPHTTPLIB_SSL_ENABLED
  8108. TEST(CryptoHashTest, BasicHashing) {
  8109. namespace crypto = httplib::detail::crypto;
  8110. // Test MD5
  8111. std::string md5_result = crypto::hash(crypto::HashAlgorithm::MD5, "hello");
  8112. EXPECT_EQ("5d41402abc4b2a76b9719d911017c592", md5_result);
  8113. // Test SHA256
  8114. std::string sha256_result =
  8115. crypto::hash(crypto::HashAlgorithm::SHA256, "hello");
  8116. EXPECT_EQ("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
  8117. sha256_result);
  8118. // Test SHA512
  8119. std::string sha512_result =
  8120. crypto::hash(crypto::HashAlgorithm::SHA512, "hello");
  8121. EXPECT_EQ(
  8122. "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d9"
  8123. "9ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043",
  8124. sha512_result);
  8125. }
  8126. TEST(CryptoHashTest, HashSize) {
  8127. namespace crypto = httplib::detail::crypto;
  8128. EXPECT_EQ(16u, crypto::hash_size(crypto::HashAlgorithm::MD5));
  8129. EXPECT_EQ(20u, crypto::hash_size(crypto::HashAlgorithm::SHA1));
  8130. EXPECT_EQ(32u, crypto::hash_size(crypto::HashAlgorithm::SHA256));
  8131. EXPECT_EQ(48u, crypto::hash_size(crypto::HashAlgorithm::SHA384));
  8132. EXPECT_EQ(64u, crypto::hash_size(crypto::HashAlgorithm::SHA512));
  8133. }
  8134. TEST(CryptoHashTest, HashRaw) {
  8135. namespace crypto = httplib::detail::crypto;
  8136. std::vector<uint8_t> digest;
  8137. bool result =
  8138. crypto::hash_raw(crypto::HashAlgorithm::SHA256, "test", 4, digest);
  8139. EXPECT_TRUE(result);
  8140. EXPECT_EQ(32u, digest.size());
  8141. // Verify first few bytes match known SHA256 of "test"
  8142. // SHA256("test") =
  8143. // 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
  8144. EXPECT_EQ(0x9f, digest[0]);
  8145. EXPECT_EQ(0x86, digest[1]);
  8146. EXPECT_EQ(0xd0, digest[2]);
  8147. }
  8148. #endif
  8149. #ifdef CPPHTTPLIB_SSL_ENABLED
  8150. TEST(SSLClientServerTest, ClientCAListFromPem) {
  8151. // Test SSL server using PemMemory constructor with client CA certificates
  8152. // This is the backend-agnostic equivalent of ClientCAListFromX509Store test
  8153. // Read PEM files
  8154. std::string server_cert_pem, server_key_pem, client_ca_pem;
  8155. read_file(SERVER_CERT_FILE, server_cert_pem);
  8156. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  8157. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  8158. // Create SSLServer with PemMemory constructor including client CA
  8159. SSLServer::PemMemory server_pem = {
  8160. server_cert_pem.c_str(),
  8161. server_cert_pem.size(),
  8162. server_key_pem.c_str(),
  8163. server_key_pem.size(),
  8164. client_ca_pem.c_str(),
  8165. client_ca_pem.size(),
  8166. nullptr // no password for server key
  8167. };
  8168. SSLServer svr(server_pem);
  8169. ASSERT_TRUE(svr.is_valid());
  8170. // No SSL error should be recorded for valid setup
  8171. EXPECT_EQ(0, svr.ssl_last_error());
  8172. // Set up server endpoints
  8173. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  8174. res.set_content("ok", "text/plain");
  8175. });
  8176. // Start server in a thread
  8177. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  8178. svr.wait_until_ready();
  8179. // Connect with client certificate (using constructor with paths)
  8180. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  8181. cli.enable_server_certificate_verification(false);
  8182. auto res = cli.Get("/test-pem-ca");
  8183. ASSERT_TRUE(res);
  8184. EXPECT_EQ(200, res->status);
  8185. EXPECT_EQ("ok", res->body);
  8186. svr.stop();
  8187. server_thread.join();
  8188. }
  8189. #endif
  8190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8191. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  8192. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  8193. // prepare large data
  8194. std::random_device seed_gen;
  8195. std::mt19937 random(seed_gen());
  8196. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  8197. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  8198. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  8199. // server
  8200. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8201. ASSERT_TRUE(svr.is_valid());
  8202. svr.Post("/binary", [&](const Request &req, Response &res) {
  8203. EXPECT_EQ(large_size_byte, req.body.size());
  8204. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  8205. res.set_content(req.body, "application/octet-stream");
  8206. });
  8207. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  8208. auto se = detail::scope_exit([&] {
  8209. svr.stop();
  8210. listen_thread.join();
  8211. ASSERT_FALSE(svr.is_running());
  8212. });
  8213. svr.wait_until_ready();
  8214. // client POST
  8215. SSLClient cli("localhost", PORT);
  8216. cli.enable_server_certificate_verification(false);
  8217. cli.set_read_timeout(std::chrono::seconds(100));
  8218. cli.set_write_timeout(std::chrono::seconds(100));
  8219. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  8220. large_size_byte, "application/octet-stream");
  8221. // compare
  8222. EXPECT_EQ(StatusCode::OK_200, res->status);
  8223. EXPECT_EQ(large_size_byte, res->body.size());
  8224. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  8225. }
  8226. #endif
  8227. #ifdef _WIN32
  8228. TEST(CleanupTest, WSACleanup) {
  8229. int ret = WSACleanup();
  8230. ASSERT_EQ(0, ret);
  8231. }
  8232. #endif
  8233. #ifndef CPPHTTPLIB_SSL_ENABLED
  8234. TEST(NoSSLSupport, SimpleInterface) {
  8235. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  8236. }
  8237. #endif
  8238. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  8239. TEST(InvalidScheme, SimpleInterface) {
  8240. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  8241. }
  8242. #endif
  8243. TEST(NoScheme, SimpleInterface) {
  8244. Client cli("yahoo.com:80");
  8245. ASSERT_TRUE(cli.is_valid());
  8246. }
  8247. TEST(SendAPI, SimpleInterface_Online) {
  8248. Client cli("http://yahoo.com");
  8249. Request req;
  8250. req.method = "GET";
  8251. req.path = "/";
  8252. auto res = cli.send(req);
  8253. ASSERT_TRUE(res);
  8254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8255. }
  8256. TEST(SendAPI, WithParamsInRequest) {
  8257. Server svr;
  8258. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  8259. EXPECT_TRUE(req.has_param("test"));
  8260. EXPECT_EQ("test_value", req.get_param_value("test"));
  8261. });
  8262. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  8263. auto se = detail::scope_exit([&] {
  8264. svr.stop();
  8265. t.join();
  8266. ASSERT_FALSE(svr.is_running());
  8267. });
  8268. svr.wait_until_ready();
  8269. Client cli(HOST, PORT);
  8270. {
  8271. Request req;
  8272. req.method = "GET";
  8273. req.path = "/";
  8274. req.params.emplace("test", "test_value");
  8275. auto res = cli.send(req);
  8276. ASSERT_TRUE(res);
  8277. }
  8278. {
  8279. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  8280. ASSERT_TRUE(res);
  8281. }
  8282. }
  8283. TEST(ClientImplMethods, GetSocketTest) {
  8284. httplib::Server svr;
  8285. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  8286. res.status = StatusCode::OK_200;
  8287. });
  8288. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  8289. auto se = detail::scope_exit([&] {
  8290. svr.stop();
  8291. thread.join();
  8292. ASSERT_FALSE(svr.is_running());
  8293. });
  8294. svr.wait_until_ready();
  8295. {
  8296. httplib::Client cli("http://127.0.0.1:3333");
  8297. cli.set_keep_alive(true);
  8298. // Use the behavior of cpp-httplib of opening the connection
  8299. // only when the first request happens. If that changes,
  8300. // this test would be obsolete.
  8301. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  8302. // This also implicitly tests the server. But other tests would fail much
  8303. // earlier than this one to be considered.
  8304. auto res = cli.Get("/");
  8305. ASSERT_TRUE(res);
  8306. EXPECT_EQ(StatusCode::OK_200, res->status);
  8307. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  8308. }
  8309. }
  8310. // Disabled due to out-of-memory problem on GitHub Actions
  8311. #ifdef _WIN64
  8312. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  8313. // allocate content size larger than 2GB in memory
  8314. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  8315. char *content = (char *)malloc(content_size);
  8316. ASSERT_TRUE(content);
  8317. Server svr;
  8318. svr.Get("/foo",
  8319. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  8320. res.set_content(content, content_size, "application/octet-stream");
  8321. });
  8322. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  8323. auto se = detail::scope_exit([&] {
  8324. svr.stop();
  8325. listen_thread.join();
  8326. if (content) free(content);
  8327. ASSERT_FALSE(svr.is_running());
  8328. });
  8329. svr.wait_until_ready();
  8330. Client cli(HOST, PORT);
  8331. auto res = cli.Get("/foo");
  8332. ASSERT_TRUE(res);
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ(content_size, res->body.length());
  8335. }
  8336. #endif
  8337. #ifdef CPPHTTPLIB_SSL_ENABLED
  8338. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  8339. Client cli("http://yahoo.com");
  8340. auto res = cli.Get("/");
  8341. ASSERT_TRUE(res);
  8342. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8343. cli.set_follow_location(true);
  8344. res = cli.Get("/");
  8345. ASSERT_TRUE(res);
  8346. EXPECT_EQ(StatusCode::OK_200, res->status);
  8347. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8348. }
  8349. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  8350. Client cli("https://yahoo.com");
  8351. auto res = cli.Get("/");
  8352. ASSERT_TRUE(res);
  8353. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8354. cli.set_follow_location(true);
  8355. res = cli.Get("/");
  8356. ASSERT_TRUE(res);
  8357. EXPECT_EQ(StatusCode::OK_200, res->status);
  8358. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8359. }
  8360. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  8361. Client cli("https://yahoo.com");
  8362. auto res = cli.Get("/");
  8363. ASSERT_TRUE(res);
  8364. ASSERT_FALSE(!res);
  8365. ASSERT_TRUE(res);
  8366. ASSERT_FALSE(res == nullptr);
  8367. ASSERT_TRUE(res != nullptr);
  8368. EXPECT_EQ(Error::Success, res.error());
  8369. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  8370. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  8371. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  8372. cli.set_follow_location(true);
  8373. res = cli.Get("/");
  8374. ASSERT_TRUE(res);
  8375. EXPECT_EQ(Error::Success, res.error());
  8376. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  8377. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  8378. EXPECT_EQ(StatusCode::OK_200, res->status);
  8379. EXPECT_EQ("https://www.yahoo.com/", res->location);
  8380. }
  8381. #endif
  8382. #ifdef CPPHTTPLIB_SSL_ENABLED
  8383. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8384. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  8385. Client cli("https://cdnjs.cloudflare.com");
  8386. auto res =
  8387. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  8388. ASSERT_TRUE(res);
  8389. EXPECT_EQ(StatusCode::OK_200, res->status);
  8390. EXPECT_EQ(287630U, res->body.size());
  8391. EXPECT_EQ("application/javascript; charset=utf-8",
  8392. res->get_header_value("Content-Type"));
  8393. }
  8394. #endif
  8395. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  8396. #undef REDIR_HOST // Silence compiler warning
  8397. #define REDIR_HOST "https://httpbingo.org"
  8398. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  8399. Client cli(REDIR_HOST);
  8400. cli.set_follow_location(true);
  8401. auto res =
  8402. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8403. ASSERT_TRUE(res);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8407. Client cli(REDIR_HOST);
  8408. cli.set_follow_location(true);
  8409. Params params;
  8410. params.emplace("url", "http://example.com");
  8411. params.emplace("status_code", "302");
  8412. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8413. ASSERT_TRUE(res);
  8414. EXPECT_EQ(StatusCode::OK_200, res->status);
  8415. }
  8416. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8417. Client cli(REDIR_HOST);
  8418. cli.set_follow_location(true);
  8419. Params params;
  8420. params.emplace("url", "http://example.com");
  8421. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8422. ASSERT_TRUE(res);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. #ifdef CPPHTTPLIB_SSL_ENABLED
  8426. TEST(HttpToHttpsRedirectTest, CertFile) {
  8427. Server svr;
  8428. ASSERT_TRUE(svr.is_valid());
  8429. svr.Get("/index", [&](const Request &, Response &res) {
  8430. res.set_redirect("https://127.0.0.1:1235/index");
  8431. svr.stop();
  8432. });
  8433. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8434. ASSERT_TRUE(ssl_svr.is_valid());
  8435. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8436. res.set_content("test", "text/plain");
  8437. ssl_svr.stop();
  8438. });
  8439. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8440. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8441. auto se = detail::scope_exit([&] {
  8442. t2.join();
  8443. t.join();
  8444. ASSERT_FALSE(svr.is_running());
  8445. });
  8446. svr.wait_until_ready();
  8447. ssl_svr.wait_until_ready();
  8448. Client cli("127.0.0.1", PORT);
  8449. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8450. cli.enable_server_certificate_verification(true);
  8451. cli.set_follow_location(true);
  8452. cli.set_connection_timeout(30);
  8453. auto res = cli.Get("/index");
  8454. ASSERT_TRUE(res);
  8455. ASSERT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST(SSLClientRedirectTest, CertFile) {
  8458. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8459. ASSERT_TRUE(ssl_svr1.is_valid());
  8460. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8461. res.set_redirect("https://127.0.0.1:1235/index");
  8462. ssl_svr1.stop();
  8463. });
  8464. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8465. ASSERT_TRUE(ssl_svr2.is_valid());
  8466. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8467. res.set_content("test", "text/plain");
  8468. ssl_svr2.stop();
  8469. });
  8470. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8471. thread t2 =
  8472. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8473. auto se = detail::scope_exit([&] {
  8474. t2.join();
  8475. t.join();
  8476. ASSERT_FALSE(ssl_svr1.is_running());
  8477. });
  8478. ssl_svr1.wait_until_ready();
  8479. ssl_svr2.wait_until_ready();
  8480. SSLClient cli("127.0.0.1", PORT);
  8481. std::string cert;
  8482. read_file(SERVER_CERT2_FILE, cert);
  8483. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8484. cli.enable_server_certificate_verification(true);
  8485. cli.set_follow_location(true);
  8486. cli.set_connection_timeout(30);
  8487. auto res = cli.Get("/index");
  8488. ASSERT_TRUE(res);
  8489. ASSERT_EQ(StatusCode::OK_200, res->status);
  8490. }
  8491. #endif
  8492. TEST(MultipartFormDataTest, LargeData) {
  8493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8494. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8495. const ContentReader &content_reader) {
  8496. if (req.is_multipart_form_data()) {
  8497. std::vector<FormData> items;
  8498. content_reader(
  8499. [&](const FormData &file) {
  8500. items.push_back(file);
  8501. return true;
  8502. },
  8503. [&](const char *data, size_t data_length) {
  8504. items.back().content.append(data, data_length);
  8505. return true;
  8506. });
  8507. EXPECT_TRUE(std::string(items[0].name) == "document");
  8508. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8509. EXPECT_TRUE(items[0].filename == "2MB_data");
  8510. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8511. EXPECT_TRUE(items[1].name == "hello");
  8512. EXPECT_TRUE(items[1].content == "world");
  8513. EXPECT_TRUE(items[1].filename == "");
  8514. EXPECT_TRUE(items[1].content_type == "");
  8515. } else {
  8516. std::string body;
  8517. content_reader([&](const char *data, size_t data_length) {
  8518. body.append(data, data_length);
  8519. return true;
  8520. });
  8521. }
  8522. });
  8523. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8524. auto se = detail::scope_exit([&] {
  8525. svr.stop();
  8526. t.join();
  8527. ASSERT_FALSE(svr.is_running());
  8528. });
  8529. svr.wait_until_ready();
  8530. {
  8531. std::string data(1024 * 1024 * 2, '.');
  8532. std::stringstream buffer;
  8533. buffer << data;
  8534. Client cli("https://localhost:8080");
  8535. cli.enable_server_certificate_verification(false);
  8536. UploadFormDataItems items{
  8537. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8538. {"hello", "world", "", ""},
  8539. };
  8540. auto res = cli.Post("/post", items);
  8541. ASSERT_TRUE(res);
  8542. ASSERT_EQ(StatusCode::OK_200, res->status);
  8543. }
  8544. }
  8545. TEST(MultipartFormDataTest, DataProviderItems) {
  8546. std::random_device seed_gen;
  8547. std::mt19937 random(seed_gen());
  8548. std::string rand1;
  8549. rand1.resize(1000);
  8550. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8551. std::string rand2;
  8552. rand2.resize(3000);
  8553. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8555. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8556. const ContentReader &content_reader) {
  8557. ASSERT_FALSE(req.is_multipart_form_data());
  8558. std::string body;
  8559. content_reader([&](const char *data, size_t data_length) {
  8560. body.append(data, data_length);
  8561. return true;
  8562. });
  8563. EXPECT_EQ(body, "");
  8564. });
  8565. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8566. const ContentReader &content_reader) {
  8567. ASSERT_TRUE(req.is_multipart_form_data());
  8568. std::vector<FormData> items;
  8569. content_reader(
  8570. [&](const FormData &file) {
  8571. items.push_back(file);
  8572. return true;
  8573. },
  8574. [&](const char *data, size_t data_length) {
  8575. items.back().content.append(data, data_length);
  8576. return true;
  8577. });
  8578. ASSERT_TRUE(items.size() == 2);
  8579. EXPECT_EQ(std::string(items[0].name), "name1");
  8580. EXPECT_EQ(items[0].content, "Testing123");
  8581. EXPECT_EQ(items[0].filename, "filename1");
  8582. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8583. EXPECT_EQ(items[1].name, "name2");
  8584. EXPECT_EQ(items[1].content, "Testing456");
  8585. EXPECT_EQ(items[1].filename, "");
  8586. EXPECT_EQ(items[1].content_type, "");
  8587. });
  8588. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8589. const ContentReader &content_reader) {
  8590. ASSERT_TRUE(req.is_multipart_form_data());
  8591. std::vector<FormData> items;
  8592. content_reader(
  8593. [&](const FormData &file) {
  8594. items.push_back(file);
  8595. return true;
  8596. },
  8597. [&](const char *data, size_t data_length) {
  8598. items.back().content.append(data, data_length);
  8599. return true;
  8600. });
  8601. ASSERT_TRUE(items.size() == 2);
  8602. EXPECT_EQ(items[0].name, "name3");
  8603. EXPECT_EQ(items[0].content, rand1);
  8604. EXPECT_EQ(items[0].filename, "filename3");
  8605. EXPECT_EQ(items[0].content_type, "");
  8606. EXPECT_EQ(items[1].name, "name4");
  8607. EXPECT_EQ(items[1].content, rand2);
  8608. EXPECT_EQ(items[1].filename, "filename4");
  8609. EXPECT_EQ(items[1].content_type, "");
  8610. });
  8611. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8612. const ContentReader &content_reader) {
  8613. ASSERT_TRUE(req.is_multipart_form_data());
  8614. std::vector<FormData> items;
  8615. content_reader(
  8616. [&](const FormData &file) {
  8617. items.push_back(file);
  8618. return true;
  8619. },
  8620. [&](const char *data, size_t data_length) {
  8621. items.back().content.append(data, data_length);
  8622. return true;
  8623. });
  8624. ASSERT_TRUE(items.size() == 4);
  8625. EXPECT_EQ(std::string(items[0].name), "name1");
  8626. EXPECT_EQ(items[0].content, "Testing123");
  8627. EXPECT_EQ(items[0].filename, "filename1");
  8628. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8629. EXPECT_EQ(items[1].name, "name2");
  8630. EXPECT_EQ(items[1].content, "Testing456");
  8631. EXPECT_EQ(items[1].filename, "");
  8632. EXPECT_EQ(items[1].content_type, "");
  8633. EXPECT_EQ(items[2].name, "name3");
  8634. EXPECT_EQ(items[2].content, rand1);
  8635. EXPECT_EQ(items[2].filename, "filename3");
  8636. EXPECT_EQ(items[2].content_type, "");
  8637. EXPECT_EQ(items[3].name, "name4");
  8638. EXPECT_EQ(items[3].content, rand2);
  8639. EXPECT_EQ(items[3].filename, "filename4");
  8640. EXPECT_EQ(items[3].content_type, "");
  8641. });
  8642. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8643. auto se = detail::scope_exit([&] {
  8644. svr.stop();
  8645. t.join();
  8646. ASSERT_FALSE(svr.is_running());
  8647. });
  8648. svr.wait_until_ready();
  8649. {
  8650. Client cli("https://localhost:8080");
  8651. cli.enable_server_certificate_verification(false);
  8652. UploadFormDataItems items{
  8653. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8654. {"name2", "Testing456", "", ""}, // not a file
  8655. };
  8656. {
  8657. auto res = cli.Post("/post-none", {}, {}, {});
  8658. ASSERT_TRUE(res);
  8659. ASSERT_EQ(StatusCode::OK_200, res->status);
  8660. }
  8661. FormDataProviderItems providers;
  8662. {
  8663. auto res =
  8664. cli.Post("/post-items", {}, items, providers); // empty providers
  8665. ASSERT_TRUE(res);
  8666. ASSERT_EQ(StatusCode::OK_200, res->status);
  8667. }
  8668. providers.push_back({"name3",
  8669. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8670. // test the offset is given correctly at each step
  8671. if (!offset)
  8672. sink.os.write(rand1.data(), 30);
  8673. else if (offset == 30)
  8674. sink.os.write(rand1.data() + 30, 300);
  8675. else if (offset == 330)
  8676. sink.os.write(rand1.data() + 330, 670);
  8677. else if (offset == rand1.size())
  8678. sink.done();
  8679. return true;
  8680. },
  8681. "filename3",
  8682. {}});
  8683. providers.push_back({"name4",
  8684. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8685. // test the offset is given correctly at each step
  8686. if (!offset)
  8687. sink.os.write(rand2.data(), 2000);
  8688. else if (offset == 2000)
  8689. sink.os.write(rand2.data() + 2000, 1);
  8690. else if (offset == 2001)
  8691. sink.os.write(rand2.data() + 2001, 999);
  8692. else if (offset == rand2.size())
  8693. sink.done();
  8694. return true;
  8695. },
  8696. "filename4",
  8697. {}});
  8698. {
  8699. auto res = cli.Post("/post-providers", {}, {}, providers);
  8700. ASSERT_TRUE(res);
  8701. ASSERT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. {
  8704. auto res = cli.Post("/post-both", {}, items, providers);
  8705. ASSERT_TRUE(res);
  8706. ASSERT_EQ(StatusCode::OK_200, res->status);
  8707. }
  8708. }
  8709. }
  8710. TEST(MultipartFormDataTest, BadHeader) {
  8711. Server svr;
  8712. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8713. res.set_content("ok", "text/plain");
  8714. });
  8715. thread t = thread([&] { svr.listen(HOST, PORT); });
  8716. auto se = detail::scope_exit([&] {
  8717. svr.stop();
  8718. t.join();
  8719. ASSERT_FALSE(svr.is_running());
  8720. });
  8721. svr.wait_until_ready();
  8722. const std::string body =
  8723. "This is the preamble. It is to be ignored, though it\r\n"
  8724. "is a handy place for composition agents to include an\r\n"
  8725. "explanatory note to non-MIME conformant readers.\r\n"
  8726. "\r\n"
  8727. "\r\n"
  8728. "--simple boundary\r\n"
  8729. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8730. ": BAD...\r\n"
  8731. "\r\n"
  8732. "value1\r\n"
  8733. "--simple boundary\r\n"
  8734. "Content-Disposition: form-data; name=\"field2\"; "
  8735. "filename=\"example.txt\"\r\n"
  8736. "\r\n"
  8737. "value2\r\n"
  8738. "--simple boundary--\r\n"
  8739. "This is the epilogue. It is also to be ignored.\r\n";
  8740. std::string content_type =
  8741. R"(multipart/form-data; boundary="simple boundary")";
  8742. Client cli(HOST, PORT);
  8743. auto res = cli.Post("/post", body, content_type.c_str());
  8744. ASSERT_TRUE(res);
  8745. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8746. }
  8747. TEST(MultipartFormDataTest, WithPreamble) {
  8748. Server svr;
  8749. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8750. res.set_content("ok", "text/plain");
  8751. });
  8752. thread t = thread([&] { svr.listen(HOST, PORT); });
  8753. auto se = detail::scope_exit([&] {
  8754. svr.stop();
  8755. t.join();
  8756. ASSERT_FALSE(svr.is_running());
  8757. });
  8758. svr.wait_until_ready();
  8759. const std::string body =
  8760. "This is the preamble. It is to be ignored, though it\r\n"
  8761. "is a handy place for composition agents to include an\r\n"
  8762. "explanatory note to non-MIME conformant readers.\r\n"
  8763. "\r\n"
  8764. "\r\n"
  8765. "--simple boundary\r\n"
  8766. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8767. "\r\n"
  8768. "value1\r\n"
  8769. "--simple boundary\r\n"
  8770. "Content-Disposition: form-data; name=\"field2\"; "
  8771. "filename=\"example.txt\"\r\n"
  8772. "\r\n"
  8773. "value2\r\n"
  8774. "--simple boundary--\r\n"
  8775. "This is the epilogue. It is also to be ignored.\r\n";
  8776. std::string content_type =
  8777. R"(multipart/form-data; boundary="simple boundary")";
  8778. Client cli(HOST, PORT);
  8779. auto res = cli.Post("/post", body, content_type.c_str());
  8780. ASSERT_TRUE(res);
  8781. EXPECT_EQ(StatusCode::OK_200, res->status);
  8782. }
  8783. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8784. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8785. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8786. const ContentReader &content_reader) {
  8787. if (req.is_multipart_form_data()) {
  8788. std::vector<FormData> items;
  8789. content_reader(
  8790. [&](const FormData &file) {
  8791. items.push_back(file);
  8792. return true;
  8793. },
  8794. [&](const char *data, size_t data_length) {
  8795. items.back().content.append(data, data_length);
  8796. return true;
  8797. });
  8798. EXPECT_TRUE(std::string(items[0].name) == "document");
  8799. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8800. EXPECT_TRUE(items[0].filename == "2MB_data");
  8801. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8802. EXPECT_TRUE(items[1].name == "hello");
  8803. EXPECT_TRUE(items[1].content == "world");
  8804. EXPECT_TRUE(items[1].filename == "");
  8805. EXPECT_TRUE(items[1].content_type == "");
  8806. } else {
  8807. std::string body;
  8808. content_reader([&](const char *data, size_t data_length) {
  8809. body.append(data, data_length);
  8810. return true;
  8811. });
  8812. }
  8813. });
  8814. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8815. auto se = detail::scope_exit([&] {
  8816. svr.stop();
  8817. t.join();
  8818. ASSERT_FALSE(svr.is_running());
  8819. });
  8820. svr.wait_until_ready();
  8821. {
  8822. std::string data(1024 * 1024 * 2, '.');
  8823. std::stringstream buffer;
  8824. buffer << data;
  8825. Client cli("https://localhost:8080");
  8826. cli.enable_server_certificate_verification(false);
  8827. UploadFormDataItems items{
  8828. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8829. {"hello", "world", "", ""},
  8830. };
  8831. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8832. ASSERT_TRUE(res);
  8833. ASSERT_EQ(StatusCode::OK_200, res->status);
  8834. }
  8835. }
  8836. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8837. std::string data(1024 * 1024 * 2, '&');
  8838. std::stringstream buffer;
  8839. buffer << data;
  8840. Client cli("https://localhost:8080");
  8841. UploadFormDataItems items{
  8842. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8843. {"hello", "world", "", ""},
  8844. };
  8845. for (const char &c : " \t\r\n") {
  8846. auto res =
  8847. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8848. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8849. ASSERT_FALSE(res);
  8850. }
  8851. }
  8852. TEST(MultipartFormDataTest, PutFormData) {
  8853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8854. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8855. const ContentReader &content_reader) {
  8856. if (req.is_multipart_form_data()) {
  8857. std::vector<FormData> items;
  8858. content_reader(
  8859. [&](const FormData &file) {
  8860. items.push_back(file);
  8861. return true;
  8862. },
  8863. [&](const char *data, size_t data_length) {
  8864. items.back().content.append(data, data_length);
  8865. return true;
  8866. });
  8867. EXPECT_TRUE(std::string(items[0].name) == "document");
  8868. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8869. EXPECT_TRUE(items[0].filename == "2MB_data");
  8870. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8871. EXPECT_TRUE(items[1].name == "hello");
  8872. EXPECT_TRUE(items[1].content == "world");
  8873. EXPECT_TRUE(items[1].filename == "");
  8874. EXPECT_TRUE(items[1].content_type == "");
  8875. } else {
  8876. std::string body;
  8877. content_reader([&](const char *data, size_t data_length) {
  8878. body.append(data, data_length);
  8879. return true;
  8880. });
  8881. }
  8882. });
  8883. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8884. auto se = detail::scope_exit([&] {
  8885. svr.stop();
  8886. t.join();
  8887. ASSERT_FALSE(svr.is_running());
  8888. });
  8889. svr.wait_until_ready();
  8890. {
  8891. std::string data(1024 * 1024 * 2, '&');
  8892. std::stringstream buffer;
  8893. buffer << data;
  8894. Client cli("https://localhost:8080");
  8895. cli.enable_server_certificate_verification(false);
  8896. UploadFormDataItems items{
  8897. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8898. {"hello", "world", "", ""},
  8899. };
  8900. auto res = cli.Put("/put", items);
  8901. ASSERT_TRUE(res);
  8902. ASSERT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. }
  8905. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8907. svr.Put("/put_customboundary",
  8908. [&](const Request &req, const Response & /*res*/,
  8909. const ContentReader &content_reader) {
  8910. if (req.is_multipart_form_data()) {
  8911. std::vector<FormData> items;
  8912. content_reader(
  8913. [&](const FormData &file) {
  8914. items.push_back(file);
  8915. return true;
  8916. },
  8917. [&](const char *data, size_t data_length) {
  8918. items.back().content.append(data, data_length);
  8919. return true;
  8920. });
  8921. EXPECT_TRUE(std::string(items[0].name) == "document");
  8922. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8923. EXPECT_TRUE(items[0].filename == "2MB_data");
  8924. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8925. EXPECT_TRUE(items[1].name == "hello");
  8926. EXPECT_TRUE(items[1].content == "world");
  8927. EXPECT_TRUE(items[1].filename == "");
  8928. EXPECT_TRUE(items[1].content_type == "");
  8929. } else {
  8930. std::string body;
  8931. content_reader([&](const char *data, size_t data_length) {
  8932. body.append(data, data_length);
  8933. return true;
  8934. });
  8935. }
  8936. });
  8937. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8938. auto se = detail::scope_exit([&] {
  8939. svr.stop();
  8940. t.join();
  8941. ASSERT_FALSE(svr.is_running());
  8942. });
  8943. svr.wait_until_ready();
  8944. {
  8945. std::string data(1024 * 1024 * 2, '&');
  8946. std::stringstream buffer;
  8947. buffer << data;
  8948. Client cli("https://localhost:8080");
  8949. cli.enable_server_certificate_verification(false);
  8950. UploadFormDataItems items{
  8951. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8952. {"hello", "world", "", ""},
  8953. };
  8954. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8955. ASSERT_TRUE(res);
  8956. ASSERT_EQ(StatusCode::OK_200, res->status);
  8957. }
  8958. }
  8959. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8960. std::string data(1024 * 1024 * 2, '&');
  8961. std::stringstream buffer;
  8962. buffer << data;
  8963. Client cli("https://localhost:8080");
  8964. cli.enable_server_certificate_verification(false);
  8965. UploadFormDataItems items{
  8966. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8967. {"hello", "world", "", ""},
  8968. };
  8969. for (const char &c : " \t\r\n") {
  8970. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8971. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8972. ASSERT_FALSE(res);
  8973. }
  8974. }
  8975. TEST(MultipartFormDataTest, AlternateFilename) {
  8976. auto handled = false;
  8977. Server svr;
  8978. svr.Post("/test", [&](const Request &req, Response &res) {
  8979. ASSERT_EQ(2u, req.form.files.size());
  8980. ASSERT_EQ(1u, req.form.fields.size());
  8981. // Test files
  8982. const auto &file1 = req.form.get_file("file1");
  8983. ASSERT_EQ("file1", file1.name);
  8984. ASSERT_EQ("A.txt", file1.filename);
  8985. ASSERT_EQ("text/plain", file1.content_type);
  8986. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8987. const auto &file2 = req.form.get_file("file2");
  8988. ASSERT_EQ("file2", file2.name);
  8989. ASSERT_EQ("a.html", file2.filename);
  8990. ASSERT_EQ("text/html", file2.content_type);
  8991. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8992. file2.content);
  8993. // Test text field
  8994. const auto &text = req.form.get_field("text");
  8995. ASSERT_EQ("text default", text);
  8996. res.set_content("ok", "text/plain");
  8997. handled = true;
  8998. });
  8999. thread t = thread([&] { svr.listen(HOST, PORT); });
  9000. auto se = detail::scope_exit([&] {
  9001. svr.stop();
  9002. t.join();
  9003. ASSERT_FALSE(svr.is_running());
  9004. ASSERT_TRUE(handled);
  9005. });
  9006. svr.wait_until_ready();
  9007. auto req = "POST /test HTTP/1.1\r\n"
  9008. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9009. "Content-Length: 399\r\n"
  9010. "\r\n"
  9011. "----------\r\n"
  9012. "Content-Disposition: form-data; name=\"text\"\r\n"
  9013. "\r\n"
  9014. "text default\r\n"
  9015. "----------\r\n"
  9016. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  9017. "filename=\"a.txt\"; name=\"file1\"\r\n"
  9018. "Content-Type: text/plain\r\n"
  9019. "\r\n"
  9020. "Content of a.txt.\r\n"
  9021. "\r\n"
  9022. "----------\r\n"
  9023. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  9024. "\"a.html\"\r\n"
  9025. "Content-Type: text/html\r\n"
  9026. "\r\n"
  9027. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  9028. "\r\n"
  9029. "------------\r\n";
  9030. ASSERT_TRUE(send_request(1, req));
  9031. }
  9032. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  9033. auto handled = false;
  9034. Server svr;
  9035. svr.Post("/test", [&](const Request &req, Response &) {
  9036. ASSERT_EQ(2u, req.form.fields.size());
  9037. const auto &text1 = req.form.get_field("text1");
  9038. ASSERT_EQ("text1", text1);
  9039. const auto &text2 = req.form.get_field("text2");
  9040. ASSERT_EQ("text2", text2);
  9041. handled = true;
  9042. });
  9043. thread t = thread([&] { svr.listen(HOST, PORT); });
  9044. auto se = detail::scope_exit([&] {
  9045. svr.stop();
  9046. t.join();
  9047. ASSERT_FALSE(svr.is_running());
  9048. ASSERT_TRUE(handled);
  9049. });
  9050. svr.wait_until_ready();
  9051. auto req = "POST /test HTTP/1.1\r\n"
  9052. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9053. "Content-Length: 146\r\n"
  9054. "\r\n----------\r\n"
  9055. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9056. "\r\n"
  9057. "text1"
  9058. "\r\n----------\r\n"
  9059. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9060. "\r\n"
  9061. "text2"
  9062. "\r\n------------";
  9063. std::string response;
  9064. ASSERT_TRUE(send_request(1, req, &response));
  9065. ASSERT_EQ("200", response.substr(9, 3));
  9066. }
  9067. TEST(MultipartFormDataTest, ContentLength) {
  9068. auto handled = false;
  9069. Server svr;
  9070. svr.Post("/test", [&](const Request &req, Response &) {
  9071. ASSERT_EQ(2u, req.form.fields.size());
  9072. const auto &text1 = req.form.get_field("text1");
  9073. ASSERT_EQ("text1", text1);
  9074. const auto &text2 = req.form.get_field("text2");
  9075. ASSERT_EQ("text2", text2);
  9076. handled = true;
  9077. });
  9078. thread t = thread([&] { svr.listen(HOST, PORT); });
  9079. auto se = detail::scope_exit([&] {
  9080. svr.stop();
  9081. t.join();
  9082. ASSERT_FALSE(svr.is_running());
  9083. ASSERT_TRUE(handled);
  9084. });
  9085. svr.wait_until_ready();
  9086. auto req = "POST /test HTTP/1.1\r\n"
  9087. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9088. "Content-Length: 167\r\n"
  9089. "\r\n----------\r\n"
  9090. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9091. "Content-Length: 5\r\n"
  9092. "\r\n"
  9093. "text1"
  9094. "\r\n----------\r\n"
  9095. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9096. "\r\n"
  9097. "text2"
  9098. "\r\n------------\r\n";
  9099. std::string response;
  9100. ASSERT_TRUE(send_request(1, req, &response));
  9101. ASSERT_EQ("200", response.substr(9, 3));
  9102. }
  9103. TEST(MultipartFormDataTest, AccessPartHeaders) {
  9104. auto handled = false;
  9105. Server svr;
  9106. svr.Post("/test", [&](const Request &req, Response &) {
  9107. ASSERT_EQ(2u, req.form.fields.size());
  9108. const auto &text1 = req.form.get_field("text1");
  9109. ASSERT_EQ("text1", text1);
  9110. // TODO: Add header access for text fields if needed
  9111. const auto &text2 = req.form.get_field("text2");
  9112. ASSERT_EQ("text2", text2);
  9113. // TODO: Header access for text fields needs to be implemented
  9114. // auto &headers = it->second.headers;
  9115. // ASSERT_EQ(3U, headers.size());
  9116. // auto custom_header = headers.find("x-whatever");
  9117. // ASSERT_TRUE(custom_header != headers.end());
  9118. // ASSERT_NE("customvalue", custom_header->second);
  9119. // ASSERT_EQ("CustomValue", custom_header->second);
  9120. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  9121. handled = true;
  9122. });
  9123. thread t = thread([&] { svr.listen(HOST, PORT); });
  9124. auto se = detail::scope_exit([&] {
  9125. svr.stop();
  9126. t.join();
  9127. ASSERT_FALSE(svr.is_running());
  9128. ASSERT_TRUE(handled);
  9129. });
  9130. svr.wait_until_ready();
  9131. auto req = "POST /test HTTP/1.1\r\n"
  9132. "Content-Type: multipart/form-data;boundary=--------\r\n"
  9133. "Content-Length: 232\r\n"
  9134. "\r\n----------\r\n"
  9135. "Content-Disposition: form-data; name=\"text1\"\r\n"
  9136. "Content-Length: 5\r\n"
  9137. "X-Test: 1\r\n"
  9138. "\r\n"
  9139. "text1"
  9140. "\r\n----------\r\n"
  9141. "Content-Disposition: form-data; name=\"text2\"\r\n"
  9142. "Content-Type: text/plain\r\n"
  9143. "X-Whatever: CustomValue\r\n"
  9144. "\r\n"
  9145. "text2"
  9146. "\r\n------------\r\n"
  9147. "That should be disregarded. Not even read";
  9148. std::string response;
  9149. ASSERT_TRUE(send_request(1, req, &response));
  9150. ASSERT_EQ("200", response.substr(9, 3));
  9151. }
  9152. #endif
  9153. TEST(MultipartFormDataTest, LargeHeader) {
  9154. auto handled = false;
  9155. Server svr;
  9156. svr.Post("/test", [&](const Request &req, Response &) {
  9157. ASSERT_EQ(1u, req.form.fields.size());
  9158. const auto &text = req.form.get_field("name1");
  9159. ASSERT_EQ("text1", text);
  9160. handled = true;
  9161. });
  9162. thread t = thread([&] { svr.listen(HOST, PORT); });
  9163. auto se = detail::scope_exit([&] {
  9164. svr.stop();
  9165. t.join();
  9166. ASSERT_FALSE(svr.is_running());
  9167. ASSERT_TRUE(handled);
  9168. });
  9169. svr.wait_until_ready();
  9170. auto boundary = std::string("cpp-httplib-multipart-data");
  9171. std::string content = "--" + boundary +
  9172. "\r\n"
  9173. "Content-Disposition: form-data; name=\"name1\"\r\n"
  9174. "\r\n"
  9175. "text1\r\n"
  9176. "--" +
  9177. boundary + "--\r\n";
  9178. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  9179. "Content-Type: multipart/form-data;boundary=" +
  9180. boundary +
  9181. "\r\n"
  9182. "Content-Length: " +
  9183. std::to_string(content.size()) +
  9184. "\r\n"
  9185. "Dummy-Header: ";
  9186. std::string header_suffix = "\r\n"
  9187. "\r\n";
  9188. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  9189. size_t header_dummy_size =
  9190. read_buff_size -
  9191. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  9192. auto header_dummy = std::string(header_dummy_size, '@');
  9193. auto req = header_prefix + header_dummy + header_suffix + content;
  9194. std::string response;
  9195. ASSERT_TRUE(send_request(1, req, &response));
  9196. ASSERT_EQ("200", response.substr(9, 3));
  9197. }
  9198. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  9199. static constexpr unsigned int number_of_tasks{1000000};
  9200. std::atomic_uint count{0};
  9201. std::unique_ptr<TaskQueue> task_queue{
  9202. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  9203. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9204. auto queued = task_queue->enqueue(
  9205. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  9206. EXPECT_TRUE(queued);
  9207. }
  9208. EXPECT_NO_THROW(task_queue->shutdown());
  9209. EXPECT_EQ(number_of_tasks, count.load());
  9210. }
  9211. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  9212. static constexpr unsigned int number_of_tasks{1000000};
  9213. static constexpr unsigned int qlimit{2};
  9214. unsigned int queued_count{0};
  9215. std::atomic_uint count{0};
  9216. std::unique_ptr<TaskQueue> task_queue{
  9217. new ThreadPool{/*num_threads=*/1, qlimit}};
  9218. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  9219. if (task_queue->enqueue(
  9220. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  9221. queued_count++;
  9222. }
  9223. }
  9224. EXPECT_NO_THROW(task_queue->shutdown());
  9225. EXPECT_EQ(queued_count, count.load());
  9226. EXPECT_TRUE(queued_count <= number_of_tasks);
  9227. EXPECT_TRUE(queued_count >= qlimit);
  9228. }
  9229. TEST(TaskQueueTest, MaxQueuedRequests) {
  9230. static constexpr unsigned int qlimit{3};
  9231. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  9232. std::condition_variable sem_cv;
  9233. std::mutex sem_mtx;
  9234. int credits = 0;
  9235. bool queued;
  9236. /* Fill up the queue with tasks that will block until we give them credits to
  9237. * complete. */
  9238. for (unsigned int n = 0; n <= qlimit;) {
  9239. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  9240. std::unique_lock<std::mutex> lock(sem_mtx);
  9241. while (credits <= 0) {
  9242. sem_cv.wait(lock);
  9243. }
  9244. /* Consume the credit and signal the test code if they are all gone. */
  9245. if (--credits == 0) { sem_cv.notify_one(); }
  9246. });
  9247. if (n < qlimit) {
  9248. /* The first qlimit enqueues must succeed. */
  9249. EXPECT_TRUE(queued);
  9250. } else {
  9251. /* The last one will succeed only when the worker thread
  9252. * starts and dequeues the first blocking task. Although
  9253. * not necessary for the correctness of this test, we sleep for
  9254. * a short while to avoid busy waiting. */
  9255. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  9256. }
  9257. if (queued) { n++; }
  9258. }
  9259. /* Further enqueues must fail since the queue is full. */
  9260. for (auto i = 0; i < 4; i++) {
  9261. queued = task_queue->enqueue([] {});
  9262. EXPECT_FALSE(queued);
  9263. }
  9264. /* Give the credits to allow the previous tasks to complete. */
  9265. {
  9266. std::unique_lock<std::mutex> lock(sem_mtx);
  9267. credits += qlimit + 1;
  9268. }
  9269. sem_cv.notify_all();
  9270. /* Wait for all the credits to be consumed. */
  9271. {
  9272. std::unique_lock<std::mutex> lock(sem_mtx);
  9273. while (credits > 0) {
  9274. sem_cv.wait(lock);
  9275. }
  9276. }
  9277. /* Check that we are able again to enqueue at least qlimit tasks. */
  9278. for (unsigned int i = 0; i < qlimit; i++) {
  9279. queued = task_queue->enqueue([] {});
  9280. EXPECT_TRUE(queued);
  9281. }
  9282. EXPECT_NO_THROW(task_queue->shutdown());
  9283. }
  9284. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  9285. Server svr;
  9286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9287. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  9288. });
  9289. svr.Get("/hello", [](const Request &req, Response &res) {
  9290. res.set_content(req.get_param_value("key"), "text/plain");
  9291. });
  9292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9293. auto se = detail::scope_exit([&] {
  9294. svr.stop();
  9295. thread.join();
  9296. ASSERT_FALSE(svr.is_running());
  9297. });
  9298. svr.wait_until_ready();
  9299. {
  9300. Client cli(HOST, PORT);
  9301. cli.set_follow_location(true);
  9302. auto res = cli.Get("/");
  9303. ASSERT_TRUE(res);
  9304. EXPECT_EQ(StatusCode::OK_200, res->status);
  9305. EXPECT_EQ("val&key2=val2", res->body);
  9306. }
  9307. }
  9308. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  9309. Server svr;
  9310. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9311. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  9312. });
  9313. svr.Get("/hello", [](const Request &req, Response &res) {
  9314. res.set_content(req.get_param_value("key"), "text/plain");
  9315. });
  9316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9317. auto se = detail::scope_exit([&] {
  9318. svr.stop();
  9319. thread.join();
  9320. ASSERT_FALSE(svr.is_running());
  9321. });
  9322. svr.wait_until_ready();
  9323. {
  9324. Client cli(HOST, PORT);
  9325. cli.set_follow_location(true);
  9326. auto res = cli.Get("/");
  9327. ASSERT_TRUE(res);
  9328. EXPECT_EQ(StatusCode::OK_200, res->status);
  9329. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  9330. }
  9331. }
  9332. #ifdef CPPHTTPLIB_SSL_ENABLED
  9333. TEST(RedirectTest, Issue2185_Online) {
  9334. SSLClient client("github.com");
  9335. client.set_follow_location(true);
  9336. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  9337. "Coollab-Windows.zip");
  9338. ASSERT_TRUE(res);
  9339. EXPECT_EQ(StatusCode::OK_200, res->status);
  9340. EXPECT_EQ(9920427U, res->body.size());
  9341. }
  9342. #endif
  9343. TEST(VulnerabilityTest, CRLFInjection) {
  9344. Server svr;
  9345. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  9346. res.set_content("Hello 1", "text/plain");
  9347. });
  9348. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  9349. res.set_content("Hello 2", "text/plain");
  9350. });
  9351. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  9352. res.set_content("Hello 3", "text/plain");
  9353. });
  9354. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  9355. res.set_content("Hello 4", "text/plain");
  9356. });
  9357. svr.set_logger([](const Request &req, const Response & /*res*/) {
  9358. for (const auto &x : req.headers) {
  9359. auto key = x.first;
  9360. EXPECT_STRNE("evil", key.c_str());
  9361. }
  9362. });
  9363. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9364. auto se = detail::scope_exit([&] {
  9365. svr.stop();
  9366. thread.join();
  9367. ASSERT_FALSE(svr.is_running());
  9368. });
  9369. svr.wait_until_ready();
  9370. {
  9371. Client cli(HOST, PORT);
  9372. cli.Post("/test1", "A=B",
  9373. "application/x-www-form-urlencoded\r\nevil: hello1");
  9374. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  9375. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  9376. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  9377. }
  9378. }
  9379. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  9380. auto server_thread = std::thread([] {
  9381. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  9382. default_socket_options(srv);
  9383. sockaddr_in addr{};
  9384. addr.sin_family = AF_INET;
  9385. addr.sin_port = htons(PORT + 1);
  9386. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  9387. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  9388. ::listen(srv, 1);
  9389. sockaddr_in cli_addr{};
  9390. socklen_t cli_len = sizeof(cli_addr);
  9391. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  9392. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  9393. std::string buf_all;
  9394. char buf[2048];
  9395. ssize_t n;
  9396. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  9397. buf_all.append(buf, static_cast<size_t>(n));
  9398. size_t pos;
  9399. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  9400. auto request_block = buf_all.substr(0, pos + 4); // include separator
  9401. auto e = request_block.find("\r\n");
  9402. if (e != std::string::npos) {
  9403. auto request_line = request_block.substr(0, e);
  9404. std::string msg =
  9405. "CRLF injection detected in request line: '" + request_line + "'";
  9406. EXPECT_FALSE(true) << msg;
  9407. }
  9408. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9409. ::send(cli,
  9410. #ifdef _WIN32
  9411. static_cast<const char *>(resp.c_str()),
  9412. static_cast<int>(resp.size()),
  9413. #else
  9414. resp.c_str(), resp.size(),
  9415. #endif
  9416. 0);
  9417. buf_all.erase(0, pos + 4);
  9418. }
  9419. }
  9420. detail::close_socket(cli);
  9421. detail::close_socket(srv);
  9422. });
  9423. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9424. auto cli = Client("127.0.0.1", PORT + 1);
  9425. auto headers = Headers{
  9426. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9427. {"Connection", "keep-alive"}};
  9428. auto res = cli.Get("/hi", headers);
  9429. EXPECT_FALSE(res);
  9430. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9431. server_thread.join();
  9432. }
  9433. TEST(PathParamsTest, StaticMatch) {
  9434. const auto pattern = "/users/all";
  9435. detail::PathParamsMatcher matcher(pattern);
  9436. Request request;
  9437. request.path = "/users/all";
  9438. ASSERT_TRUE(matcher.match(request));
  9439. std::unordered_map<std::string, std::string> expected_params = {};
  9440. EXPECT_EQ(request.path_params, expected_params);
  9441. }
  9442. TEST(PathParamsTest, StaticMismatch) {
  9443. const auto pattern = "/users/all";
  9444. detail::PathParamsMatcher matcher(pattern);
  9445. Request request;
  9446. request.path = "/users/1";
  9447. ASSERT_FALSE(matcher.match(request));
  9448. }
  9449. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9450. const auto pattern = "/users/:id/subscriptions";
  9451. detail::PathParamsMatcher matcher(pattern);
  9452. Request request;
  9453. request.path = "/users/42/subscriptions";
  9454. ASSERT_TRUE(matcher.match(request));
  9455. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9456. EXPECT_EQ(request.path_params, expected_params);
  9457. }
  9458. TEST(PathParamsTest, SingleParamInTheEnd) {
  9459. const auto pattern = "/users/:id";
  9460. detail::PathParamsMatcher matcher(pattern);
  9461. Request request;
  9462. request.path = "/users/24";
  9463. ASSERT_TRUE(matcher.match(request));
  9464. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9465. EXPECT_EQ(request.path_params, expected_params);
  9466. }
  9467. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9468. const auto pattern = "/users/:id/";
  9469. detail::PathParamsMatcher matcher(pattern);
  9470. Request request;
  9471. request.path = "/users/42/";
  9472. ASSERT_TRUE(matcher.match(request));
  9473. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9474. EXPECT_EQ(request.path_params, expected_params);
  9475. }
  9476. TEST(PathParamsTest, EmptyParam) {
  9477. const auto pattern = "/users/:id/";
  9478. detail::PathParamsMatcher matcher(pattern);
  9479. Request request;
  9480. request.path = "/users//";
  9481. ASSERT_TRUE(matcher.match(request));
  9482. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9483. EXPECT_EQ(request.path_params, expected_params);
  9484. }
  9485. TEST(PathParamsTest, FragmentMismatch) {
  9486. const auto pattern = "/users/:id/";
  9487. detail::PathParamsMatcher matcher(pattern);
  9488. Request request;
  9489. request.path = "/admins/24/";
  9490. ASSERT_FALSE(matcher.match(request));
  9491. }
  9492. TEST(PathParamsTest, ExtraFragments) {
  9493. const auto pattern = "/users/:id";
  9494. detail::PathParamsMatcher matcher(pattern);
  9495. Request request;
  9496. request.path = "/users/42/subscriptions";
  9497. ASSERT_FALSE(matcher.match(request));
  9498. }
  9499. TEST(PathParamsTest, MissingTrailingParam) {
  9500. const auto pattern = "/users/:id";
  9501. detail::PathParamsMatcher matcher(pattern);
  9502. Request request;
  9503. request.path = "/users";
  9504. ASSERT_FALSE(matcher.match(request));
  9505. }
  9506. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9507. const auto pattern = "/users/:id/subscriptions";
  9508. detail::PathParamsMatcher matcher(pattern);
  9509. Request request;
  9510. request.path = "/users/subscriptions";
  9511. ASSERT_FALSE(matcher.match(request));
  9512. }
  9513. TEST(PathParamsTest, MultipleParams) {
  9514. const auto pattern = "/users/:userid/subscriptions/:subid";
  9515. detail::PathParamsMatcher matcher(pattern);
  9516. Request request;
  9517. request.path = "/users/42/subscriptions/2";
  9518. ASSERT_TRUE(matcher.match(request));
  9519. std::unordered_map<std::string, std::string> expected_params = {
  9520. {"userid", "42"}, {"subid", "2"}};
  9521. EXPECT_EQ(request.path_params, expected_params);
  9522. }
  9523. TEST(PathParamsTest, SequenceOfParams) {
  9524. const auto pattern = "/values/:x/:y/:z";
  9525. detail::PathParamsMatcher matcher(pattern);
  9526. Request request;
  9527. request.path = "/values/1/2/3";
  9528. ASSERT_TRUE(matcher.match(request));
  9529. std::unordered_map<std::string, std::string> expected_params = {
  9530. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9531. EXPECT_EQ(request.path_params, expected_params);
  9532. }
  9533. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9534. const auto pattern = "/prefix:suffix";
  9535. detail::PathParamsMatcher matcher(pattern);
  9536. Request request;
  9537. request.path = "/prefix:suffix";
  9538. ASSERT_TRUE(matcher.match(request));
  9539. const std::unordered_map<std::string, std::string> expected_params = {};
  9540. EXPECT_EQ(request.path_params, expected_params);
  9541. }
  9542. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9543. // If ipv6 regex working, regex match codepath is taken.
  9544. // else port will default to 80 in Client impl
  9545. int clientImplMagicPort = 80;
  9546. int port = 4321;
  9547. // above ports must be different to avoid false negative
  9548. EXPECT_NE(clientImplMagicPort, port);
  9549. std::string ipV6TestURL = "http://[ff06::c3]";
  9550. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9551. CLIENT_PRIVATE_KEY_FILE);
  9552. EXPECT_EQ(cli.port(), port);
  9553. }
  9554. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9555. auto file_path = "./www/dir/index.html";
  9556. auto dir_path = "./www/dir";
  9557. detail::FileStat stat_file(file_path);
  9558. EXPECT_TRUE(stat_file.is_file());
  9559. EXPECT_FALSE(stat_file.is_dir());
  9560. detail::FileStat stat_dir(dir_path);
  9561. EXPECT_FALSE(stat_dir.is_file());
  9562. EXPECT_TRUE(stat_dir.is_dir());
  9563. }
  9564. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9565. // IPv4 with default HTTP port (80)
  9566. EXPECT_EQ("example.com",
  9567. detail::make_host_and_port_string("example.com", 80, false));
  9568. // IPv4 with default HTTPS port (443)
  9569. EXPECT_EQ("example.com",
  9570. detail::make_host_and_port_string("example.com", 443, true));
  9571. // IPv4 with non-default HTTP port
  9572. EXPECT_EQ("example.com:8080",
  9573. detail::make_host_and_port_string("example.com", 8080, false));
  9574. // IPv4 with non-default HTTPS port
  9575. EXPECT_EQ("example.com:8443",
  9576. detail::make_host_and_port_string("example.com", 8443, true));
  9577. // IPv6 with default HTTP port (80)
  9578. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9579. // IPv6 with default HTTPS port (443)
  9580. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9581. // IPv6 with non-default HTTP port
  9582. EXPECT_EQ("[::1]:8080",
  9583. detail::make_host_and_port_string("::1", 8080, false));
  9584. // IPv6 with non-default HTTPS port
  9585. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9586. // IPv6 full address with default port
  9587. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9588. detail::make_host_and_port_string(
  9589. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9590. // IPv6 full address with non-default port
  9591. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9592. detail::make_host_and_port_string(
  9593. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9594. // IPv6 localhost with non-default port
  9595. EXPECT_EQ("[::1]:3000",
  9596. detail::make_host_and_port_string("::1", 3000, false));
  9597. // IPv6 with zone ID (link-local address) with default port
  9598. EXPECT_EQ("[fe80::1%eth0]",
  9599. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9600. // IPv6 with zone ID (link-local address) with non-default port
  9601. EXPECT_EQ("[fe80::1%eth0]:8080",
  9602. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9603. // Edge case: Port 443 with is_ssl=false (should add port)
  9604. EXPECT_EQ("example.com:443",
  9605. detail::make_host_and_port_string("example.com", 443, false));
  9606. // Edge case: Port 80 with is_ssl=true (should add port)
  9607. EXPECT_EQ("example.com:80",
  9608. detail::make_host_and_port_string("example.com", 80, true));
  9609. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9610. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9611. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9612. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9613. // Security fix: Already bracketed IPv6 should not get double brackets
  9614. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9615. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9616. EXPECT_EQ("[::1]:8080",
  9617. detail::make_host_and_port_string("[::1]", 8080, false));
  9618. EXPECT_EQ("[2001:db8::1]:8080",
  9619. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9620. EXPECT_EQ("[fe80::1%eth0]",
  9621. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9622. EXPECT_EQ("[fe80::1%eth0]:8080",
  9623. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9624. // Edge case: Empty host (should return as-is)
  9625. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9626. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9627. // This is a known limitation but shouldn't crash
  9628. EXPECT_EQ("[host:name]",
  9629. detail::make_host_and_port_string("host:name", 80, false));
  9630. // Port number edge cases (no validation, but should not crash)
  9631. EXPECT_EQ("example.com:0",
  9632. detail::make_host_and_port_string("example.com", 0, false));
  9633. EXPECT_EQ("example.com:-1",
  9634. detail::make_host_and_port_string("example.com", -1, false));
  9635. EXPECT_EQ("example.com:65535",
  9636. detail::make_host_and_port_string("example.com", 65535, false));
  9637. EXPECT_EQ("example.com:65536",
  9638. detail::make_host_and_port_string("example.com", 65536, false));
  9639. }
  9640. #ifdef CPPHTTPLIB_SSL_ENABLED
  9641. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9642. httplib::SSLClient cli("roblox.com", 443);
  9643. cli.set_follow_location(true);
  9644. auto res = cli.Get("/");
  9645. ASSERT_TRUE(res);
  9646. EXPECT_EQ(StatusCode::OK_200, res->status);
  9647. }
  9648. #endif
  9649. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9650. Server svr;
  9651. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9652. EXPECT_EQ(res.status, 400);
  9653. });
  9654. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9655. auto se = detail::scope_exit([&] {
  9656. svr.stop();
  9657. thread.join();
  9658. ASSERT_FALSE(svr.is_running());
  9659. });
  9660. svr.wait_until_ready();
  9661. Client cli(HOST, PORT);
  9662. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9663. }
  9664. TEST(InvalidHeaderCharsTest, is_field_name) {
  9665. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9666. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9667. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9668. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9669. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9670. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9671. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9672. EXPECT_FALSE(detail::fields::is_field_name(""));
  9673. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9674. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9675. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9676. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9677. }
  9678. TEST(InvalidHeaderCharsTest, is_field_value) {
  9679. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9680. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9681. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9682. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9683. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9684. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9685. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9686. EXPECT_TRUE(detail::fields::is_field_value(""));
  9687. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9688. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9689. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9690. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9691. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9692. }
  9693. TEST(InvalidHeaderCharsTest, OnServer) {
  9694. Server svr;
  9695. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9696. std::string header = "Not Set";
  9697. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9698. res.set_header(header, "value");
  9699. res.set_content("Page Content Page Content", "text/plain");
  9700. });
  9701. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9702. std::string header = "Not Set";
  9703. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9704. res.set_header("X-Test", header);
  9705. res.set_content("Page Content Page Content", "text/plain");
  9706. });
  9707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9708. auto se = detail::scope_exit([&] {
  9709. svr.stop();
  9710. thread.join();
  9711. ASSERT_FALSE(svr.is_running());
  9712. });
  9713. svr.wait_until_ready();
  9714. Client cli(HOST, PORT);
  9715. {
  9716. auto res = cli.Get(
  9717. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9718. ASSERT_TRUE(res);
  9719. EXPECT_EQ("Page Content Page Content", res->body);
  9720. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9721. }
  9722. {
  9723. auto res = cli.Get(
  9724. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9725. ASSERT_TRUE(res);
  9726. EXPECT_EQ("Page Content Page Content", res->body);
  9727. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9728. }
  9729. }
  9730. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9731. auto handled = false;
  9732. Server svr;
  9733. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9734. thread t = thread([&] { svr.listen(HOST, PORT); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. t.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. ASSERT_FALSE(handled);
  9740. });
  9741. svr.wait_until_ready();
  9742. auto req = "POST /test HTTP/1.1\r\n"
  9743. "Content-Length: x\r\n"
  9744. "\r\n";
  9745. std::string response;
  9746. ASSERT_TRUE(send_request(1, req, &response));
  9747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9748. response.substr(0, response.find("\r\n")));
  9749. }
  9750. #ifndef _WIN32
  9751. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9752. static constexpr char reject[] = "Unauthorized";
  9753. static constexpr char accept[] = "Upload accepted";
  9754. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9755. Server svr;
  9756. svr.set_expect_100_continue_handler(
  9757. [](const Request & /*req*/, Response &res) {
  9758. res.status = StatusCode::Unauthorized_401;
  9759. res.set_content(reject, "text/plain");
  9760. return res.status;
  9761. });
  9762. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9763. res.set_content(accept, "text/plain");
  9764. });
  9765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9766. auto se = detail::scope_exit([&] {
  9767. svr.stop();
  9768. thread.join();
  9769. ASSERT_FALSE(svr.is_running());
  9770. });
  9771. svr.wait_until_ready();
  9772. {
  9773. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9774. curl_easy_init(), &curl_easy_cleanup};
  9775. ASSERT_NE(curl, nullptr);
  9776. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9777. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9778. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9779. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9780. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9781. &curl_slist_free_all};
  9782. ASSERT_NE(list, nullptr);
  9783. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9784. struct read_data {
  9785. size_t read_size;
  9786. size_t total_size;
  9787. } data = {0, total_size};
  9788. using read_callback_t =
  9789. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9790. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9791. void *userdata) -> size_t {
  9792. read_data *data = (read_data *)userdata;
  9793. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9794. std::fill_n(ptr, size * nmemb, 'A');
  9795. data->read_size += size * nmemb;
  9796. return size * nmemb;
  9797. };
  9798. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9799. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9800. std::vector<char> buffer;
  9801. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9802. using write_callback_t =
  9803. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9804. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9805. void *userdata) -> size_t {
  9806. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9807. buffer->reserve(buffer->size() + size * nmemb + 1);
  9808. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9809. return size * nmemb;
  9810. };
  9811. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9812. {
  9813. const auto res = curl_easy_perform(curl.get());
  9814. ASSERT_EQ(res, CURLE_OK);
  9815. }
  9816. {
  9817. auto response_code = long{};
  9818. const auto res =
  9819. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9820. ASSERT_EQ(res, CURLE_OK);
  9821. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9822. }
  9823. {
  9824. auto dl = curl_off_t{};
  9825. const auto res =
  9826. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9827. ASSERT_EQ(res, CURLE_OK);
  9828. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9829. }
  9830. {
  9831. buffer.push_back('\0');
  9832. ASSERT_STRCASEEQ(buffer.data(), reject);
  9833. }
  9834. }
  9835. }
  9836. #endif
  9837. template <typename S, typename C>
  9838. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9839. svr.Get("/stream", [&](const Request &, Response &res) {
  9840. auto data = new std::string("01234567890123456789");
  9841. res.set_content_provider(
  9842. data->size(), "text/plain",
  9843. [&, data](size_t offset, size_t length, DataSink &sink) {
  9844. const size_t DATA_CHUNK_SIZE = 4;
  9845. const auto &d = *data;
  9846. std::this_thread::sleep_for(std::chrono::seconds(1));
  9847. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9848. return true;
  9849. },
  9850. [data](bool success) {
  9851. EXPECT_FALSE(success);
  9852. delete data;
  9853. });
  9854. });
  9855. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9856. auto i = new size_t(0);
  9857. res.set_content_provider(
  9858. "text/plain",
  9859. [i](size_t, DataSink &sink) {
  9860. if (*i < 5) {
  9861. std::this_thread::sleep_for(std::chrono::seconds(1));
  9862. sink.write("abcd", 4);
  9863. (*i)++;
  9864. } else {
  9865. sink.done();
  9866. }
  9867. return true;
  9868. },
  9869. [i](bool success) {
  9870. EXPECT_FALSE(success);
  9871. delete i;
  9872. });
  9873. });
  9874. svr.Get("/chunked", [&](const Request &, Response &res) {
  9875. auto i = new size_t(0);
  9876. res.set_chunked_content_provider(
  9877. "text/plain",
  9878. [i](size_t, DataSink &sink) {
  9879. if (*i < 5) {
  9880. std::this_thread::sleep_for(std::chrono::seconds(1));
  9881. sink.os << "abcd";
  9882. (*i)++;
  9883. } else {
  9884. sink.done();
  9885. }
  9886. return true;
  9887. },
  9888. [i](bool success) {
  9889. EXPECT_FALSE(success);
  9890. delete i;
  9891. });
  9892. });
  9893. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9894. auto se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. listen_thread.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. });
  9899. svr.wait_until_ready();
  9900. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9901. {
  9902. auto start = std::chrono::steady_clock::now();
  9903. auto res = cli.Get("/stream");
  9904. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9905. std::chrono::steady_clock::now() - start)
  9906. .count();
  9907. ASSERT_FALSE(res);
  9908. EXPECT_EQ(Error::Read, res.error());
  9909. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9910. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9911. }
  9912. {
  9913. auto start = std::chrono::steady_clock::now();
  9914. auto res = cli.Get("/stream_without_length");
  9915. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9916. std::chrono::steady_clock::now() - start)
  9917. .count();
  9918. ASSERT_FALSE(res);
  9919. EXPECT_EQ(Error::Read, res.error());
  9920. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9921. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9922. }
  9923. {
  9924. auto start = std::chrono::steady_clock::now();
  9925. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9926. EXPECT_EQ("abcd", string(data, data_length));
  9927. return true;
  9928. });
  9929. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9930. std::chrono::steady_clock::now() - start)
  9931. .count();
  9932. ASSERT_FALSE(res);
  9933. EXPECT_EQ(Error::Read, res.error());
  9934. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9935. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9936. }
  9937. }
  9938. TEST(MaxTimeoutTest, ContentStream) {
  9939. time_t timeout = 2000;
  9940. time_t threshold = 200;
  9941. Server svr;
  9942. Client cli("localhost", PORT);
  9943. max_timeout_test(svr, cli, timeout, threshold);
  9944. }
  9945. #ifdef CPPHTTPLIB_SSL_ENABLED
  9946. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9947. time_t timeout = 2000;
  9948. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9950. SSLClient cli("localhost", PORT);
  9951. cli.enable_server_certificate_verification(false);
  9952. max_timeout_test(svr, cli, timeout, threshold);
  9953. }
  9954. #endif
  9955. class EventDispatcher {
  9956. public:
  9957. EventDispatcher() {}
  9958. bool wait_event(DataSink *sink) {
  9959. unique_lock<mutex> lk(m_);
  9960. int id = id_;
  9961. // Wait with timeout to prevent hanging if client disconnects
  9962. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9963. [&] { return cid_ == id; })) {
  9964. return false; // Timeout occurred
  9965. }
  9966. sink->write(message_.data(), message_.size());
  9967. return true;
  9968. }
  9969. void send_event(const string &message) {
  9970. lock_guard<mutex> lk(m_);
  9971. cid_ = id_++;
  9972. message_ = message;
  9973. cv_.notify_all();
  9974. }
  9975. private:
  9976. mutex m_;
  9977. condition_variable cv_;
  9978. atomic_int id_{0};
  9979. atomic_int cid_{-1};
  9980. string message_;
  9981. };
  9982. TEST(ClientInThreadTest, Issue2068) {
  9983. EventDispatcher ed;
  9984. Server svr;
  9985. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9986. res.set_chunked_content_provider("text/event-stream",
  9987. [&](size_t /*offset*/, DataSink &sink) {
  9988. return ed.wait_event(&sink);
  9989. });
  9990. });
  9991. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9992. svr.wait_until_ready();
  9993. thread event_thread([&] {
  9994. int id = 0;
  9995. while (svr.is_running()) {
  9996. this_thread::sleep_for(chrono::milliseconds(500));
  9997. std::stringstream ss;
  9998. ss << "data: " << id << "\n\n";
  9999. ed.send_event(ss.str());
  10000. id++;
  10001. }
  10002. });
  10003. auto se = detail::scope_exit([&] {
  10004. svr.stop();
  10005. listen_thread.join();
  10006. event_thread.join();
  10007. ASSERT_FALSE(svr.is_running());
  10008. });
  10009. {
  10010. auto client = detail::make_unique<Client>(HOST, PORT);
  10011. client->set_read_timeout(std::chrono::minutes(10));
  10012. std::atomic<bool> stop{false};
  10013. std::thread t([&] {
  10014. client->Get("/event1",
  10015. [&](const char *, size_t) -> bool { return !stop; });
  10016. });
  10017. std::this_thread::sleep_for(std::chrono::seconds(2));
  10018. stop = true;
  10019. client->stop();
  10020. t.join();
  10021. // Reset client after thread has finished
  10022. client.reset();
  10023. }
  10024. }
  10025. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  10026. Server svr;
  10027. svr.Get("/", [](const Request &req, Response &res) {
  10028. EXPECT_EQ(2U, req.trailers.size());
  10029. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  10030. // Denied
  10031. EXPECT_FALSE(req.has_trailer("Content-Length"));
  10032. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  10033. // Accepted
  10034. EXPECT_TRUE(req.has_trailer("X-Hello"));
  10035. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  10036. EXPECT_TRUE(req.has_trailer("X-World"));
  10037. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  10038. res.set_content("ok", "text/plain");
  10039. });
  10040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. ASSERT_FALSE(svr.is_running());
  10045. });
  10046. svr.wait_until_ready();
  10047. const std::string req = "GET / HTTP/1.1\r\n"
  10048. "Transfer-Encoding: chunked\r\n"
  10049. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  10050. "\r\n"
  10051. "0\r\n"
  10052. "Content-Length: 10\r\n"
  10053. "Host: internal.local\r\n"
  10054. "Content-Type: malicious/content\r\n"
  10055. "Cookie: any\r\n"
  10056. "Set-Cookie: any\r\n"
  10057. "X-Forwarded-For: attacker.com\r\n"
  10058. "X-Real-Ip: 1.1.1.1\r\n"
  10059. "X-Hello: hello\r\n"
  10060. "X-World: world\r\n"
  10061. "\r\n";
  10062. std::string res;
  10063. ASSERT_TRUE(send_request(1, req, &res));
  10064. }
  10065. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  10066. Server svr;
  10067. std::string observed_remote_addr;
  10068. std::string observed_xff;
  10069. svr.Get("/ip", [&](const Request &req, Response &res) {
  10070. observed_remote_addr = req.remote_addr;
  10071. observed_xff = req.get_header_value("X-Forwarded-For");
  10072. res.set_content("ok", "text/plain");
  10073. });
  10074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10075. auto se = detail::scope_exit([&] {
  10076. svr.stop();
  10077. t.join();
  10078. ASSERT_FALSE(svr.is_running());
  10079. });
  10080. svr.wait_until_ready();
  10081. Client cli(HOST, PORT);
  10082. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  10083. ASSERT_TRUE(res);
  10084. EXPECT_EQ(StatusCode::OK_200, res->status);
  10085. EXPECT_EQ(observed_xff, "203.0.113.66");
  10086. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10087. observed_remote_addr == "127.0.0.1");
  10088. }
  10089. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  10090. Server svr;
  10091. svr.set_trusted_proxies({"203.0.113.66"});
  10092. std::string observed_remote_addr;
  10093. std::string observed_xff;
  10094. svr.Get("/ip", [&](const Request &req, Response &res) {
  10095. observed_remote_addr = req.remote_addr;
  10096. observed_xff = req.get_header_value("X-Forwarded-For");
  10097. res.set_content("ok", "text/plain");
  10098. });
  10099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10100. auto se = detail::scope_exit([&] {
  10101. svr.stop();
  10102. t.join();
  10103. ASSERT_FALSE(svr.is_running());
  10104. });
  10105. svr.wait_until_ready();
  10106. Client cli(HOST, PORT);
  10107. auto res = cli.Get("/ip");
  10108. ASSERT_TRUE(res);
  10109. EXPECT_EQ(StatusCode::OK_200, res->status);
  10110. EXPECT_EQ(observed_xff, "");
  10111. EXPECT_TRUE(observed_remote_addr == "::1" ||
  10112. observed_remote_addr == "127.0.0.1");
  10113. }
  10114. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  10115. Server svr;
  10116. svr.set_trusted_proxies({"203.0.113.66"});
  10117. std::string observed_remote_addr;
  10118. std::string observed_xff;
  10119. svr.Get("/ip", [&](const Request &req, Response &res) {
  10120. observed_remote_addr = req.remote_addr;
  10121. observed_xff = req.get_header_value("X-Forwarded-For");
  10122. res.set_content("ok", "text/plain");
  10123. });
  10124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10125. auto se = detail::scope_exit([&] {
  10126. svr.stop();
  10127. t.join();
  10128. ASSERT_FALSE(svr.is_running());
  10129. });
  10130. svr.wait_until_ready();
  10131. Client cli(HOST, PORT);
  10132. auto res =
  10133. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  10134. ASSERT_TRUE(res);
  10135. EXPECT_EQ(StatusCode::OK_200, res->status);
  10136. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  10137. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10138. }
  10139. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  10140. Server svr;
  10141. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  10142. std::string observed_remote_addr;
  10143. std::string observed_xff;
  10144. svr.Get("/ip", [&](const Request &req, Response &res) {
  10145. observed_remote_addr = req.remote_addr;
  10146. observed_xff = req.get_header_value("X-Forwarded-For");
  10147. res.set_content("ok", "text/plain");
  10148. });
  10149. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10150. auto se = detail::scope_exit([&] {
  10151. svr.stop();
  10152. t.join();
  10153. ASSERT_FALSE(svr.is_running());
  10154. });
  10155. svr.wait_until_ready();
  10156. Client cli(HOST, PORT);
  10157. auto res = cli.Get(
  10158. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10159. ASSERT_TRUE(res);
  10160. EXPECT_EQ(StatusCode::OK_200, res->status);
  10161. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10162. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10163. }
  10164. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  10165. Server svr;
  10166. svr.set_trusted_proxies({"192.0.2.45"});
  10167. std::string observed_remote_addr;
  10168. std::string observed_xff;
  10169. svr.Get("/ip", [&](const Request &req, Response &res) {
  10170. observed_remote_addr = req.remote_addr;
  10171. observed_xff = req.get_header_value("X-Forwarded-For");
  10172. res.set_content("ok", "text/plain");
  10173. });
  10174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10175. auto se = detail::scope_exit([&] {
  10176. svr.stop();
  10177. t.join();
  10178. ASSERT_FALSE(svr.is_running());
  10179. });
  10180. svr.wait_until_ready();
  10181. Client cli(HOST, PORT);
  10182. auto res =
  10183. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  10184. ASSERT_TRUE(res);
  10185. EXPECT_EQ(StatusCode::OK_200, res->status);
  10186. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  10187. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  10188. }
  10189. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  10190. Server svr;
  10191. svr.set_trusted_proxies({"192.0.2.45"});
  10192. std::string observed_remote_addr;
  10193. std::string observed_xff;
  10194. svr.Get("/ip", [&](const Request &req, Response &res) {
  10195. observed_remote_addr = req.remote_addr;
  10196. observed_xff = req.get_header_value("X-Forwarded-For");
  10197. res.set_content("ok", "text/plain");
  10198. });
  10199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10200. auto se = detail::scope_exit([&] {
  10201. svr.stop();
  10202. t.join();
  10203. ASSERT_FALSE(svr.is_running());
  10204. });
  10205. svr.wait_until_ready();
  10206. Client cli(HOST, PORT);
  10207. auto res = cli.Get(
  10208. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  10209. ASSERT_TRUE(res);
  10210. EXPECT_EQ(StatusCode::OK_200, res->status);
  10211. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  10212. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10213. }
  10214. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  10215. Server svr;
  10216. svr.set_trusted_proxies({"192.0.2.45"});
  10217. std::string observed_remote_addr;
  10218. std::string observed_xff;
  10219. svr.Get("/ip", [&](const Request &req, Response &res) {
  10220. observed_remote_addr = req.remote_addr;
  10221. observed_xff = req.get_header_value("X-Forwarded-For");
  10222. res.set_content("ok", "text/plain");
  10223. });
  10224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10225. auto se = detail::scope_exit([&] {
  10226. svr.stop();
  10227. t.join();
  10228. ASSERT_FALSE(svr.is_running());
  10229. });
  10230. svr.wait_until_ready();
  10231. std::string raw_req =
  10232. "GET /ip HTTP/1.1\r\n"
  10233. "Host: localhost\r\n"
  10234. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  10235. "Connection: close\r\n"
  10236. "\r\n";
  10237. std::string out;
  10238. ASSERT_TRUE(send_request(5, raw_req, &out));
  10239. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10240. // Header parser trims surrounding whitespace of the header value
  10241. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  10242. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  10243. }
  10244. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  10245. Server svr;
  10246. svr.Post("/post", [&](const Request &req, Response &res) {
  10247. res.set_content(req.body, "text/plain");
  10248. });
  10249. svr.Put("/put", [&](const Request &req, Response &res) {
  10250. res.set_content(req.body, "text/plain");
  10251. });
  10252. svr.Patch("/patch", [&](const Request &req, Response &res) {
  10253. res.set_content(req.body, "text/plain");
  10254. });
  10255. svr.Delete("/delete", [&](const Request &req, Response &res) {
  10256. res.set_content(req.body, "text/plain");
  10257. });
  10258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10259. auto se = detail::scope_exit([&] {
  10260. svr.stop();
  10261. t.join();
  10262. ASSERT_FALSE(svr.is_running());
  10263. });
  10264. svr.wait_until_ready();
  10265. std::string resp;
  10266. // POST without Content-Length
  10267. ASSERT_TRUE(send_request(5,
  10268. "POST /post HTTP/1.1\r\n"
  10269. "Host: localhost\r\n"
  10270. "Connection: close\r\n"
  10271. "\r\n",
  10272. &resp));
  10273. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10274. // PUT without Content-Length
  10275. resp.clear();
  10276. ASSERT_TRUE(send_request(5,
  10277. "PUT /put HTTP/1.1\r\n"
  10278. "Host: localhost\r\n"
  10279. "Connection: close\r\n"
  10280. "\r\n",
  10281. &resp));
  10282. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10283. // PATCH without Content-Length
  10284. resp.clear();
  10285. ASSERT_TRUE(send_request(5,
  10286. "PATCH /patch HTTP/1.1\r\n"
  10287. "Host: localhost\r\n"
  10288. "Connection: close\r\n"
  10289. "\r\n",
  10290. &resp));
  10291. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10292. // DELETE without Content-Length
  10293. resp.clear();
  10294. ASSERT_TRUE(send_request(5,
  10295. "DELETE /delete HTTP/1.1\r\n"
  10296. "Host: localhost\r\n"
  10297. "Connection: close\r\n"
  10298. "\r\n",
  10299. &resp));
  10300. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  10301. }
  10302. //==============================================================================
  10303. // open_stream() Tests
  10304. //==============================================================================
  10305. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  10306. std::string result;
  10307. char buf[8192];
  10308. ssize_t n;
  10309. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10310. result.append(buf, static_cast<size_t>(n));
  10311. }
  10312. return result;
  10313. }
  10314. // Mock stream for unit tests
  10315. class MockStream : public Stream {
  10316. public:
  10317. std::string data;
  10318. size_t pos = 0;
  10319. ssize_t error_after = -1; // -1 = no error
  10320. explicit MockStream(const std::string &d, ssize_t err = -1)
  10321. : data(d), error_after(err) {}
  10322. bool is_readable() const override { return true; }
  10323. bool wait_readable() const override { return true; }
  10324. bool wait_writable() const override { return true; }
  10325. ssize_t read(char *ptr, size_t size) override {
  10326. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  10327. if (pos >= data.size()) return 0;
  10328. size_t limit =
  10329. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  10330. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  10331. std::memcpy(ptr, data.data() + pos, to_read);
  10332. pos += to_read;
  10333. return static_cast<ssize_t>(to_read);
  10334. }
  10335. ssize_t write(const char *, size_t) override { return -1; }
  10336. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  10337. ip = "127.0.0.1";
  10338. port = 0;
  10339. }
  10340. void get_local_ip_and_port(std::string &ip, int &port) const override {
  10341. ip = "127.0.0.1";
  10342. port = 0;
  10343. }
  10344. socket_t socket() const override { return INVALID_SOCKET; }
  10345. time_t duration() const override { return 0; }
  10346. };
  10347. TEST(StreamHandleTest, Basic) {
  10348. ClientImpl::StreamHandle handle;
  10349. EXPECT_FALSE(handle.is_valid());
  10350. handle.response = detail::make_unique<Response>();
  10351. handle.error = Error::Connection;
  10352. EXPECT_FALSE(handle.is_valid());
  10353. handle.error = Error::Success;
  10354. EXPECT_TRUE(handle.is_valid());
  10355. }
  10356. TEST(BodyReaderTest, Basic) {
  10357. MockStream stream("Hello, World!");
  10358. detail::BodyReader reader;
  10359. reader.stream = &stream;
  10360. reader.content_length = 13;
  10361. char buf[32];
  10362. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  10363. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  10364. EXPECT_TRUE(reader.eof);
  10365. }
  10366. TEST(BodyReaderTest, NoStream) {
  10367. detail::BodyReader reader;
  10368. char buf[32];
  10369. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10370. EXPECT_EQ(Error::Connection, reader.last_error);
  10371. }
  10372. TEST(BodyReaderTest, Error) {
  10373. MockStream stream("Hello, World!", 5);
  10374. detail::BodyReader reader;
  10375. reader.stream = &stream;
  10376. reader.content_length = 13;
  10377. char buf[32];
  10378. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  10379. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  10380. EXPECT_EQ(Error::Read, reader.last_error);
  10381. }
  10382. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  10383. // Mock-based StreamHandle tests relying on private internals are removed.
  10384. class OpenStreamTest : public ::testing::Test {
  10385. protected:
  10386. void SetUp() override {
  10387. svr_.Get("/hello", [](const Request &, Response &res) {
  10388. res.set_content("Hello World!", "text/plain");
  10389. });
  10390. svr_.Get("/large", [](const Request &, Response &res) {
  10391. res.set_content(std::string(10000, 'X'), "text/plain");
  10392. });
  10393. svr_.Get("/chunked", [](const Request &, Response &res) {
  10394. res.set_chunked_content_provider("text/plain",
  10395. [](size_t offset, DataSink &sink) {
  10396. if (offset < 15) {
  10397. sink.write("chunk", 5);
  10398. return true;
  10399. }
  10400. sink.done();
  10401. return true;
  10402. });
  10403. });
  10404. svr_.Get("/compressible", [](const Request &, Response &res) {
  10405. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10406. DataSink &sink) {
  10407. if (offset < 100 * 1024) {
  10408. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10409. sink.write(chunk.data(), chunk.size());
  10410. return true;
  10411. }
  10412. sink.done();
  10413. return true;
  10414. });
  10415. });
  10416. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10417. [](const Request & /*req*/, Response &res) {
  10418. auto i = new int(0);
  10419. res.set_header("Trailer", "Content-Length, X-Allowed");
  10420. res.set_chunked_content_provider(
  10421. "text/plain",
  10422. [i](size_t /*offset*/, DataSink &sink) {
  10423. switch (*i) {
  10424. case 0: sink.os << "123"; break;
  10425. case 1: sink.os << "456"; break;
  10426. case 2: sink.os << "789"; break;
  10427. case 3: {
  10428. sink.done_with_trailer(
  10429. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10430. } break;
  10431. }
  10432. (*i)++;
  10433. return true;
  10434. },
  10435. [i](bool success) {
  10436. EXPECT_TRUE(success);
  10437. delete i;
  10438. });
  10439. });
  10440. // Echo headers endpoint for header-related tests
  10441. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10442. std::string body;
  10443. for (const auto &h : req.headers) {
  10444. body.append(h.first);
  10445. body.push_back(':');
  10446. body.append(h.second);
  10447. body.push_back('\n');
  10448. }
  10449. res.set_content(body, "text/plain");
  10450. });
  10451. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10452. std::string body;
  10453. for (const auto &h : req.headers) {
  10454. body.append(h.first);
  10455. body.push_back(':');
  10456. body.append(h.second);
  10457. body.push_back('\n');
  10458. }
  10459. res.set_content(body, "text/plain");
  10460. });
  10461. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10462. svr_.wait_until_ready();
  10463. }
  10464. void TearDown() override {
  10465. svr_.stop();
  10466. if (thread_.joinable()) thread_.join();
  10467. }
  10468. Server svr_;
  10469. std::thread thread_;
  10470. };
  10471. TEST_F(OpenStreamTest, Basic) {
  10472. Client cli("127.0.0.1", 8787);
  10473. auto handle = cli.open_stream("GET", "/hello");
  10474. EXPECT_TRUE(handle.is_valid());
  10475. EXPECT_EQ("Hello World!", read_all(handle));
  10476. }
  10477. TEST_F(OpenStreamTest, SmallBuffer) {
  10478. Client cli("127.0.0.1", 8787);
  10479. auto handle = cli.open_stream("GET", "/hello");
  10480. std::string result;
  10481. char buf[4];
  10482. ssize_t n;
  10483. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10484. result.append(buf, static_cast<size_t>(n));
  10485. EXPECT_EQ("Hello World!", result);
  10486. }
  10487. TEST_F(OpenStreamTest, DefaultHeaders) {
  10488. Client cli("127.0.0.1", 8787);
  10489. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10490. {
  10491. auto handle = cli.open_stream("GET", "/echo-headers");
  10492. ASSERT_TRUE(handle.is_valid());
  10493. auto body = read_all(handle);
  10494. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10495. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10496. std::string::npos);
  10497. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10498. }
  10499. // open_stream POST with body and no explicit content_type should NOT add
  10500. // text/plain Content-Type (behavior differs from non-streaming path), but
  10501. // should include Content-Length
  10502. {
  10503. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10504. ASSERT_TRUE(handle.is_valid());
  10505. auto body = read_all(handle);
  10506. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10507. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10508. }
  10509. // open_stream POST with explicit Content-Type should preserve it
  10510. {
  10511. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10512. {{"Content-Type", "application/custom"}},
  10513. "{}", "application/custom");
  10514. ASSERT_TRUE(handle.is_valid());
  10515. auto body = read_all(handle);
  10516. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10517. }
  10518. // User-specified User-Agent must not be overwritten for stream API
  10519. {
  10520. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10521. {{"User-Agent", "MyAgent/1.2"}});
  10522. ASSERT_TRUE(handle.is_valid());
  10523. auto body = read_all(handle);
  10524. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10525. }
  10526. }
  10527. TEST_F(OpenStreamTest, Large) {
  10528. Client cli("127.0.0.1", 8787);
  10529. auto handle = cli.open_stream("GET", "/large");
  10530. EXPECT_EQ(10000u, read_all(handle).size());
  10531. }
  10532. TEST_F(OpenStreamTest, ConnectionError) {
  10533. Client cli("127.0.0.1", 9999);
  10534. auto handle = cli.open_stream("GET", "/hello");
  10535. EXPECT_FALSE(handle.is_valid());
  10536. }
  10537. TEST_F(OpenStreamTest, Chunked) {
  10538. Client cli("127.0.0.1", 8787);
  10539. auto handle = cli.open_stream("GET", "/chunked");
  10540. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10541. "Transfer-Encoding") == "chunked");
  10542. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10543. }
  10544. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10545. Client cli("127.0.0.1", 8787);
  10546. auto handle =
  10547. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10548. ASSERT_TRUE(handle.is_valid());
  10549. // Consume body to allow trailers to be received/parsed
  10550. auto body = read_all(handle);
  10551. // Explicitly parse trailers (ensure trailers are available for assertion)
  10552. handle.parse_trailers_if_needed();
  10553. EXPECT_EQ(std::string("123456789"), body);
  10554. // The response should include a Trailer header declaring both names
  10555. ASSERT_TRUE(handle.response);
  10556. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10557. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10558. handle.response->get_header_value("Trailer"));
  10559. // Prohibited trailer must not be present
  10560. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10561. // Allowed trailer should be present
  10562. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10563. EXPECT_EQ(std::string("yes"),
  10564. handle.response->get_trailer_value("X-Allowed"));
  10565. // Verify trailers are NOT present as regular headers
  10566. EXPECT_EQ(std::string(""),
  10567. handle.response->get_header_value("Content-Length"));
  10568. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10569. }
  10570. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10571. TEST_F(OpenStreamTest, Gzip) {
  10572. Client cli("127.0.0.1", 8787);
  10573. auto handle = cli.open_stream("GET", "/compressible", {},
  10574. {{"Accept-Encoding", "gzip"}});
  10575. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10576. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10577. }
  10578. #endif
  10579. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10580. TEST_F(OpenStreamTest, Brotli) {
  10581. Client cli("127.0.0.1", 8787);
  10582. auto handle =
  10583. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10584. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10585. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10586. }
  10587. #endif
  10588. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10589. TEST_F(OpenStreamTest, Zstd) {
  10590. Client cli("127.0.0.1", 8787);
  10591. auto handle = cli.open_stream("GET", "/compressible", {},
  10592. {{"Accept-Encoding", "zstd"}});
  10593. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10594. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10595. }
  10596. #endif
  10597. #ifdef CPPHTTPLIB_SSL_ENABLED
  10598. class SSLOpenStreamTest : public ::testing::Test {
  10599. protected:
  10600. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10601. void SetUp() override {
  10602. svr_.Get("/hello", [](const Request &, Response &res) {
  10603. res.set_content("Hello SSL World!", "text/plain");
  10604. });
  10605. svr_.Get("/chunked", [](const Request &, Response &res) {
  10606. res.set_chunked_content_provider("text/plain",
  10607. [](size_t offset, DataSink &sink) {
  10608. if (offset < 15) {
  10609. sink.write("chunk", 5);
  10610. return true;
  10611. }
  10612. sink.done();
  10613. return true;
  10614. });
  10615. });
  10616. svr_.Post("/echo", [](const Request &req, Response &res) {
  10617. res.set_content(req.body, req.get_header_value("Content-Type"));
  10618. });
  10619. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10620. std::string body = req.body;
  10621. res.set_chunked_content_provider(
  10622. "text/plain", [body](size_t offset, DataSink &sink) {
  10623. if (offset < body.size()) {
  10624. sink.write(body.data() + offset, body.size() - offset);
  10625. }
  10626. sink.done();
  10627. return true;
  10628. });
  10629. });
  10630. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10631. svr_.wait_until_ready();
  10632. }
  10633. void TearDown() override {
  10634. svr_.stop();
  10635. if (thread_.joinable()) thread_.join();
  10636. }
  10637. SSLServer svr_;
  10638. std::thread thread_;
  10639. };
  10640. TEST_F(SSLOpenStreamTest, Basic) {
  10641. SSLClient cli("127.0.0.1", 8788);
  10642. cli.enable_server_certificate_verification(false);
  10643. auto handle = cli.open_stream("GET", "/hello");
  10644. ASSERT_TRUE(handle.is_valid());
  10645. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10646. }
  10647. TEST_F(SSLOpenStreamTest, Chunked) {
  10648. SSLClient cli("127.0.0.1", 8788);
  10649. cli.enable_server_certificate_verification(false);
  10650. auto handle = cli.open_stream("GET", "/chunked");
  10651. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10652. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10653. "Transfer-Encoding") == "chunked");
  10654. auto body = read_all(handle);
  10655. EXPECT_EQ("chunkchunkchunk", body);
  10656. }
  10657. TEST_F(SSLOpenStreamTest, Post) {
  10658. SSLClient cli("127.0.0.1", 8788);
  10659. cli.enable_server_certificate_verification(false);
  10660. auto handle =
  10661. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10662. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10663. EXPECT_EQ(200, handle.response->status);
  10664. auto body = read_all(handle);
  10665. EXPECT_EQ("Hello SSL POST", body);
  10666. }
  10667. TEST_F(SSLOpenStreamTest, PostChunked) {
  10668. SSLClient cli("127.0.0.1", 8788);
  10669. cli.enable_server_certificate_verification(false);
  10670. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10671. "Chunked SSL Data", "text/plain");
  10672. ASSERT_TRUE(handle.is_valid());
  10673. EXPECT_EQ(200, handle.response->status);
  10674. auto body = read_all(handle);
  10675. EXPECT_EQ("Chunked SSL Data", body);
  10676. }
  10677. #endif // CPPHTTPLIB_SSL_ENABLED
  10678. //==============================================================================
  10679. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10680. // results for various scenarios.
  10681. //==============================================================================
  10682. TEST(ParityTest, GetVsOpenStream) {
  10683. Server svr;
  10684. const std::string path = "/parity";
  10685. const std::string content = "Parity test content: hello world";
  10686. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10687. res.set_content(content, "text/plain");
  10688. });
  10689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10690. auto se = detail::scope_exit([&] {
  10691. svr.stop();
  10692. t.join();
  10693. ASSERT_FALSE(svr.is_running());
  10694. });
  10695. svr.wait_until_ready();
  10696. Client cli(HOST, PORT);
  10697. // Non-stream path
  10698. auto r1 = cli.Get(path);
  10699. ASSERT_TRUE(r1);
  10700. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10701. // Stream path
  10702. auto h = cli.open_stream("GET", path);
  10703. ASSERT_TRUE(h.is_valid());
  10704. EXPECT_EQ(r1->body, read_all(h));
  10705. }
  10706. // Helper to compress data with provided compressor type T
  10707. template <typename Compressor>
  10708. static std::string compress_payload_for_parity(const std::string &in) {
  10709. std::string out;
  10710. Compressor compressor;
  10711. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10712. [&](const char *data, size_t n) {
  10713. out.append(data, n);
  10714. return true;
  10715. });
  10716. EXPECT_TRUE(ok);
  10717. return out;
  10718. }
  10719. // Helper function for compression parity tests
  10720. template <typename Compressor>
  10721. static void test_compression_parity(const std::string &original,
  10722. const std::string &path,
  10723. const std::string &encoding) {
  10724. const std::string compressed =
  10725. compress_payload_for_parity<Compressor>(original);
  10726. Server svr;
  10727. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10728. res.set_content(compressed, "application/octet-stream");
  10729. res.set_header("Content-Encoding", encoding);
  10730. });
  10731. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. ASSERT_FALSE(svr.is_running());
  10736. });
  10737. svr.wait_until_ready();
  10738. Client cli(HOST, PORT);
  10739. // Non-streaming
  10740. {
  10741. auto res = cli.Get(path);
  10742. ASSERT_TRUE(res);
  10743. EXPECT_EQ(StatusCode::OK_200, res->status);
  10744. EXPECT_EQ(original, res->body);
  10745. }
  10746. // Streaming
  10747. {
  10748. auto h = cli.open_stream("GET", path);
  10749. ASSERT_TRUE(h.is_valid());
  10750. EXPECT_EQ(original, read_all(h));
  10751. }
  10752. }
  10753. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10754. TEST(ParityTest, Gzip) {
  10755. test_compression_parity<detail::gzip_compressor>(
  10756. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10757. }
  10758. #endif
  10759. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10760. TEST(ParityTest, Brotli) {
  10761. test_compression_parity<detail::brotli_compressor>(
  10762. "Hello, brotli parity test payload", "/parity-br", "br");
  10763. }
  10764. #endif
  10765. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10766. TEST(ParityTest, Zstd) {
  10767. test_compression_parity<detail::zstd_compressor>(
  10768. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10769. }
  10770. #endif
  10771. //==============================================================================
  10772. // New Stream API Tests
  10773. //==============================================================================
  10774. inline std::string read_body(httplib::stream::Result &result) {
  10775. std::string body;
  10776. while (result.next()) {
  10777. body.append(result.data(), result.size());
  10778. }
  10779. return body;
  10780. }
  10781. TEST(ClientConnectionTest, Basic) {
  10782. httplib::ClientConnection conn;
  10783. EXPECT_FALSE(conn.is_open());
  10784. conn.sock = 1;
  10785. EXPECT_TRUE(conn.is_open());
  10786. httplib::ClientConnection conn2(std::move(conn));
  10787. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10788. conn2.sock = INVALID_SOCKET;
  10789. }
  10790. // Unified test server for all stream::* tests
  10791. class StreamApiTest : public ::testing::Test {
  10792. protected:
  10793. void SetUp() override {
  10794. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10795. res.set_content("Hello World!", "text/plain");
  10796. });
  10797. svr_.Get("/echo-params",
  10798. [](const httplib::Request &req, httplib::Response &res) {
  10799. std::string r;
  10800. for (const auto &p : req.params) {
  10801. if (!r.empty()) r += "&";
  10802. r += p.first + "=" + p.second;
  10803. }
  10804. res.set_content(r, "text/plain");
  10805. });
  10806. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10807. res.set_content(req.body, req.get_header_value("Content-Type"));
  10808. });
  10809. svr_.Post("/echo-headers",
  10810. [](const httplib::Request &req, httplib::Response &res) {
  10811. std::string r;
  10812. for (const auto &h : req.headers)
  10813. r += h.first + ": " + h.second + "\n";
  10814. res.set_content(r, "text/plain");
  10815. });
  10816. svr_.Post("/echo-params",
  10817. [](const httplib::Request &req, httplib::Response &res) {
  10818. std::string r = "params:";
  10819. for (const auto &p : req.params)
  10820. r += p.first + "=" + p.second + ";";
  10821. res.set_content(r + " body:" + req.body, "text/plain");
  10822. });
  10823. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10824. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10825. });
  10826. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10827. res.set_content("PUT:" + req.body, "text/plain");
  10828. });
  10829. svr_.Patch("/echo",
  10830. [](const httplib::Request &req, httplib::Response &res) {
  10831. res.set_content("PATCH:" + req.body, "text/plain");
  10832. });
  10833. svr_.Delete(
  10834. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10835. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10836. "text/plain");
  10837. });
  10838. svr_.Get("/head-test",
  10839. [](const httplib::Request &, httplib::Response &res) {
  10840. res.set_content("body for HEAD", "text/plain");
  10841. });
  10842. svr_.Options("/options",
  10843. [](const httplib::Request &, httplib::Response &res) {
  10844. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10845. });
  10846. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10847. svr_.wait_until_ready();
  10848. }
  10849. void TearDown() override {
  10850. svr_.stop();
  10851. if (thread_.joinable()) thread_.join();
  10852. }
  10853. httplib::Server svr_;
  10854. std::thread thread_;
  10855. };
  10856. // stream::Get tests
  10857. TEST_F(StreamApiTest, GetBasic) {
  10858. httplib::Client cli(HOST, PORT);
  10859. auto result = httplib::stream::Get(cli, "/hello");
  10860. ASSERT_TRUE(result.is_valid());
  10861. EXPECT_EQ(200, result.status());
  10862. EXPECT_EQ("Hello World!", read_body(result));
  10863. }
  10864. TEST_F(StreamApiTest, GetWithParams) {
  10865. httplib::Client cli(HOST, PORT);
  10866. httplib::Params params{{"foo", "bar"}};
  10867. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10868. ASSERT_TRUE(result.is_valid());
  10869. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10870. }
  10871. TEST_F(StreamApiTest, GetConnectionError) {
  10872. httplib::Client cli(HOST, 9999);
  10873. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10874. }
  10875. TEST_F(StreamApiTest, Get404) {
  10876. httplib::Client cli(HOST, PORT);
  10877. auto result = httplib::stream::Get(cli, "/nonexistent");
  10878. EXPECT_TRUE(result.is_valid());
  10879. EXPECT_EQ(404, result.status());
  10880. }
  10881. // stream::Post tests
  10882. TEST_F(StreamApiTest, PostBasic) {
  10883. httplib::Client cli(HOST, PORT);
  10884. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10885. "application/json");
  10886. ASSERT_TRUE(result.is_valid());
  10887. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10888. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10889. }
  10890. TEST_F(StreamApiTest, PostWithHeaders) {
  10891. httplib::Client cli(HOST, PORT);
  10892. httplib::Headers headers{{"X-Custom", "value"}};
  10893. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10894. "text/plain");
  10895. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10896. }
  10897. TEST_F(StreamApiTest, PostWithParams) {
  10898. httplib::Client cli(HOST, PORT);
  10899. httplib::Params params{{"k", "v"}};
  10900. auto result =
  10901. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10902. auto body = read_body(result);
  10903. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10904. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10905. }
  10906. TEST_F(StreamApiTest, PostLarge) {
  10907. httplib::Client cli(HOST, PORT);
  10908. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10909. size_t total = 0;
  10910. while (result.next()) {
  10911. total += result.size();
  10912. }
  10913. EXPECT_EQ(100u * 1024u, total);
  10914. }
  10915. // stream::Put/Patch tests
  10916. TEST_F(StreamApiTest, PutAndPatch) {
  10917. httplib::Client cli(HOST, PORT);
  10918. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10919. EXPECT_EQ("PUT:test", read_body(put));
  10920. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10921. EXPECT_EQ("PATCH:test", read_body(patch));
  10922. }
  10923. // stream::Delete tests
  10924. TEST_F(StreamApiTest, Delete) {
  10925. httplib::Client cli(HOST, PORT);
  10926. auto del1 = httplib::stream::Delete(cli, "/resource");
  10927. EXPECT_EQ("Deleted", read_body(del1));
  10928. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10929. EXPECT_EQ("Deleted:data", read_body(del2));
  10930. }
  10931. // stream::Head/Options tests
  10932. TEST_F(StreamApiTest, HeadAndOptions) {
  10933. httplib::Client cli(HOST, PORT);
  10934. auto head = httplib::stream::Head(cli, "/head-test");
  10935. EXPECT_TRUE(head.is_valid());
  10936. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10937. auto opts = httplib::stream::Options(cli, "/options");
  10938. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10939. }
  10940. // SSL stream::* tests
  10941. #ifdef CPPHTTPLIB_SSL_ENABLED
  10942. class SSLStreamApiTest : public ::testing::Test {
  10943. protected:
  10944. void SetUp() override {
  10945. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10946. res.set_content("Hello SSL!", "text/plain");
  10947. });
  10948. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10949. res.set_content(req.body, "text/plain");
  10950. });
  10951. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10952. svr_.wait_until_ready();
  10953. }
  10954. void TearDown() override {
  10955. svr_.stop();
  10956. if (thread_.joinable()) thread_.join();
  10957. }
  10958. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10959. std::thread thread_;
  10960. };
  10961. TEST_F(SSLStreamApiTest, GetAndPost) {
  10962. httplib::SSLClient cli("127.0.0.1", 8803);
  10963. cli.enable_server_certificate_verification(false);
  10964. auto get = httplib::stream::Get(cli, "/hello");
  10965. EXPECT_EQ("Hello SSL!", read_body(get));
  10966. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10967. EXPECT_EQ("test", read_body(post));
  10968. }
  10969. #endif
  10970. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10971. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10972. // BodyReader
  10973. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10974. // Test that read timeout during streaming is detected
  10975. // Use a large content-length response where server delays mid-stream
  10976. Server svr;
  10977. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10978. // Send a large response with delay in the middle
  10979. res.set_content_provider(
  10980. 1000, // content_length
  10981. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10982. if (offset < 100) {
  10983. // Send first 100 bytes immediately
  10984. std::string data(100, 'A');
  10985. sink.write(data.c_str(), data.size());
  10986. return true;
  10987. }
  10988. // Then delay longer than client timeout
  10989. std::this_thread::sleep_for(std::chrono::seconds(3));
  10990. std::string data(900, 'B');
  10991. sink.write(data.c_str(), data.size());
  10992. return true;
  10993. });
  10994. });
  10995. auto port = 8091;
  10996. std::thread t([&]() { svr.listen("localhost", port); });
  10997. svr.wait_until_ready();
  10998. Client cli("localhost", port);
  10999. cli.set_read_timeout(1, 0); // 1 second timeout
  11000. auto handle = cli.open_stream("GET", "/slow-stream");
  11001. ASSERT_TRUE(handle.is_valid());
  11002. char buf[256];
  11003. ssize_t total = 0;
  11004. ssize_t n;
  11005. bool got_error = false;
  11006. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11007. total += n;
  11008. }
  11009. if (n < 0) {
  11010. got_error = true;
  11011. // Should be timeout or read error
  11012. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11013. handle.get_read_error() == Error::Read)
  11014. << "Actual error: " << to_string(handle.get_read_error());
  11015. }
  11016. // Either we got an error, or we got less data than expected
  11017. EXPECT_TRUE(got_error || total < 1000)
  11018. << "Expected timeout but got all " << total << " bytes";
  11019. svr.stop();
  11020. t.join();
  11021. }
  11022. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  11023. // Test connection closed detection via BodyReader
  11024. Server svr;
  11025. std::atomic<bool> close_now{false};
  11026. svr.Get("/will-close", [&](const Request &, Response &res) {
  11027. res.set_content_provider(
  11028. 10000, // Large content_length that we won't fully send
  11029. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11030. if (offset < 100) {
  11031. std::string data(100, 'X');
  11032. sink.write(data.c_str(), data.size());
  11033. return true;
  11034. }
  11035. // Wait for signal then abort
  11036. while (!close_now) {
  11037. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11038. }
  11039. return false; // Abort - server will close connection
  11040. });
  11041. });
  11042. auto port = 8092;
  11043. std::thread t([&]() { svr.listen("localhost", port); });
  11044. svr.wait_until_ready();
  11045. Client cli("localhost", port);
  11046. auto handle = cli.open_stream("GET", "/will-close");
  11047. ASSERT_TRUE(handle.is_valid());
  11048. char buf[256];
  11049. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11050. EXPECT_GT(n, 0) << "First read should succeed";
  11051. // Signal server to close
  11052. close_now = true;
  11053. // Keep reading until error or EOF
  11054. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11055. // Keep reading
  11056. }
  11057. // Should get an error since content_length wasn't satisfied
  11058. if (n < 0) {
  11059. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11060. handle.get_read_error() == Error::Read)
  11061. << "Actual error: " << to_string(handle.get_read_error());
  11062. }
  11063. svr.stop();
  11064. t.join();
  11065. }
  11066. #ifdef CPPHTTPLIB_SSL_ENABLED
  11067. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  11068. // Test that read timeout during SSL streaming is detected
  11069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11070. svr.Get("/slow-stream", [](const Request &, Response &res) {
  11071. res.set_content_provider(
  11072. 1000, "text/plain",
  11073. [](size_t offset, size_t /*length*/, DataSink &sink) {
  11074. if (offset < 100) {
  11075. std::string data(100, 'A');
  11076. sink.write(data.c_str(), data.size());
  11077. return true;
  11078. }
  11079. std::this_thread::sleep_for(std::chrono::seconds(3));
  11080. std::string data(900, 'B');
  11081. sink.write(data.c_str(), data.size());
  11082. return true;
  11083. });
  11084. });
  11085. auto port = 8093;
  11086. std::thread t([&]() { svr.listen("localhost", port); });
  11087. svr.wait_until_ready();
  11088. SSLClient cli("localhost", port);
  11089. cli.enable_server_certificate_verification(false);
  11090. cli.set_read_timeout(1, 0); // 1 second timeout
  11091. auto handle = cli.open_stream("GET", "/slow-stream");
  11092. ASSERT_TRUE(handle.is_valid());
  11093. char buf[256];
  11094. ssize_t total = 0;
  11095. ssize_t n;
  11096. bool got_error = false;
  11097. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11098. total += n;
  11099. }
  11100. if (n < 0) {
  11101. got_error = true;
  11102. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  11103. handle.get_read_error() == Error::Read)
  11104. << "Actual error: " << to_string(handle.get_read_error());
  11105. }
  11106. EXPECT_TRUE(got_error || total < 1000)
  11107. << "Expected timeout but got all " << total << " bytes";
  11108. svr.stop();
  11109. t.join();
  11110. }
  11111. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  11112. // Test SSL connection closed detection
  11113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11114. std::atomic<bool> close_now{false};
  11115. svr.Get("/will-close", [&](const Request &, Response &res) {
  11116. res.set_content_provider(
  11117. 10000, "text/plain",
  11118. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  11119. if (offset < 100) {
  11120. std::string data(100, 'X');
  11121. sink.write(data.c_str(), data.size());
  11122. return true;
  11123. }
  11124. while (!close_now) {
  11125. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11126. }
  11127. return false;
  11128. });
  11129. });
  11130. auto port = 8094;
  11131. std::thread t([&]() { svr.listen("localhost", port); });
  11132. svr.wait_until_ready();
  11133. SSLClient cli("localhost", port);
  11134. cli.enable_server_certificate_verification(false);
  11135. auto handle = cli.open_stream("GET", "/will-close");
  11136. ASSERT_TRUE(handle.is_valid());
  11137. char buf[256];
  11138. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  11139. EXPECT_GT(n, 0);
  11140. // Signal server to close
  11141. close_now = true;
  11142. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11143. // Keep reading
  11144. }
  11145. if (n < 0) {
  11146. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  11147. handle.get_read_error() == Error::Read)
  11148. << "Actual error: " << to_string(handle.get_read_error());
  11149. }
  11150. svr.stop();
  11151. t.join();
  11152. }
  11153. #endif
  11154. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  11155. using namespace httplib;
  11156. // Create a test file
  11157. const char *fname = "etag_testfile.txt";
  11158. const char *content = "etag-content";
  11159. {
  11160. std::ofstream ofs(fname);
  11161. ofs << content;
  11162. ASSERT_TRUE(ofs.good());
  11163. }
  11164. Server svr;
  11165. svr.set_mount_point("/static", ".");
  11166. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  11167. svr.wait_until_ready();
  11168. Client cli(HOST, PORT);
  11169. // First request: should get 200 with ETag header
  11170. auto res1 = cli.Get("/static/etag_testfile.txt");
  11171. ASSERT_TRUE(res1);
  11172. ASSERT_EQ(200, res1->status);
  11173. ASSERT_TRUE(res1->has_header("ETag"));
  11174. std::string etag = res1->get_header_value("ETag");
  11175. EXPECT_FALSE(etag.empty());
  11176. // Verify ETag format: W/"hex-hex"
  11177. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  11178. EXPECT_EQ('W', etag[0]);
  11179. EXPECT_EQ('/', etag[1]);
  11180. EXPECT_EQ('"', etag[2]);
  11181. EXPECT_EQ('"', etag.back());
  11182. // Exact match: expect 304 Not Modified
  11183. Headers h2 = {{"If-None-Match", etag}};
  11184. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  11185. ASSERT_TRUE(res2);
  11186. EXPECT_EQ(304, res2->status);
  11187. // Wildcard match: expect 304 Not Modified
  11188. Headers h3 = {{"If-None-Match", "*"}};
  11189. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  11190. ASSERT_TRUE(res3);
  11191. EXPECT_EQ(304, res3->status);
  11192. // Non-matching ETag: expect 200
  11193. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  11194. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  11195. ASSERT_TRUE(res4);
  11196. EXPECT_EQ(200, res4->status);
  11197. // Multiple ETags with one matching: expect 304
  11198. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  11199. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  11200. ASSERT_TRUE(res5);
  11201. EXPECT_EQ(304, res5->status);
  11202. svr.stop();
  11203. t.join();
  11204. std::remove(fname);
  11205. }
  11206. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  11207. using namespace httplib;
  11208. Server svr;
  11209. svr.set_mount_point("/static", ".");
  11210. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11211. svr.wait_until_ready();
  11212. Client cli(HOST, PORT);
  11213. // Send If-None-Match: * to a non-existent file
  11214. Headers h = {{"If-None-Match", "*"}};
  11215. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  11216. ASSERT_TRUE(res);
  11217. EXPECT_EQ(404, res->status);
  11218. svr.stop();
  11219. t.join();
  11220. }
  11221. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  11222. using namespace httplib;
  11223. // Create a test file
  11224. const char *fname = "ims_testfile.txt";
  11225. const char *content = "if-modified-since-test";
  11226. {
  11227. std::ofstream ofs(fname);
  11228. ofs << content;
  11229. ASSERT_TRUE(ofs.good());
  11230. }
  11231. Server svr;
  11232. svr.set_mount_point("/static", ".");
  11233. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11234. svr.wait_until_ready();
  11235. Client cli(HOST, PORT);
  11236. // First request: should get 200 with Last-Modified header
  11237. auto res1 = cli.Get("/static/ims_testfile.txt");
  11238. ASSERT_TRUE(res1);
  11239. ASSERT_EQ(200, res1->status);
  11240. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11241. std::string last_modified = res1->get_header_value("Last-Modified");
  11242. EXPECT_FALSE(last_modified.empty());
  11243. // If-Modified-Since with same time: expect 304
  11244. Headers h2 = {{"If-Modified-Since", last_modified}};
  11245. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  11246. ASSERT_TRUE(res2);
  11247. EXPECT_EQ(304, res2->status);
  11248. // If-Modified-Since with future time: expect 304
  11249. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11250. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  11251. ASSERT_TRUE(res3);
  11252. EXPECT_EQ(304, res3->status);
  11253. // If-Modified-Since with past time: expect 200
  11254. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11255. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  11256. ASSERT_TRUE(res4);
  11257. EXPECT_EQ(200, res4->status);
  11258. // If-None-Match takes precedence over If-Modified-Since
  11259. // (send matching ETag with old If-Modified-Since -> should still be 304)
  11260. ASSERT_TRUE(res1->has_header("ETag"));
  11261. std::string etag = res1->get_header_value("ETag");
  11262. Headers h5 = {{"If-None-Match", etag},
  11263. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11264. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  11265. ASSERT_TRUE(res5);
  11266. EXPECT_EQ(304, res5->status);
  11267. svr.stop();
  11268. t.join();
  11269. std::remove(fname);
  11270. }
  11271. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  11272. using namespace httplib;
  11273. Server svr;
  11274. // Endpoint that returns compressible content
  11275. svr.Get("/compressible", [](const Request &, Response &res) {
  11276. // Return a large enough body to trigger compression
  11277. std::string body(1000, 'a');
  11278. res.set_content(body, "text/plain");
  11279. });
  11280. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11281. svr.wait_until_ready();
  11282. Client cli(HOST, PORT);
  11283. // Request with gzip support: should get Vary header when compressed
  11284. cli.set_compress(true);
  11285. auto res1 = cli.Get("/compressible");
  11286. ASSERT_TRUE(res1);
  11287. EXPECT_EQ(200, res1->status);
  11288. // If Content-Encoding is set, Vary should also be set
  11289. if (res1->has_header("Content-Encoding")) {
  11290. EXPECT_TRUE(res1->has_header("Vary"));
  11291. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  11292. }
  11293. // Request without Accept-Encoding header: should not have compression
  11294. Headers h_no_compress;
  11295. auto res2 = cli.Get("/compressible", h_no_compress);
  11296. ASSERT_TRUE(res2);
  11297. EXPECT_EQ(200, res2->status);
  11298. // Verify Vary header is present when compression is applied
  11299. // (the exact behavior depends on server configuration)
  11300. svr.stop();
  11301. t.join();
  11302. }
  11303. TEST(ETagTest, IfRangeWithETag) {
  11304. using namespace httplib;
  11305. // Create a test file with known content
  11306. const char *fname = "if_range_testfile.txt";
  11307. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  11308. {
  11309. std::ofstream ofs(fname);
  11310. ofs << content;
  11311. ASSERT_TRUE(ofs.good());
  11312. }
  11313. Server svr;
  11314. svr.set_mount_point("/static", ".");
  11315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11316. svr.wait_until_ready();
  11317. Client cli(HOST, PORT);
  11318. // First request: get ETag
  11319. auto res1 = cli.Get("/static/if_range_testfile.txt");
  11320. ASSERT_TRUE(res1);
  11321. ASSERT_EQ(200, res1->status);
  11322. ASSERT_TRUE(res1->has_header("ETag"));
  11323. std::string etag = res1->get_header_value("ETag");
  11324. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  11325. // Since our server generates weak ETags (W/"..."), If-Range with our
  11326. // ETag should NOT result in partial content - it should return full content.
  11327. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  11328. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  11329. ASSERT_TRUE(res2);
  11330. // Weak ETag in If-Range -> full content (200), not partial (206)
  11331. EXPECT_EQ(200, res2->status);
  11332. EXPECT_EQ(content, res2->body);
  11333. EXPECT_FALSE(res2->has_header("Content-Range"));
  11334. // Range request with non-matching If-Range (ETag): should get 200 (full
  11335. // content)
  11336. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  11337. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  11338. ASSERT_TRUE(res3);
  11339. EXPECT_EQ(200, res3->status);
  11340. EXPECT_EQ(content, res3->body);
  11341. EXPECT_FALSE(res3->has_header("Content-Range"));
  11342. // Range request with strong ETag (hypothetical - our server doesn't generate
  11343. // strong ETags, but if client sends a strong ETag that doesn't match, it
  11344. // should return full content)
  11345. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  11346. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  11347. ASSERT_TRUE(res4);
  11348. EXPECT_EQ(200, res4->status);
  11349. EXPECT_EQ(content, res4->body);
  11350. EXPECT_FALSE(res4->has_header("Content-Range"));
  11351. svr.stop();
  11352. t.join();
  11353. std::remove(fname);
  11354. }
  11355. TEST(ETagTest, IfRangeWithDate) {
  11356. using namespace httplib;
  11357. // Create a test file
  11358. const char *fname = "if_range_date_testfile.txt";
  11359. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  11360. {
  11361. std::ofstream ofs(fname);
  11362. ofs << content;
  11363. ASSERT_TRUE(ofs.good());
  11364. }
  11365. Server svr;
  11366. svr.set_mount_point("/static", ".");
  11367. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11368. svr.wait_until_ready();
  11369. Client cli(HOST, PORT);
  11370. // First request: get Last-Modified
  11371. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  11372. ASSERT_TRUE(res1);
  11373. ASSERT_EQ(200, res1->status);
  11374. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11375. std::string last_modified = res1->get_header_value("Last-Modified");
  11376. // Range request with matching If-Range (date): should get 206
  11377. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  11378. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  11379. ASSERT_TRUE(res2);
  11380. EXPECT_EQ(206, res2->status);
  11381. EXPECT_EQ("FGHIJ", res2->body);
  11382. // Range request with old If-Range date: should get 200 (full content)
  11383. Headers h3 = {{"Range", "bytes=5-9"},
  11384. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  11385. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  11386. ASSERT_TRUE(res3);
  11387. EXPECT_EQ(200, res3->status);
  11388. EXPECT_EQ(content, res3->body);
  11389. // Range request with future If-Range date: should get 206
  11390. Headers h4 = {{"Range", "bytes=0-4"},
  11391. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  11392. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  11393. ASSERT_TRUE(res4);
  11394. EXPECT_EQ(206, res4->status);
  11395. EXPECT_EQ("ABCDE", res4->body);
  11396. svr.stop();
  11397. t.join();
  11398. std::remove(fname);
  11399. }
  11400. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  11401. using namespace httplib;
  11402. const char *fname = "etag_malformed.txt";
  11403. const char *content = "malformed-etag";
  11404. {
  11405. std::ofstream ofs(fname);
  11406. ofs << content;
  11407. ASSERT_TRUE(ofs.good());
  11408. }
  11409. Server svr;
  11410. svr.set_mount_point("/static", ".");
  11411. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11412. svr.wait_until_ready();
  11413. Client cli(HOST, PORT);
  11414. // baseline: should get 200 and an ETag
  11415. auto res1 = cli.Get("/static/etag_malformed.txt");
  11416. ASSERT_TRUE(res1);
  11417. ASSERT_EQ(200, res1->status);
  11418. ASSERT_TRUE(res1->has_header("ETag"));
  11419. // Malformed ETag value (missing quotes) should be treated as non-matching
  11420. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11421. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11422. ASSERT_TRUE(res_bad);
  11423. EXPECT_EQ(200, res_bad->status);
  11424. // Whitespace-only header value should be considered invalid / non-matching
  11425. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11426. "Host: localhost\r\n"
  11427. "If-None-Match: \r\n"
  11428. "Connection: close\r\n"
  11429. "\r\n";
  11430. std::string out;
  11431. ASSERT_TRUE(send_request(5, raw_req, &out));
  11432. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11433. svr.stop();
  11434. t.join();
  11435. std::remove(fname);
  11436. }
  11437. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11438. using namespace httplib;
  11439. const char *fname = "ims_invalid_format.txt";
  11440. const char *content = "ims-bad-format";
  11441. {
  11442. std::ofstream ofs(fname);
  11443. ofs << content;
  11444. ASSERT_TRUE(ofs.good());
  11445. }
  11446. Server svr;
  11447. svr.set_mount_point("/static", ".");
  11448. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11449. svr.wait_until_ready();
  11450. Client cli(HOST, PORT);
  11451. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11452. ASSERT_TRUE(res1);
  11453. ASSERT_EQ(200, res1->status);
  11454. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11455. // If-Modified-Since with invalid format should not result in 304
  11456. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11457. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11458. ASSERT_TRUE(res_bad);
  11459. EXPECT_EQ(200, res_bad->status);
  11460. // If-Range with invalid date format should be treated as mismatch -> full
  11461. // content (200)
  11462. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11463. {"If-Range", "invalid-date"}};
  11464. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11465. ASSERT_TRUE(res_ifrange);
  11466. EXPECT_EQ(200, res_ifrange->status);
  11467. svr.stop();
  11468. t.join();
  11469. std::remove(fname);
  11470. }
  11471. TEST(ETagTest, IfRangeWithMalformedETag) {
  11472. using namespace httplib;
  11473. const char *fname = "ifrange_malformed.txt";
  11474. const std::string content = "0123456789";
  11475. {
  11476. std::ofstream ofs(fname);
  11477. ofs << content;
  11478. ASSERT_TRUE(ofs.good());
  11479. }
  11480. Server svr;
  11481. svr.set_mount_point("/static", ".");
  11482. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11483. svr.wait_until_ready();
  11484. Client cli(HOST, PORT);
  11485. // First request: get ETag
  11486. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11487. ASSERT_TRUE(res1);
  11488. ASSERT_EQ(200, res1->status);
  11489. ASSERT_TRUE(res1->has_header("ETag"));
  11490. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11491. // full content (200)
  11492. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11493. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11494. ASSERT_TRUE(res2);
  11495. EXPECT_EQ(200, res2->status);
  11496. EXPECT_EQ(content, res2->body);
  11497. svr.stop();
  11498. t.join();
  11499. std::remove(fname);
  11500. }
  11501. TEST(ETagTest, ExtremeLargeDateValues) {
  11502. using namespace httplib;
  11503. const char *fname = "ims_extreme_date.txt";
  11504. const char *content = "ims-extreme-date";
  11505. {
  11506. std::ofstream ofs(fname);
  11507. ofs << content;
  11508. ASSERT_TRUE(ofs.good());
  11509. }
  11510. Server svr;
  11511. svr.set_mount_point("/static", ".");
  11512. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11513. svr.wait_until_ready();
  11514. Client cli(HOST, PORT);
  11515. auto res1 = cli.Get(std::string("/static/") + fname);
  11516. ASSERT_TRUE(res1);
  11517. ASSERT_EQ(200, res1->status);
  11518. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11519. // Extremely large year that may overflow date parsing routines.
  11520. Headers h_large_date = {
  11521. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11522. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11523. ASSERT_TRUE(res_bad);
  11524. // Expect server to treat this as invalid/mismatch and return full content
  11525. EXPECT_EQ(200, res_bad->status);
  11526. // If-Range with extremely large date should be treated as mismatch -> full
  11527. // content (200)
  11528. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11529. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11530. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11531. ASSERT_TRUE(res_ifrange);
  11532. EXPECT_EQ(200, res_ifrange->status);
  11533. svr.stop();
  11534. t.join();
  11535. std::remove(fname);
  11536. }
  11537. TEST(ETagTest, NegativeFileModificationTime) {
  11538. using namespace httplib;
  11539. const char *fname = "ims_negative_mtime.txt";
  11540. const std::string content = "negative-mtime";
  11541. {
  11542. std::ofstream ofs(fname);
  11543. ofs << content;
  11544. ASSERT_TRUE(ofs.good());
  11545. }
  11546. // Try to set file mtime to a negative value. This may fail on some
  11547. // platforms/filesystems; if it fails, the test will still verify server
  11548. // behaves safely by performing a regular conditional request.
  11549. #if defined(__APPLE__) || defined(__linux__)
  11550. bool set_negative = false;
  11551. do {
  11552. struct timeval times[2];
  11553. // access time: now
  11554. times[0].tv_sec = time(nullptr);
  11555. times[0].tv_usec = 0;
  11556. // modification time: negative (e.g., -1)
  11557. times[1].tv_sec = -1;
  11558. times[1].tv_usec = 0;
  11559. if (utimes(fname, times) == 0) { set_negative = true; }
  11560. } while (0);
  11561. #else
  11562. bool set_negative = false;
  11563. #endif
  11564. Server svr;
  11565. svr.set_mount_point("/static", ".");
  11566. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11567. svr.wait_until_ready();
  11568. Client cli(HOST, PORT);
  11569. auto res1 = cli.Get(std::string("/static/") + fname);
  11570. ASSERT_TRUE(res1);
  11571. ASSERT_EQ(200, res1->status);
  11572. bool has_last_modified = res1->has_header("Last-Modified");
  11573. std::string last_modified;
  11574. if (has_last_modified) {
  11575. last_modified = res1->get_header_value("Last-Modified");
  11576. }
  11577. if (set_negative) {
  11578. // If we successfully set a negative mtime, ensure server returns a
  11579. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11580. // with an old date and ensure server handles it without crash.
  11581. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11582. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11583. ASSERT_TRUE(res2);
  11584. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11585. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11586. } else {
  11587. // Could not set negative mtime on this platform; fall back to verifying
  11588. // that normal invalid/malformed dates are treated safely (non-304).
  11589. Headers h_bad_date = {
  11590. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11591. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11592. ASSERT_TRUE(res_bad);
  11593. EXPECT_EQ(200, res_bad->status);
  11594. }
  11595. svr.stop();
  11596. t.join();
  11597. std::remove(fname);
  11598. }
  11599. //==============================================================================
  11600. // SSE Parsing Tests
  11601. //==============================================================================
  11602. class SSEParsingTest : public ::testing::Test {
  11603. protected:
  11604. // Test helper that mimics SSE parsing behavior
  11605. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11606. int &retry_ms) {
  11607. // Blank line signals end of event
  11608. if (line.empty() || line == "\r") { return true; }
  11609. // Lines starting with ':' are comments (ignored)
  11610. if (!line.empty() && line[0] == ':') { return false; }
  11611. // Find the colon separator
  11612. auto colon_pos = line.find(':');
  11613. if (colon_pos == std::string::npos) {
  11614. // Line with no colon is treated as field name with empty value
  11615. return false;
  11616. }
  11617. std::string field = line.substr(0, colon_pos);
  11618. std::string value;
  11619. // Value starts after colon, skip optional single space
  11620. if (colon_pos + 1 < line.size()) {
  11621. size_t value_start = colon_pos + 1;
  11622. if (line[value_start] == ' ') { value_start++; }
  11623. value = line.substr(value_start);
  11624. // Remove trailing \r if present
  11625. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11626. }
  11627. // Handle known fields
  11628. if (field == "event") {
  11629. msg.event = value;
  11630. } else if (field == "data") {
  11631. // Multiple data lines are concatenated with newlines
  11632. if (!msg.data.empty()) { msg.data += "\n"; }
  11633. msg.data += value;
  11634. } else if (field == "id") {
  11635. // Empty id is valid (clears the last event ID)
  11636. msg.id = value;
  11637. } else if (field == "retry") {
  11638. // Parse retry interval in milliseconds
  11639. try {
  11640. retry_ms = std::stoi(value);
  11641. } catch (...) {
  11642. // Invalid retry value, ignore
  11643. }
  11644. }
  11645. // Unknown fields are ignored per SSE spec
  11646. return false;
  11647. }
  11648. };
  11649. // Test: Single-line data
  11650. TEST_F(SSEParsingTest, SingleLineData) {
  11651. sse::SSEMessage msg;
  11652. int retry_ms = 3000;
  11653. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11654. EXPECT_EQ(msg.data, "hello");
  11655. EXPECT_EQ(msg.event, "message");
  11656. // Blank line ends event
  11657. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11658. }
  11659. // Test: Multi-line data
  11660. TEST_F(SSEParsingTest, MultiLineData) {
  11661. sse::SSEMessage msg;
  11662. int retry_ms = 3000;
  11663. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11664. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11665. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11666. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11667. }
  11668. // Test: Custom event types
  11669. TEST_F(SSEParsingTest, CustomEventType) {
  11670. sse::SSEMessage msg;
  11671. int retry_ms = 3000;
  11672. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11673. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11674. EXPECT_EQ(msg.event, "update");
  11675. EXPECT_EQ(msg.data, "payload");
  11676. }
  11677. // Test: Event ID handling
  11678. TEST_F(SSEParsingTest, EventIdHandling) {
  11679. sse::SSEMessage msg;
  11680. int retry_ms = 3000;
  11681. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11682. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11683. EXPECT_EQ(msg.id, "12345");
  11684. }
  11685. // Test: Empty event ID (clears last event ID)
  11686. TEST_F(SSEParsingTest, EmptyEventId) {
  11687. sse::SSEMessage msg;
  11688. msg.id = "previous";
  11689. int retry_ms = 3000;
  11690. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11691. EXPECT_EQ(msg.id, "");
  11692. }
  11693. // Test: Retry field parsing
  11694. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11695. sse::SSEMessage msg;
  11696. int retry_ms = 3000;
  11697. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11698. EXPECT_EQ(retry_ms, 5000);
  11699. }
  11700. // Test: Invalid retry value
  11701. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11702. sse::SSEMessage msg;
  11703. int retry_ms = 3000;
  11704. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11705. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11706. }
  11707. // Test: Comments (lines starting with :)
  11708. TEST_F(SSEParsingTest, CommentsIgnored) {
  11709. sse::SSEMessage msg;
  11710. int retry_ms = 3000;
  11711. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11712. EXPECT_EQ(msg.data, "");
  11713. EXPECT_EQ(msg.event, "message");
  11714. }
  11715. // Test: Colon in value
  11716. TEST_F(SSEParsingTest, ColonInValue) {
  11717. sse::SSEMessage msg;
  11718. int retry_ms = 3000;
  11719. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11720. EXPECT_EQ(msg.data, "hello:world:test");
  11721. }
  11722. // Test: Line with no colon (field name only)
  11723. TEST_F(SSEParsingTest, FieldNameOnly) {
  11724. sse::SSEMessage msg;
  11725. int retry_ms = 3000;
  11726. // According to SSE spec, this is treated as field name with empty value
  11727. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11728. // Since we don't recognize "data" without colon, data should be empty
  11729. EXPECT_EQ(msg.data, "");
  11730. }
  11731. // Test: Trailing \r handling
  11732. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11733. sse::SSEMessage msg;
  11734. int retry_ms = 3000;
  11735. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11736. EXPECT_EQ(msg.data, "hello");
  11737. }
  11738. // Test: Unknown fields ignored
  11739. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11740. sse::SSEMessage msg;
  11741. int retry_ms = 3000;
  11742. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11743. EXPECT_EQ(msg.data, "");
  11744. EXPECT_EQ(msg.event, "message");
  11745. }
  11746. // Test: Space after colon is optional
  11747. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11748. sse::SSEMessage msg1, msg2;
  11749. int retry_ms = 3000;
  11750. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11751. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11752. EXPECT_EQ(msg1.data, "hello");
  11753. EXPECT_EQ(msg2.data, "hello");
  11754. }
  11755. // Test: SSEMessage clear
  11756. TEST_F(SSEParsingTest, MessageClear) {
  11757. sse::SSEMessage msg;
  11758. msg.event = "custom";
  11759. msg.data = "some data";
  11760. msg.id = "123";
  11761. msg.clear();
  11762. EXPECT_EQ(msg.event, "message");
  11763. EXPECT_EQ(msg.data, "");
  11764. EXPECT_EQ(msg.id, "");
  11765. }
  11766. // Test: Complete event parsing
  11767. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11768. sse::SSEMessage msg;
  11769. int retry_ms = 3000;
  11770. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11771. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11772. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11773. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11774. // Blank line ends event
  11775. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11776. EXPECT_EQ(msg.event, "notification");
  11777. EXPECT_EQ(msg.id, "evt-42");
  11778. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11779. EXPECT_EQ(retry_ms, 1000);
  11780. }
  11781. //==============================================================================
  11782. // Integration Tests with Server
  11783. //==============================================================================
  11784. class SSEIntegrationTest : public ::testing::Test {
  11785. protected:
  11786. void SetUp() override {
  11787. stop_server_.store(false);
  11788. events_.clear();
  11789. server_ = httplib::detail::make_unique<Server>();
  11790. setup_server();
  11791. start_server();
  11792. }
  11793. void TearDown() override {
  11794. stop_server_.store(true);
  11795. event_cv_.notify_all();
  11796. server_->stop();
  11797. if (server_thread_.joinable()) { server_thread_.join(); }
  11798. }
  11799. void setup_server() {
  11800. // Simple SSE endpoint
  11801. server_->Get("/events", [this](const Request &req, Response &res) {
  11802. auto last_id = req.get_header_value("Last-Event-ID");
  11803. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11804. res.set_chunked_content_provider(
  11805. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11806. std::unique_lock<std::mutex> lock(event_mutex_);
  11807. if (event_cv_.wait_for(
  11808. lock, std::chrono::milliseconds(200), [this] {
  11809. return !events_.empty() || stop_server_.load();
  11810. })) {
  11811. if (stop_server_.load()) { return false; }
  11812. if (!events_.empty()) {
  11813. std::string event = events_.front();
  11814. events_.erase(events_.begin());
  11815. sink.write(event.data(), event.size());
  11816. return true;
  11817. }
  11818. }
  11819. return !stop_server_.load();
  11820. });
  11821. });
  11822. // Endpoint that returns error
  11823. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11824. res.status = 500;
  11825. res.set_content("Internal Server Error", "text/plain");
  11826. });
  11827. // Endpoint for custom event types
  11828. server_->Get("/custom-events", [](const Request &, Response &res) {
  11829. res.set_chunked_content_provider(
  11830. "text/event-stream", [](size_t offset, DataSink &sink) {
  11831. if (offset == 0) {
  11832. std::string event = "event: update\ndata: updated\n\n"
  11833. "event: delete\ndata: deleted\n\n";
  11834. sink.write(event.data(), event.size());
  11835. }
  11836. return false; // End stream after sending
  11837. });
  11838. });
  11839. }
  11840. void start_server() {
  11841. port_ = server_->bind_to_any_port(HOST);
  11842. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11843. // Wait for server to start
  11844. while (!server_->is_running()) {
  11845. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11846. }
  11847. }
  11848. int get_port() const { return port_; }
  11849. void send_event(const std::string &event) {
  11850. std::lock_guard<std::mutex> lock(event_mutex_);
  11851. events_.push_back(event);
  11852. event_cv_.notify_all();
  11853. }
  11854. std::unique_ptr<Server> server_;
  11855. std::thread server_thread_;
  11856. std::mutex event_mutex_;
  11857. std::condition_variable event_cv_;
  11858. std::vector<std::string> events_;
  11859. std::atomic<bool> stop_server_{false};
  11860. std::string last_received_event_id_;
  11861. int port_ = 0;
  11862. };
  11863. // Test: Successful connection and on_open callback
  11864. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11865. // Add a simple endpoint that sends one event and closes
  11866. server_->Get("/simple-event", [](const Request &, Response &res) {
  11867. res.set_chunked_content_provider(
  11868. "text/event-stream", [](size_t offset, DataSink &sink) {
  11869. if (offset == 0) {
  11870. std::string event = "data: hello\n\n";
  11871. sink.write(event.data(), event.size());
  11872. }
  11873. return false; // Close stream after sending
  11874. });
  11875. });
  11876. Client client("localhost", get_port());
  11877. sse::SSEClient sse(client, "/simple-event");
  11878. std::atomic<bool> open_called{false};
  11879. std::atomic<bool> message_received{false};
  11880. sse.on_open([&open_called]() { open_called.store(true); });
  11881. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11882. if (msg.data == "hello") { message_received.store(true); }
  11883. });
  11884. sse.set_reconnect_interval(100);
  11885. sse.set_max_reconnect_attempts(1);
  11886. // Start async
  11887. sse.start_async();
  11888. // Wait for message to be processed
  11889. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11890. sse.stop();
  11891. EXPECT_TRUE(open_called.load());
  11892. EXPECT_TRUE(message_received.load());
  11893. }
  11894. // Test: on_message callback
  11895. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11896. // Endpoint that sends multiple events then closes
  11897. server_->Get("/multi-event", [](const Request &, Response &res) {
  11898. res.set_chunked_content_provider(
  11899. "text/event-stream", [](size_t offset, DataSink &sink) {
  11900. if (offset == 0) {
  11901. std::string events = "data: message1\n\ndata: message2\n\n";
  11902. sink.write(events.data(), events.size());
  11903. }
  11904. return false;
  11905. });
  11906. });
  11907. Client client("localhost", get_port());
  11908. sse::SSEClient sse(client, "/multi-event");
  11909. std::vector<std::string> received_messages;
  11910. std::mutex messages_mutex;
  11911. sse.on_message([&](const sse::SSEMessage &msg) {
  11912. std::lock_guard<std::mutex> lock(messages_mutex);
  11913. received_messages.push_back(msg.data);
  11914. });
  11915. sse.set_reconnect_interval(100);
  11916. sse.set_max_reconnect_attempts(1);
  11917. sse.start_async();
  11918. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11919. sse.stop();
  11920. std::lock_guard<std::mutex> lock(messages_mutex);
  11921. EXPECT_GE(received_messages.size(), 2u);
  11922. if (received_messages.size() >= 2) {
  11923. EXPECT_EQ(received_messages[0], "message1");
  11924. EXPECT_EQ(received_messages[1], "message2");
  11925. }
  11926. }
  11927. // Test: on_event for specific types
  11928. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11929. Client client("localhost", get_port());
  11930. sse::SSEClient sse(client, "/custom-events");
  11931. std::atomic<bool> update_received{false};
  11932. std::atomic<bool> delete_received{false};
  11933. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11934. if (msg.data == "updated") { update_received.store(true); }
  11935. });
  11936. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11937. if (msg.data == "deleted") { delete_received.store(true); }
  11938. });
  11939. sse.set_max_reconnect_attempts(1);
  11940. sse.start_async();
  11941. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11942. sse.stop();
  11943. EXPECT_TRUE(update_received.load());
  11944. EXPECT_TRUE(delete_received.load());
  11945. }
  11946. // Test: on_error callback on connection failure
  11947. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11948. // Connect to a non-existent port
  11949. Client client("localhost", 59999);
  11950. sse::SSEClient sse(client, "/events");
  11951. std::atomic<bool> error_called{false};
  11952. Error received_error = Error::Success;
  11953. sse.on_error([&](Error err) {
  11954. error_called.store(true);
  11955. received_error = err;
  11956. });
  11957. sse.set_reconnect_interval(50);
  11958. sse.set_max_reconnect_attempts(1);
  11959. sse.start_async();
  11960. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11961. sse.stop();
  11962. EXPECT_TRUE(error_called.load());
  11963. EXPECT_NE(received_error, Error::Success);
  11964. }
  11965. // Test: Last-Event-ID header sent on reconnect
  11966. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11967. // Endpoint that sends event with ID
  11968. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11969. res.set_chunked_content_provider(
  11970. "text/event-stream", [](size_t offset, DataSink &sink) {
  11971. if (offset == 0) {
  11972. std::string event = "id: evt-123\ndata: test\n\n";
  11973. sink.write(event.data(), event.size());
  11974. }
  11975. return false;
  11976. });
  11977. });
  11978. Client client("localhost", get_port());
  11979. sse::SSEClient sse(client, "/event-with-id");
  11980. std::atomic<bool> id_received{false};
  11981. sse.on_message([&](const sse::SSEMessage &msg) {
  11982. if (!msg.id.empty()) { id_received.store(true); }
  11983. });
  11984. sse.set_reconnect_interval(100);
  11985. sse.set_max_reconnect_attempts(1);
  11986. sse.start_async();
  11987. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11988. sse.stop();
  11989. EXPECT_TRUE(id_received.load());
  11990. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11991. }
  11992. // Test: Manual stop
  11993. TEST_F(SSEIntegrationTest, ManualStop) {
  11994. // Endpoint that sends one event and stays open briefly
  11995. std::atomic<bool> handler_running{true};
  11996. server_->Get("/stay-open", [&handler_running](const Request &,
  11997. Response &res) {
  11998. res.set_chunked_content_provider(
  11999. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  12000. if (offset == 0) {
  12001. std::string event = "data: connected\n\n";
  12002. sink.write(event.data(), event.size());
  12003. }
  12004. // Keep connection open while handler_running is true
  12005. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  12006. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12007. }
  12008. return false;
  12009. });
  12010. });
  12011. Client client("localhost", get_port());
  12012. sse::SSEClient sse(client, "/stay-open");
  12013. std::atomic<bool> connected{false};
  12014. sse.on_open([&connected]() { connected.store(true); });
  12015. sse.set_reconnect_interval(100);
  12016. sse.set_max_reconnect_attempts(1);
  12017. sse.start_async();
  12018. // Wait for connection to establish
  12019. for (int i = 0; i < 20 && !connected.load(); ++i) {
  12020. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  12021. }
  12022. EXPECT_TRUE(connected.load());
  12023. EXPECT_TRUE(sse.is_connected());
  12024. // Signal handler to stop
  12025. handler_running.store(false);
  12026. // Stop SSE client
  12027. sse.stop();
  12028. EXPECT_FALSE(sse.is_connected());
  12029. }
  12030. // Test: SSEClient with custom headers
  12031. TEST_F(SSEIntegrationTest, CustomHeaders) {
  12032. // Setup a server endpoint that checks for custom header
  12033. std::atomic<bool> header_received{false};
  12034. server_->Get("/header-check", [&](const Request &req, Response &res) {
  12035. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  12036. header_received.store(true);
  12037. }
  12038. res.set_chunked_content_provider("text/event-stream",
  12039. [](size_t, DataSink &) { return false; });
  12040. });
  12041. Client client("localhost", get_port());
  12042. Headers headers = {{"X-Custom-Header", "custom-value"}};
  12043. sse::SSEClient sse(client, "/header-check", headers);
  12044. sse.set_max_reconnect_attempts(1);
  12045. sse.start_async();
  12046. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12047. sse.stop();
  12048. EXPECT_TRUE(header_received.load());
  12049. }
  12050. // Test: Reconnect interval configuration
  12051. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  12052. Client client("localhost", get_port());
  12053. sse::SSEClient sse(client, "/events");
  12054. auto &result = sse.set_reconnect_interval(500);
  12055. // Builder pattern should return reference to self
  12056. EXPECT_EQ(&result, &sse);
  12057. }
  12058. // Test: Max reconnect attempts
  12059. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  12060. // Connect to non-existent port to force reconnects
  12061. Client client("localhost", 59998);
  12062. sse::SSEClient sse(client, "/events");
  12063. std::atomic<int> error_count{0};
  12064. sse.on_error([&](Error) { error_count.fetch_add(1); });
  12065. sse.set_reconnect_interval(50);
  12066. sse.set_max_reconnect_attempts(2);
  12067. auto start = std::chrono::steady_clock::now();
  12068. sse.start(); // Blocking call
  12069. auto end = std::chrono::steady_clock::now();
  12070. // Should have stopped after 2 failed attempts
  12071. EXPECT_GE(error_count.load(), 2);
  12072. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  12073. auto duration =
  12074. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  12075. #ifdef _WIN32
  12076. // Windows is much slower for socket connection failures
  12077. EXPECT_LT(duration.count(), 7000);
  12078. #else
  12079. EXPECT_LT(duration.count(), 1000);
  12080. #endif
  12081. }
  12082. // Test: Multi-line data in integration
  12083. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  12084. // Endpoint with multi-line data
  12085. server_->Get("/multiline-data", [](const Request &, Response &res) {
  12086. res.set_chunked_content_provider(
  12087. "text/event-stream", [](size_t offset, DataSink &sink) {
  12088. if (offset == 0) {
  12089. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  12090. sink.write(event.data(), event.size());
  12091. }
  12092. return false;
  12093. });
  12094. });
  12095. Client client("localhost", get_port());
  12096. sse::SSEClient sse(client, "/multiline-data");
  12097. std::string received_data;
  12098. std::mutex data_mutex;
  12099. sse.on_message([&](const sse::SSEMessage &msg) {
  12100. std::lock_guard<std::mutex> lock(data_mutex);
  12101. received_data = msg.data;
  12102. });
  12103. sse.set_reconnect_interval(100);
  12104. sse.set_max_reconnect_attempts(1);
  12105. sse.start_async();
  12106. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12107. sse.stop();
  12108. std::lock_guard<std::mutex> lock(data_mutex);
  12109. EXPECT_EQ(received_data, "line1\nline2\nline3");
  12110. }
  12111. // Test: Auto-reconnect after server disconnection
  12112. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  12113. std::atomic<int> connection_count{0};
  12114. std::atomic<int> message_count{0};
  12115. // Endpoint that sends one event and closes, forcing reconnect
  12116. server_->Get("/reconnect-test",
  12117. [&connection_count](const Request &, Response &res) {
  12118. connection_count.fetch_add(1);
  12119. res.set_chunked_content_provider(
  12120. "text/event-stream", [](size_t offset, DataSink &sink) {
  12121. if (offset == 0) {
  12122. std::string event = "data: hello\n\n";
  12123. sink.write(event.data(), event.size());
  12124. }
  12125. return false; // Close connection after sending
  12126. });
  12127. });
  12128. Client client("localhost", get_port());
  12129. sse::SSEClient sse(client, "/reconnect-test");
  12130. sse.on_message([&message_count](const sse::SSEMessage &) {
  12131. message_count.fetch_add(1);
  12132. });
  12133. sse.set_reconnect_interval(100);
  12134. sse.set_max_reconnect_attempts(3);
  12135. sse.start_async();
  12136. // Wait long enough for multiple reconnects
  12137. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  12138. sse.stop();
  12139. // Should have connected multiple times (initial + reconnects)
  12140. EXPECT_GE(connection_count.load(), 2);
  12141. // Should have received messages from multiple connections
  12142. EXPECT_GE(message_count.load(), 2);
  12143. }
  12144. // Test: Last-Event-ID sent on reconnect
  12145. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  12146. std::atomic<int> connection_count{0};
  12147. std::vector<std::string> received_last_event_ids;
  12148. std::mutex id_mutex;
  12149. // Endpoint that checks Last-Event-ID header and sends event with ID
  12150. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  12151. int conn = connection_count.fetch_add(1);
  12152. // Capture the Last-Event-ID header from each connection
  12153. {
  12154. std::lock_guard<std::mutex> lock(id_mutex);
  12155. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  12156. }
  12157. res.set_chunked_content_provider(
  12158. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  12159. if (offset == 0) {
  12160. std::string event =
  12161. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  12162. sink.write(event.data(), event.size());
  12163. }
  12164. return false;
  12165. });
  12166. });
  12167. Client client("localhost", get_port());
  12168. sse::SSEClient sse(client, "/reconnect-with-id");
  12169. sse.set_reconnect_interval(100);
  12170. sse.set_max_reconnect_attempts(3);
  12171. sse.start_async();
  12172. // Wait for at least 2 connections
  12173. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12174. sse.stop();
  12175. // Verify behavior
  12176. std::lock_guard<std::mutex> lock(id_mutex);
  12177. EXPECT_GE(received_last_event_ids.size(), 2u);
  12178. // First connection should have no Last-Event-ID
  12179. if (!received_last_event_ids.empty()) {
  12180. EXPECT_EQ(received_last_event_ids[0], "");
  12181. }
  12182. // Second connection should have Last-Event-ID from first connection
  12183. if (received_last_event_ids.size() >= 2) {
  12184. EXPECT_EQ(received_last_event_ids[1], "event-0");
  12185. }
  12186. }
  12187. TEST(Issue2318Test, EmptyHostString) {
  12188. {
  12189. httplib::Client cli_empty("", PORT);
  12190. auto res = cli_empty.Get("/");
  12191. ASSERT_FALSE(res);
  12192. EXPECT_EQ(httplib::Error::Connection, res.error());
  12193. }
  12194. {
  12195. httplib::Client cli(" ", PORT);
  12196. auto res = cli.Get("/");
  12197. ASSERT_FALSE(res);
  12198. EXPECT_EQ(httplib::Error::Connection, res.error());
  12199. }
  12200. }
  12201. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12202. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  12203. Server svr;
  12204. // Set a small payload limit (1KB)
  12205. svr.set_payload_max_length(1024);
  12206. svr.Post("/test", [&](const Request &req, Response &res) {
  12207. res.set_content("Body size: " + std::to_string(req.body.size()),
  12208. "text/plain");
  12209. });
  12210. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. listen_thread.join();
  12214. });
  12215. svr.wait_until_ready();
  12216. // Create data that compresses well but exceeds limit when decompressed
  12217. // 8KB of repeated null bytes compresses to a very small size
  12218. std::string original_data(8 * 1024, '\0');
  12219. // Compress the data using gzip
  12220. std::string compressed_data;
  12221. detail::gzip_compressor compressor;
  12222. compressor.compress(original_data.data(), original_data.size(), true,
  12223. [&](const char *data, size_t size) {
  12224. compressed_data.append(data, size);
  12225. return true;
  12226. });
  12227. // Verify compression worked (compressed should be much smaller)
  12228. ASSERT_LT(compressed_data.size(), original_data.size());
  12229. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  12230. // Send compressed data with Content-Encoding: gzip
  12231. Client cli(HOST, PORT);
  12232. Headers headers = {{"Content-Encoding", "gzip"}};
  12233. auto res =
  12234. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  12235. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  12236. ASSERT_TRUE(res);
  12237. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  12238. }
  12239. #endif