test.cc 430 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995
  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. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. auto port = 1234;
  74. Server svr;
  75. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  76. res.set_content("Benchmark Response", "text/plain");
  77. });
  78. auto listen_thread = std::thread([&]() { svr.listen(host, port); });
  79. auto se = detail::scope_exit([&] {
  80. svr.stop();
  81. listen_thread.join();
  82. ASSERT_FALSE(svr.is_running());
  83. });
  84. svr.wait_until_ready();
  85. Client cli(host, port);
  86. // Warm-up request to establish connection and resolve DNS
  87. auto warmup_res = cli.Get("/benchmark");
  88. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  89. // Run multiple trials and collect timings
  90. const int num_trials = 20;
  91. std::vector<int64_t> timings;
  92. timings.reserve(num_trials);
  93. for (int i = 0; i < num_trials; i++) {
  94. auto start = std::chrono::high_resolution_clock::now();
  95. auto res = cli.Get("/benchmark");
  96. auto end = std::chrono::high_resolution_clock::now();
  97. auto elapsed =
  98. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  99. .count();
  100. // Assertions after timing measurement to avoid overhead
  101. ASSERT_TRUE(res);
  102. EXPECT_EQ(StatusCode::OK_200, res->status);
  103. timings.push_back(elapsed);
  104. }
  105. // Calculate 25th percentile (lower quartile)
  106. std::sort(timings.begin(), timings.end());
  107. auto p25 = timings[num_trials / 4];
  108. // Format timings for output
  109. std::ostringstream timings_str;
  110. timings_str << "[";
  111. for (size_t i = 0; i < timings.size(); i++) {
  112. if (i > 0) timings_str << ", ";
  113. timings_str << timings[i];
  114. }
  115. timings_str << "]";
  116. // Localhost HTTP GET should be fast even in CI environments
  117. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  118. << "ms (Issue #1777). Timings: " << timings_str.str();
  119. }
  120. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  121. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. const std::string pathname_{"./httplib-server.sock"};
  136. const std::string pattern_{"/hi"};
  137. const std::string content_{"Hello World!"};
  138. };
  139. TEST_F(UnixSocketTest, pathname) {
  140. httplib::Server svr;
  141. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  142. res.set_content(content_, "text/plain");
  143. });
  144. std::thread t{[&] {
  145. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  146. }};
  147. auto se = detail::scope_exit([&] {
  148. svr.stop();
  149. t.join();
  150. ASSERT_FALSE(svr.is_running());
  151. });
  152. svr.wait_until_ready();
  153. ASSERT_TRUE(svr.is_running());
  154. client_GET(pathname_);
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.wait_writable());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(PORT + 1);
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  263. ASSERT_EQ(0, listen(s, 1));
  264. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  265. ASSERT_EQ(0, close(s));
  266. }};
  267. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  268. std::thread cli{[&] {
  269. const int s = socket(AF_INET, SOCK_STREAM, 0);
  270. ASSERT_LE(0, s);
  271. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. cli.join();
  275. svr.join();
  276. ASSERT_NE(disconnected_svr_sock, -1);
  277. const auto asSocketStream = [&](socket_t fd,
  278. std::function<bool(Stream &)> func) {
  279. return detail::process_client_socket(
  280. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  281. };
  282. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  283. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  284. EXPECT_FALSE(ss.wait_writable());
  285. return true;
  286. });
  287. ASSERT_EQ(0, close(disconnected_svr_sock));
  288. }
  289. #endif // #ifndef _WIN32
  290. TEST(ClientTest, MoveConstructible) {
  291. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  292. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  293. }
  294. TEST(ClientTest, MoveAssignable) {
  295. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  296. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  297. }
  298. #ifdef _WIN32
  299. TEST(StartupTest, WSAStartup) {
  300. WSADATA wsaData;
  301. int ret = WSAStartup(0x0002, &wsaData);
  302. ASSERT_EQ(0, ret);
  303. }
  304. #endif
  305. TEST(DecodePathTest, PercentCharacter) {
  306. EXPECT_EQ(
  307. decode_path_component(
  308. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  309. u8"descrip=Gastos áéíóúñÑ 6");
  310. }
  311. TEST(DecodePathTest, PercentCharacterNUL) {
  312. string expected;
  313. expected.push_back('x');
  314. expected.push_back('\0');
  315. expected.push_back('x');
  316. EXPECT_EQ(decode_path_component("x%00x"), expected);
  317. }
  318. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  319. string unescapedCharacters = "-_.!~*'()";
  320. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  321. }
  322. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  323. string reservedCharacters = ";,/?:@&=+$";
  324. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  325. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  326. }
  327. TEST(ClientQueryOrder, PreserveOrder) {
  328. // This test reproduces Issue #2259: client may reorder query parameters
  329. // when sending a GET request. The expected behavior is that the client
  330. // preserves the original query string order when the caller supplied it
  331. // as part of the path.
  332. Server svr;
  333. svr.Get("/", [&](const Request &req, Response &res) {
  334. // Echo back the raw target so the test can assert ordering
  335. res.set_content(req.target, "text/plain");
  336. });
  337. std::thread t{[&] { svr.listen(HOST, PORT); }};
  338. auto se = detail::scope_exit([&] {
  339. svr.stop();
  340. t.join();
  341. ASSERT_FALSE(svr.is_running());
  342. });
  343. svr.wait_until_ready();
  344. Client cli(HOST, PORT);
  345. ASSERT_TRUE(cli.is_valid());
  346. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  347. auto res = cli.Get(original);
  348. ASSERT_TRUE(res);
  349. // Expect the echoed target to exactly match the original path (order
  350. // preserved)
  351. EXPECT_EQ(res->body, original);
  352. }
  353. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  354. string chineseCharacters = u8"中国語";
  355. string russianCharacters = u8"дом";
  356. string brazilianCharacters = u8"óculos";
  357. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  358. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  359. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  360. "%D0%B4%D0%BE%D0%BC");
  361. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  362. }
  363. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  364. string unescapedCharacters = "-_.!~*'()";
  365. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  366. }
  367. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  368. string reservedCharacters = ";,/?:@&=+$";
  369. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  370. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  371. }
  372. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  373. string chineseCharacters = u8"中国語";
  374. string russianCharacters = u8"дом";
  375. string brazilianCharacters = u8"óculos";
  376. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  377. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  378. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  379. "%D0%B4%D0%BE%D0%BC");
  380. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  381. }
  382. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  383. // Issue #2082 use case: encoding path component with ampersand
  384. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  385. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  386. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  387. }
  388. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  389. string unescapedCharacters = "-_.!~*'()";
  390. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  391. }
  392. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  393. string reservedCharacters = ";,/?:@&=+$#";
  394. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  395. }
  396. TEST(EncodeUriTest, TestUTF8Characters) {
  397. string chineseCharacters = u8"中国語";
  398. string russianCharacters = u8"дом";
  399. string brazilianCharacters = u8"óculos";
  400. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  401. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  402. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  403. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  404. }
  405. TEST(EncodeUriTest, TestCompleteUri) {
  406. string uri =
  407. "https://example.com/path/to/resource?query=value&param=test#fragment";
  408. EXPECT_EQ(
  409. httplib::encode_uri(uri),
  410. "https://example.com/path/to/resource?query=value&param=test#fragment");
  411. }
  412. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  413. string uri =
  414. "https://example.com/path with spaces/file name.html?q=hello world";
  415. EXPECT_EQ(httplib::encode_uri(uri),
  416. "https://example.com/path%20with%20spaces/"
  417. "file%20name.html?q=hello%20world");
  418. }
  419. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  420. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  421. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  422. }
  423. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  424. string unescapedCharacters = "-_.!~*'()";
  425. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  426. }
  427. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  428. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  429. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  430. string encodedBrazilian = "%C3%B3culos";
  431. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  433. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  434. }
  435. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  436. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  437. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  438. "Piri Tommy Villiers - on & on");
  439. }
  440. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  441. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  442. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  443. }
  444. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  445. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  446. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  447. }
  448. TEST(DecodeUriTest, TestUTF8Characters) {
  449. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  450. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  451. string encodedBrazilian = "%C3%B3culos";
  452. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  453. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  454. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  455. }
  456. TEST(DecodeUriTest, TestCompleteUri) {
  457. string encodedUri = "https://example.com/path%20with%20spaces/"
  458. "file%20name.html?q=hello%20world";
  459. EXPECT_EQ(
  460. httplib::decode_uri(encodedUri),
  461. "https://example.com/path with spaces/file name.html?q=hello world");
  462. }
  463. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  464. string original =
  465. "https://example.com/path with spaces/file name.html?q=hello world";
  466. string encoded = httplib::encode_uri(original);
  467. string decoded = httplib::decode_uri(encoded);
  468. EXPECT_EQ(decoded, original);
  469. }
  470. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  471. string original = "Piri Tommy Villiers - on & on";
  472. string encoded = httplib::encode_uri_component(original);
  473. string decoded = httplib::decode_uri_component(encoded);
  474. EXPECT_EQ(decoded, original);
  475. }
  476. TEST(TrimTests, TrimStringTests) {
  477. EXPECT_EQ("abc", detail::trim_copy("abc"));
  478. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  479. EXPECT_TRUE(detail::trim_copy("").empty());
  480. }
  481. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  482. // Simple case without quality values
  483. std::vector<std::string> result1;
  484. EXPECT_TRUE(detail::parse_accept_header(
  485. "text/html,application/json,text/plain", result1));
  486. EXPECT_EQ(result1.size(), 3U);
  487. EXPECT_EQ(result1[0], "text/html");
  488. EXPECT_EQ(result1[1], "application/json");
  489. EXPECT_EQ(result1[2], "text/plain");
  490. // With quality values
  491. std::vector<std::string> result2;
  492. EXPECT_TRUE(detail::parse_accept_header(
  493. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  494. EXPECT_EQ(result2.size(), 3U);
  495. EXPECT_EQ(result2[0], "application/json"); // highest q value
  496. EXPECT_EQ(result2[1], "text/html");
  497. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  498. }
  499. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  500. // Mixed with and without quality values
  501. std::vector<std::string> result;
  502. EXPECT_TRUE(detail::parse_accept_header(
  503. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  504. EXPECT_EQ(result.size(), 3U);
  505. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  506. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  507. EXPECT_EQ(result[2], "application/json"); // q=0.5
  508. }
  509. TEST(ParseAcceptHeaderTest, EdgeCases) {
  510. // Empty header
  511. std::vector<std::string> empty_result;
  512. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  513. EXPECT_TRUE(empty_result.empty());
  514. // Single type
  515. std::vector<std::string> single_result;
  516. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  517. EXPECT_EQ(single_result.size(), 1U);
  518. EXPECT_EQ(single_result[0], "application/json");
  519. // Wildcard types
  520. std::vector<std::string> wildcard_result;
  521. EXPECT_TRUE(detail::parse_accept_header(
  522. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  523. EXPECT_EQ(wildcard_result.size(), 3U);
  524. EXPECT_EQ(wildcard_result[0], "application/json");
  525. EXPECT_EQ(wildcard_result[1], "text/*");
  526. EXPECT_EQ(wildcard_result[2], "*/*");
  527. }
  528. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  529. // Common browser Accept header
  530. std::vector<std::string> browser_result;
  531. EXPECT_TRUE(
  532. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  533. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  534. browser_result));
  535. EXPECT_EQ(browser_result.size(), 6U);
  536. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  540. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  541. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  542. // API client header
  543. std::vector<std::string> api_result;
  544. EXPECT_TRUE(detail::parse_accept_header(
  545. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  546. api_result));
  547. EXPECT_EQ(api_result.size(), 3U);
  548. EXPECT_EQ(api_result[0], "application/json");
  549. EXPECT_EQ(api_result[1], "application/xml");
  550. EXPECT_EQ(api_result[2], "text/plain");
  551. }
  552. TEST(ParseAcceptHeaderTest, SpecialCases) {
  553. // Quality value with 3 decimal places
  554. std::vector<std::string> decimal_result;
  555. EXPECT_TRUE(detail::parse_accept_header(
  556. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  557. EXPECT_EQ(decimal_result.size(), 2U);
  558. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  559. EXPECT_EQ(decimal_result[1], "text/html");
  560. // Zero quality (should still be included but with lowest priority)
  561. std::vector<std::string> zero_q_result;
  562. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  563. zero_q_result));
  564. EXPECT_EQ(zero_q_result.size(), 2U);
  565. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  566. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  567. // No spaces around commas
  568. std::vector<std::string> no_space_result;
  569. EXPECT_TRUE(detail::parse_accept_header(
  570. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  571. no_space_result));
  572. EXPECT_EQ(no_space_result.size(), 3U);
  573. EXPECT_EQ(no_space_result[0], "text/html");
  574. EXPECT_EQ(no_space_result[1], "application/json");
  575. EXPECT_EQ(no_space_result[2], "text/plain");
  576. }
  577. TEST(ParseAcceptHeaderTest, InvalidCases) {
  578. std::vector<std::string> result;
  579. // Invalid quality value (> 1.0)
  580. EXPECT_FALSE(
  581. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  582. // Invalid quality value (< 0.0)
  583. EXPECT_FALSE(
  584. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  585. // Invalid quality value (not a number)
  586. EXPECT_FALSE(detail::parse_accept_header(
  587. "text/html;q=invalid,application/json", result));
  588. // Empty quality value
  589. EXPECT_FALSE(
  590. detail::parse_accept_header("text/html;q=,application/json", result));
  591. // Invalid media type format (no slash and not wildcard)
  592. EXPECT_FALSE(
  593. detail::parse_accept_header("invalidtype,application/json", result));
  594. // Empty media type
  595. result.clear();
  596. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  597. // Only commas
  598. result.clear();
  599. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  600. // Valid cases should still work
  601. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  602. EXPECT_EQ(result.size(), 1U);
  603. EXPECT_EQ(result[0], "*/*");
  604. EXPECT_TRUE(detail::parse_accept_header("*", result));
  605. EXPECT_EQ(result.size(), 1U);
  606. EXPECT_EQ(result[0], "*");
  607. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  608. EXPECT_EQ(result.size(), 1U);
  609. EXPECT_EQ(result[0], "text/*");
  610. }
  611. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  612. Server svr;
  613. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  614. EXPECT_EQ(req.accept_content_types.size(), 3U);
  615. EXPECT_EQ(req.accept_content_types[0], "application/json");
  616. EXPECT_EQ(req.accept_content_types[1], "text/html");
  617. EXPECT_EQ(req.accept_content_types[2], "*/*");
  618. res.set_content("ok", "text/plain");
  619. });
  620. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  621. EXPECT_TRUE(false);
  622. res.set_content("bad request", "text/plain");
  623. });
  624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  625. auto se = detail::scope_exit([&] {
  626. svr.stop();
  627. listen_thread.join();
  628. ASSERT_FALSE(svr.is_running());
  629. });
  630. svr.wait_until_ready();
  631. Client cli("localhost", PORT);
  632. {
  633. auto res =
  634. cli.Get("/accept_ok",
  635. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  636. ASSERT_TRUE(res);
  637. EXPECT_EQ(StatusCode::OK_200, res->status);
  638. }
  639. {
  640. auto res = cli.Get("/accept_bad_request",
  641. {{"Accept", "text/html;q=abc,application/json"}});
  642. ASSERT_TRUE(res);
  643. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  644. }
  645. }
  646. TEST(DivideTest, DivideStringTests) {
  647. auto divide = [](const std::string &str, char d) {
  648. std::string lhs;
  649. std::string rhs;
  650. detail::divide(str, d,
  651. [&](const char *lhs_data, std::size_t lhs_size,
  652. const char *rhs_data, std::size_t rhs_size) {
  653. lhs.assign(lhs_data, lhs_size);
  654. rhs.assign(rhs_data, rhs_size);
  655. });
  656. return std::make_pair(std::move(lhs), std::move(rhs));
  657. };
  658. {
  659. const auto res = divide("", '=');
  660. EXPECT_EQ(res.first, "");
  661. EXPECT_EQ(res.second, "");
  662. }
  663. {
  664. const auto res = divide("=", '=');
  665. EXPECT_EQ(res.first, "");
  666. EXPECT_EQ(res.second, "");
  667. }
  668. {
  669. const auto res = divide(" ", '=');
  670. EXPECT_EQ(res.first, " ");
  671. EXPECT_EQ(res.second, "");
  672. }
  673. {
  674. const auto res = divide("a", '=');
  675. EXPECT_EQ(res.first, "a");
  676. EXPECT_EQ(res.second, "");
  677. }
  678. {
  679. const auto res = divide("a=", '=');
  680. EXPECT_EQ(res.first, "a");
  681. EXPECT_EQ(res.second, "");
  682. }
  683. {
  684. const auto res = divide("=b", '=');
  685. EXPECT_EQ(res.first, "");
  686. EXPECT_EQ(res.second, "b");
  687. }
  688. {
  689. const auto res = divide("a=b", '=');
  690. EXPECT_EQ(res.first, "a");
  691. EXPECT_EQ(res.second, "b");
  692. }
  693. {
  694. const auto res = divide("a=b=", '=');
  695. EXPECT_EQ(res.first, "a");
  696. EXPECT_EQ(res.second, "b=");
  697. }
  698. {
  699. const auto res = divide("a=b=c", '=');
  700. EXPECT_EQ(res.first, "a");
  701. EXPECT_EQ(res.second, "b=c");
  702. }
  703. }
  704. TEST(SplitTest, ParseQueryString) {
  705. string s = "key1=val1&key2=val2&key3=val3";
  706. Params dic;
  707. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  708. [&](const char *b, const char *e) {
  709. string key, val;
  710. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  711. if (key.empty()) {
  712. key.assign(b2, e2);
  713. } else {
  714. val.assign(b2, e2);
  715. }
  716. });
  717. dic.emplace(key, val);
  718. });
  719. EXPECT_EQ("val1", dic.find("key1")->second);
  720. EXPECT_EQ("val2", dic.find("key2")->second);
  721. EXPECT_EQ("val3", dic.find("key3")->second);
  722. }
  723. TEST(SplitTest, ParseInvalidQueryTests) {
  724. {
  725. string s = " ";
  726. Params dict;
  727. detail::parse_query_text(s, dict);
  728. EXPECT_TRUE(dict.empty());
  729. }
  730. {
  731. string s = " = =";
  732. Params dict;
  733. detail::parse_query_text(s, dict);
  734. EXPECT_TRUE(dict.empty());
  735. }
  736. }
  737. TEST(ParseQueryTest, ParseQueryString) {
  738. {
  739. std::string s = "key1=val1&key2=val2&key3=val3";
  740. Params dic;
  741. detail::parse_query_text(s, dic);
  742. EXPECT_EQ("val1", dic.find("key1")->second);
  743. EXPECT_EQ("val2", dic.find("key2")->second);
  744. EXPECT_EQ("val3", dic.find("key3")->second);
  745. }
  746. {
  747. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  748. Params dic;
  749. detail::parse_query_text(s, dic);
  750. EXPECT_EQ("", dic.find("key1")->second);
  751. EXPECT_EQ("val1", dic.find("key2")->second);
  752. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  753. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  754. }
  755. }
  756. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  757. Params dic;
  758. EXPECT_EQ(detail::params_to_query_str(dic), "");
  759. dic.emplace("key1", "val1");
  760. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  761. dic.emplace("key2", "val2");
  762. dic.emplace("key3", "val3");
  763. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  764. }
  765. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  766. string content_type = "multipart/form-data; boundary=something";
  767. string boundary;
  768. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  769. EXPECT_TRUE(ret);
  770. EXPECT_EQ(boundary, "something");
  771. }
  772. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  773. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  780. string content_type =
  781. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  782. string boundary;
  783. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  784. EXPECT_TRUE(ret);
  785. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  786. }
  787. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  788. string content_type =
  789. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  790. string boundary;
  791. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  792. EXPECT_TRUE(ret);
  793. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  794. }
  795. TEST(GetHeaderValueTest, DefaultValue) {
  796. Headers headers = {{"Dummy", "Dummy"}};
  797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  798. EXPECT_STREQ("text/plain", val);
  799. }
  800. TEST(GetHeaderValueTest, DefaultValueInt) {
  801. Headers headers = {{"Dummy", "Dummy"}};
  802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  803. EXPECT_EQ(100ull, val);
  804. }
  805. TEST(GetHeaderValueTest, RegularValue) {
  806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  808. EXPECT_STREQ("text/html", val);
  809. }
  810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  813. EXPECT_STREQ("text/html", val);
  814. }
  815. TEST(GetHeaderValueTest, SetContent) {
  816. Response res;
  817. res.set_content("html", "text/html");
  818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  819. res.set_content("text", "text/plain");
  820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  822. }
  823. TEST(GetHeaderValueTest, RegularValueInt) {
  824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  826. EXPECT_EQ(100ull, val);
  827. }
  828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  829. Headers headers = {{"Content-Length", "x"}};
  830. auto is_invalid_value = false;
  831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  832. is_invalid_value);
  833. EXPECT_EQ(0ull, val);
  834. EXPECT_TRUE(is_invalid_value);
  835. }
  836. TEST(GetHeaderValueTest, Range) {
  837. {
  838. Headers headers = {make_range_header({{1, -1}})};
  839. auto val = detail::get_header_value(headers, "Range", 0, 0);
  840. EXPECT_STREQ("bytes=1-", val);
  841. }
  842. {
  843. Headers headers = {make_range_header({{-1, 1}})};
  844. auto val = detail::get_header_value(headers, "Range", 0, 0);
  845. EXPECT_STREQ("bytes=-1", val);
  846. }
  847. {
  848. Headers headers = {make_range_header({{1, 10}})};
  849. auto val = detail::get_header_value(headers, "Range", 0, 0);
  850. EXPECT_STREQ("bytes=1-10", val);
  851. }
  852. {
  853. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  854. auto val = detail::get_header_value(headers, "Range", 0, 0);
  855. EXPECT_STREQ("bytes=1-10, 100-", val);
  856. }
  857. {
  858. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  859. auto val = detail::get_header_value(headers, "Range", 0, 0);
  860. EXPECT_STREQ("bytes=1-10, 100-200", val);
  861. }
  862. {
  863. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  864. auto val = detail::get_header_value(headers, "Range", 0, 0);
  865. EXPECT_STREQ("bytes=0-0, -1", val);
  866. }
  867. }
  868. TEST(ParseHeaderValueTest, Range) {
  869. {
  870. Ranges ranges;
  871. auto ret = detail::parse_range_header("bytes=1-", ranges);
  872. EXPECT_TRUE(ret);
  873. EXPECT_EQ(1u, ranges.size());
  874. EXPECT_EQ(1u, ranges[0].first);
  875. EXPECT_EQ(-1, ranges[0].second);
  876. }
  877. {
  878. Ranges ranges;
  879. auto ret = detail::parse_range_header("bytes=-1", ranges);
  880. EXPECT_TRUE(ret);
  881. EXPECT_EQ(1u, ranges.size());
  882. EXPECT_EQ(-1, ranges[0].first);
  883. EXPECT_EQ(1u, ranges[0].second);
  884. }
  885. {
  886. Ranges ranges;
  887. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  888. EXPECT_TRUE(ret);
  889. EXPECT_EQ(1u, ranges.size());
  890. EXPECT_EQ(1u, ranges[0].first);
  891. EXPECT_EQ(10u, ranges[0].second);
  892. }
  893. {
  894. Ranges ranges;
  895. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  896. EXPECT_FALSE(ret);
  897. }
  898. {
  899. Ranges ranges;
  900. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  901. EXPECT_TRUE(ret);
  902. EXPECT_EQ(2u, ranges.size());
  903. EXPECT_EQ(1u, ranges[0].first);
  904. EXPECT_EQ(10u, ranges[0].second);
  905. EXPECT_EQ(100u, ranges[1].first);
  906. EXPECT_EQ(-1, ranges[1].second);
  907. }
  908. {
  909. Ranges ranges;
  910. auto ret =
  911. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  912. EXPECT_TRUE(ret);
  913. EXPECT_EQ(3u, ranges.size());
  914. EXPECT_EQ(1u, ranges[0].first);
  915. EXPECT_EQ(10u, ranges[0].second);
  916. EXPECT_EQ(100u, ranges[1].first);
  917. EXPECT_EQ(200u, ranges[1].second);
  918. EXPECT_EQ(300u, ranges[2].first);
  919. EXPECT_EQ(400u, ranges[2].second);
  920. }
  921. {
  922. Ranges ranges;
  923. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  926. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  927. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  928. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  929. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  936. EXPECT_TRUE(ranges.empty());
  937. }
  938. }
  939. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  940. Request req;
  941. req.set_header("Accept-Encoding", "gzip");
  942. Response res;
  943. res.set_header("Content-Type", "text/plain");
  944. auto ret = detail::encoding_type(req, res);
  945. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  946. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  947. #else
  948. EXPECT_TRUE(ret == detail::EncodingType::None);
  949. #endif
  950. }
  951. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  952. Request req;
  953. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  954. Response res;
  955. res.set_header("Content-Type", "text/plain");
  956. auto ret = detail::encoding_type(req, res);
  957. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  958. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  959. #elif CPPHTTPLIB_ZLIB_SUPPORT
  960. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  961. #elif CPPHTTPLIB_ZSTD_SUPPORT
  962. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  963. #else
  964. EXPECT_TRUE(ret == detail::EncodingType::None);
  965. #endif
  966. }
  967. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  968. Request req;
  969. req.set_header("Accept-Encoding",
  970. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  971. Response res;
  972. res.set_header("Content-Type", "text/plain");
  973. auto ret = detail::encoding_type(req, res);
  974. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  975. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  976. #elif CPPHTTPLIB_ZLIB_SUPPORT
  977. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  978. #elif CPPHTTPLIB_ZSTD_SUPPORT
  979. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  980. #else
  981. EXPECT_TRUE(ret == detail::EncodingType::None);
  982. #endif
  983. }
  984. TEST(BufferStreamTest, read) {
  985. detail::BufferStream strm1;
  986. Stream &strm = strm1;
  987. EXPECT_EQ(5, strm.write("hello"));
  988. char buf[512];
  989. EXPECT_EQ(2, strm.read(buf, 2));
  990. EXPECT_EQ('h', buf[0]);
  991. EXPECT_EQ('e', buf[1]);
  992. EXPECT_EQ(2, strm.read(buf, 2));
  993. EXPECT_EQ('l', buf[0]);
  994. EXPECT_EQ('l', buf[1]);
  995. EXPECT_EQ(1, strm.read(buf, 1));
  996. EXPECT_EQ('o', buf[0]);
  997. EXPECT_EQ(0, strm.read(buf, 1));
  998. }
  999. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1000. auto host = "www.httpwatch.com";
  1001. auto ip = hosted_at(host);
  1002. EXPECT_EQ("23.96.13.243", ip);
  1003. std::vector<std::string> addrs;
  1004. hosted_at(host, addrs);
  1005. EXPECT_EQ(1u, addrs.size());
  1006. }
  1007. #if 0 // It depends on each test environment...
  1008. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1009. auto host = "www.youtube.com";
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(20u, addrs.size());
  1013. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1014. EXPECT_TRUE(it != addrs.end());
  1015. }
  1016. #endif
  1017. class ChunkedEncodingTest : public ::testing::Test {
  1018. protected:
  1019. ChunkedEncodingTest()
  1020. : cli_(HOST, PORT)
  1021. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1022. ,
  1023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1024. #endif
  1025. {
  1026. cli_.set_connection_timeout(2);
  1027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1028. cli_.enable_server_certificate_verification(false);
  1029. #endif
  1030. }
  1031. virtual void SetUp() {
  1032. read_file("./image.jpg", image_data_);
  1033. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1034. res.set_content("Hello World!", "text/plain");
  1035. });
  1036. svr_.Get(
  1037. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1038. res.set_chunked_content_provider(
  1039. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1040. size_t remaining = image_data_.size() - offset;
  1041. if (remaining == 0) {
  1042. sink.done();
  1043. } else {
  1044. constexpr size_t CHUNK_SIZE = 1024;
  1045. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1046. sink.write(&image_data_[offset], send_size);
  1047. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1048. }
  1049. return true;
  1050. });
  1051. });
  1052. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1053. svr_.wait_until_ready();
  1054. }
  1055. virtual void TearDown() {
  1056. svr_.stop();
  1057. if (!request_threads_.empty()) {
  1058. std::this_thread::sleep_for(std::chrono::seconds(1));
  1059. for (auto &t : request_threads_) {
  1060. t.join();
  1061. }
  1062. }
  1063. t_.join();
  1064. }
  1065. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1066. SSLClient cli_;
  1067. SSLServer svr_;
  1068. #else
  1069. Client cli_;
  1070. Server svr_;
  1071. #endif
  1072. thread t_;
  1073. std::vector<thread> request_threads_;
  1074. std::string image_data_;
  1075. };
  1076. TEST_F(ChunkedEncodingTest, NormalGet) {
  1077. auto res = cli_.Get("/chunked");
  1078. ASSERT_TRUE(res);
  1079. std::string out;
  1080. read_file("./image.jpg", out);
  1081. EXPECT_EQ(StatusCode::OK_200, res->status);
  1082. EXPECT_EQ(out, res->body);
  1083. }
  1084. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1085. std::string body;
  1086. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1087. body.append(data, data_length);
  1088. return true;
  1089. });
  1090. ASSERT_TRUE(res);
  1091. std::string out;
  1092. read_file("./image.jpg", out);
  1093. EXPECT_EQ(StatusCode::OK_200, res->status);
  1094. EXPECT_EQ(out, body);
  1095. }
  1096. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1097. std::string body;
  1098. auto res = cli_.Get(
  1099. "/chunked",
  1100. [&](const Response &response) {
  1101. EXPECT_EQ(StatusCode::OK_200, response.status);
  1102. return true;
  1103. },
  1104. [&](const char *data, size_t data_length) {
  1105. body.append(data, data_length);
  1106. return true;
  1107. });
  1108. ASSERT_TRUE(res);
  1109. std::string out;
  1110. read_file("./image.jpg", out);
  1111. EXPECT_EQ(StatusCode::OK_200, res->status);
  1112. EXPECT_EQ(out, body);
  1113. }
  1114. TEST(RangeTest, FromHTTPBin_Online) {
  1115. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1116. auto host = "httpcan.org";
  1117. auto path = std::string{"/range/32"};
  1118. #else
  1119. auto host = "nghttp2.org";
  1120. auto path = std::string{"/httpbin/range/32"};
  1121. #endif
  1122. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1123. auto port = 443;
  1124. SSLClient cli(host, port);
  1125. #else
  1126. auto port = 80;
  1127. Client cli(host, port);
  1128. #endif
  1129. cli.set_connection_timeout(5);
  1130. {
  1131. auto res = cli.Get(path);
  1132. ASSERT_TRUE(res);
  1133. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1134. EXPECT_EQ(StatusCode::OK_200, res->status);
  1135. }
  1136. {
  1137. Headers headers = {make_range_header({{1, -1}})};
  1138. auto res = cli.Get(path, headers);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, 10}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijk", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{0, 31}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1155. EXPECT_EQ(StatusCode::OK_200, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, -1}})};
  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, 32}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1169. }
  1170. }
  1171. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1172. auto host = "unresolvableaddress.local";
  1173. auto path = std::string{"/"};
  1174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1175. auto port = 443;
  1176. SSLClient cli(host, port);
  1177. #else
  1178. auto port = 80;
  1179. Client cli(host, port);
  1180. #endif
  1181. cli.set_connection_timeout(1);
  1182. {
  1183. auto res = cli.Get(path);
  1184. ASSERT_FALSE(res);
  1185. }
  1186. std::this_thread::sleep_for(std::chrono::seconds(8));
  1187. }
  1188. TEST(ConnectionErrorTest, InvalidHost) {
  1189. auto host = "-abcde.com";
  1190. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1191. auto port = 443;
  1192. SSLClient cli(host, port);
  1193. #else
  1194. auto port = 80;
  1195. Client cli(host, port);
  1196. #endif
  1197. cli.set_connection_timeout(std::chrono::seconds(2));
  1198. auto res = cli.Get("/");
  1199. ASSERT_TRUE(!res);
  1200. EXPECT_EQ(Error::Connection, res.error());
  1201. }
  1202. TEST(ConnectionErrorTest, InvalidHost2) {
  1203. auto host = "httpcan.org/";
  1204. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1205. SSLClient cli(host);
  1206. #else
  1207. Client cli(host);
  1208. #endif
  1209. cli.set_connection_timeout(std::chrono::seconds(2));
  1210. auto res = cli.Get("/");
  1211. ASSERT_TRUE(!res);
  1212. EXPECT_EQ(Error::Connection, res.error());
  1213. }
  1214. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1215. auto host = "httpcan.org/";
  1216. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1217. SSLClient cli(host);
  1218. #else
  1219. Client cli(host);
  1220. #endif
  1221. cli.set_connection_timeout(std::chrono::seconds(2));
  1222. auto res = cli.Get("/");
  1223. ASSERT_TRUE(!res);
  1224. stringstream s;
  1225. s << "error code: " << res.error();
  1226. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1227. }
  1228. TEST(ConnectionErrorTest, InvalidPort) {
  1229. auto host = "localhost";
  1230. auto port = 44380;
  1231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1232. SSLClient cli(host, port);
  1233. #else
  1234. Client cli(host, port);
  1235. #endif
  1236. cli.set_connection_timeout(std::chrono::seconds(2));
  1237. auto res = cli.Get("/");
  1238. ASSERT_TRUE(!res);
  1239. EXPECT_TRUE(Error::Connection == res.error() ||
  1240. Error::ConnectionTimeout == res.error());
  1241. }
  1242. TEST(ConnectionErrorTest, Timeout_Online) {
  1243. auto host = "google.com";
  1244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1245. auto port = 44380;
  1246. SSLClient cli(host, port);
  1247. #else
  1248. auto port = 8080;
  1249. Client cli(host, port);
  1250. #endif
  1251. cli.set_connection_timeout(std::chrono::seconds(2));
  1252. // only probe one address type so that the error reason
  1253. // correlates to the timed-out IPv4, not the unsupported
  1254. // IPv6 connection attempt
  1255. cli.set_address_family(AF_INET);
  1256. auto res = cli.Get("/");
  1257. ASSERT_TRUE(!res);
  1258. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1259. }
  1260. TEST(CancelTest, NoCancel_Online) {
  1261. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1262. auto host = "httpcan.org";
  1263. auto path = std::string{"/range/32"};
  1264. #else
  1265. auto host = "nghttp2.org";
  1266. auto path = std::string{"/httpbin/range/32"};
  1267. #endif
  1268. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1269. auto port = 443;
  1270. SSLClient cli(host, port);
  1271. #else
  1272. auto port = 80;
  1273. Client cli(host, port);
  1274. #endif
  1275. cli.set_connection_timeout(std::chrono::seconds(5));
  1276. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1277. ASSERT_TRUE(res);
  1278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1279. EXPECT_EQ(StatusCode::OK_200, res->status);
  1280. }
  1281. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1282. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1283. auto host = "httpcan.org";
  1284. auto path = std::string{"/range/32"};
  1285. #else
  1286. auto host = "nghttp2.org";
  1287. auto path = std::string{"/httpbin/range/32"};
  1288. #endif
  1289. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1290. auto port = 443;
  1291. SSLClient cli(host, port);
  1292. #else
  1293. auto port = 80;
  1294. Client cli(host, port);
  1295. #endif
  1296. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1297. cli.set_connection_timeout(std::chrono::seconds(5));
  1298. ASSERT_TRUE(!res);
  1299. EXPECT_EQ(Error::Canceled, res.error());
  1300. }
  1301. TEST(CancelTest, WithCancelLargePayload_Online) {
  1302. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1303. auto host = "httpcan.org";
  1304. auto path = std::string{"/range/65536"};
  1305. #else
  1306. auto host = "nghttp2.org";
  1307. auto path = std::string{"/httpbin/range/65536"};
  1308. #endif
  1309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1310. auto port = 443;
  1311. SSLClient cli(host, port);
  1312. #else
  1313. auto port = 80;
  1314. Client cli(host, port);
  1315. #endif
  1316. cli.set_connection_timeout(std::chrono::seconds(5));
  1317. uint32_t count = 0;
  1318. auto res =
  1319. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1320. ASSERT_TRUE(!res);
  1321. EXPECT_EQ(Error::Canceled, res.error());
  1322. }
  1323. TEST(CancelTest, NoCancelPost) {
  1324. Server svr;
  1325. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1326. res.set_content("Hello World!", "text/plain");
  1327. });
  1328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. thread.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. Client cli(HOST, PORT);
  1336. cli.set_connection_timeout(std::chrono::seconds(5));
  1337. auto res =
  1338. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1339. "application/json", [](uint64_t, uint64_t) { return true; });
  1340. ASSERT_TRUE(res);
  1341. EXPECT_EQ("Hello World!", res->body);
  1342. EXPECT_EQ(StatusCode::OK_200, res->status);
  1343. }
  1344. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1345. Server svr;
  1346. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1347. res.set_content("Hello World!", "text/plain");
  1348. });
  1349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1350. auto se = detail::scope_exit([&] {
  1351. svr.stop();
  1352. thread.join();
  1353. ASSERT_FALSE(svr.is_running());
  1354. });
  1355. svr.wait_until_ready();
  1356. Client cli(HOST, PORT);
  1357. cli.set_connection_timeout(std::chrono::seconds(5));
  1358. auto res =
  1359. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1360. "application/json", [](uint64_t, uint64_t) { return false; });
  1361. ASSERT_TRUE(!res);
  1362. EXPECT_EQ(Error::Canceled, res.error());
  1363. }
  1364. TEST(CancelTest, WithCancelLargePayloadPost) {
  1365. Server svr;
  1366. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1367. res.set_content(LARGE_DATA, "text/plain");
  1368. });
  1369. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1370. auto se = detail::scope_exit([&] {
  1371. svr.stop();
  1372. thread.join();
  1373. ASSERT_FALSE(svr.is_running());
  1374. });
  1375. svr.wait_until_ready();
  1376. Client cli(HOST, PORT);
  1377. cli.set_connection_timeout(std::chrono::seconds(5));
  1378. auto res =
  1379. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1380. "application/json", [](uint64_t, uint64_t) { return false; });
  1381. ASSERT_TRUE(!res);
  1382. EXPECT_EQ(Error::Canceled, res.error());
  1383. }
  1384. TEST(CancelTest, NoCancelPut) {
  1385. Server svr;
  1386. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1387. res.set_content("Hello World!", "text/plain");
  1388. });
  1389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1390. auto se = detail::scope_exit([&] {
  1391. svr.stop();
  1392. thread.join();
  1393. ASSERT_FALSE(svr.is_running());
  1394. });
  1395. svr.wait_until_ready();
  1396. Client cli(HOST, PORT);
  1397. cli.set_connection_timeout(std::chrono::seconds(5));
  1398. auto res =
  1399. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1400. "application/json", [](uint64_t, uint64_t) { return true; });
  1401. ASSERT_TRUE(res);
  1402. EXPECT_EQ("Hello World!", res->body);
  1403. EXPECT_EQ(StatusCode::OK_200, res->status);
  1404. }
  1405. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1406. Server svr;
  1407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1408. res.set_content("Hello World!", "text/plain");
  1409. });
  1410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1411. auto se = detail::scope_exit([&] {
  1412. svr.stop();
  1413. thread.join();
  1414. ASSERT_FALSE(svr.is_running());
  1415. });
  1416. svr.wait_until_ready();
  1417. Client cli(HOST, PORT);
  1418. cli.set_connection_timeout(std::chrono::seconds(5));
  1419. auto res =
  1420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1421. "application/json", [](uint64_t, uint64_t) { return false; });
  1422. ASSERT_TRUE(!res);
  1423. EXPECT_EQ(Error::Canceled, res.error());
  1424. }
  1425. TEST(CancelTest, WithCancelLargePayloadPut) {
  1426. Server svr;
  1427. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1428. res.set_content(LARGE_DATA, "text/plain");
  1429. });
  1430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. thread.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, PORT);
  1438. cli.set_connection_timeout(std::chrono::seconds(5));
  1439. auto res =
  1440. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1441. "application/json", [](uint64_t, uint64_t) { return false; });
  1442. ASSERT_TRUE(!res);
  1443. EXPECT_EQ(Error::Canceled, res.error());
  1444. }
  1445. TEST(CancelTest, NoCancelPatch) {
  1446. Server svr;
  1447. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1448. res.set_content("Hello World!", "text/plain");
  1449. });
  1450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1451. auto se = detail::scope_exit([&] {
  1452. svr.stop();
  1453. thread.join();
  1454. ASSERT_FALSE(svr.is_running());
  1455. });
  1456. svr.wait_until_ready();
  1457. Client cli(HOST, PORT);
  1458. cli.set_connection_timeout(std::chrono::seconds(5));
  1459. auto res =
  1460. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1461. "application/json", [](uint64_t, uint64_t) { return true; });
  1462. ASSERT_TRUE(res);
  1463. EXPECT_EQ("Hello World!", res->body);
  1464. EXPECT_EQ(StatusCode::OK_200, res->status);
  1465. }
  1466. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1467. Server svr;
  1468. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1469. res.set_content("Hello World!", "text/plain");
  1470. });
  1471. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1472. auto se = detail::scope_exit([&] {
  1473. svr.stop();
  1474. thread.join();
  1475. ASSERT_FALSE(svr.is_running());
  1476. });
  1477. svr.wait_until_ready();
  1478. Client cli(HOST, PORT);
  1479. cli.set_connection_timeout(std::chrono::seconds(5));
  1480. auto res =
  1481. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1482. "application/json", [](uint64_t, uint64_t) { return false; });
  1483. ASSERT_TRUE(!res);
  1484. EXPECT_EQ(Error::Canceled, res.error());
  1485. }
  1486. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1487. Server svr;
  1488. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1489. res.set_content(LARGE_DATA, "text/plain");
  1490. });
  1491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. thread.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, PORT);
  1499. cli.set_connection_timeout(std::chrono::seconds(5));
  1500. auto res =
  1501. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1502. "application/json", [](uint64_t, uint64_t) { return false; });
  1503. ASSERT_TRUE(!res);
  1504. EXPECT_EQ(Error::Canceled, res.error());
  1505. }
  1506. TEST(CancelTest, NoCancelDelete) {
  1507. Server svr;
  1508. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1509. res.set_content("Hello World!", "text/plain");
  1510. });
  1511. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1512. auto se = detail::scope_exit([&] {
  1513. svr.stop();
  1514. thread.join();
  1515. ASSERT_FALSE(svr.is_running());
  1516. });
  1517. svr.wait_until_ready();
  1518. Client cli(HOST, PORT);
  1519. cli.set_connection_timeout(std::chrono::seconds(5));
  1520. auto res =
  1521. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1522. "application/json", [](uint64_t, uint64_t) { return true; });
  1523. ASSERT_TRUE(res);
  1524. EXPECT_EQ("Hello World!", res->body);
  1525. EXPECT_EQ(StatusCode::OK_200, res->status);
  1526. }
  1527. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1528. Server svr;
  1529. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1530. res.set_content("Hello World!", "text/plain");
  1531. });
  1532. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1533. auto se = detail::scope_exit([&] {
  1534. svr.stop();
  1535. thread.join();
  1536. ASSERT_FALSE(svr.is_running());
  1537. });
  1538. svr.wait_until_ready();
  1539. Client cli(HOST, PORT);
  1540. cli.set_connection_timeout(std::chrono::seconds(5));
  1541. auto res =
  1542. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1543. "application/json", [](uint64_t, uint64_t) { return false; });
  1544. ASSERT_TRUE(!res);
  1545. EXPECT_EQ(Error::Canceled, res.error());
  1546. }
  1547. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1548. Server svr;
  1549. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1550. res.set_content(LARGE_DATA, "text/plain");
  1551. });
  1552. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1553. auto se = detail::scope_exit([&] {
  1554. svr.stop();
  1555. thread.join();
  1556. ASSERT_FALSE(svr.is_running());
  1557. });
  1558. svr.wait_until_ready();
  1559. Client cli(HOST, PORT);
  1560. cli.set_connection_timeout(std::chrono::seconds(5));
  1561. auto res =
  1562. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1563. "application/json", [](uint64_t, uint64_t) { return false; });
  1564. ASSERT_TRUE(!res);
  1565. EXPECT_EQ(Error::Canceled, res.error());
  1566. }
  1567. static std::string remove_whitespace(const std::string &input) {
  1568. std::string output;
  1569. output.reserve(input.size());
  1570. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1571. [](unsigned char c) { return !std::isspace(c); });
  1572. return output;
  1573. }
  1574. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1575. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1576. auto host = "httpcan.org";
  1577. auto path = std::string{"/basic-auth/hello/world"};
  1578. #else
  1579. auto host = "nghttp2.org";
  1580. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1581. #endif
  1582. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1583. auto port = 443;
  1584. SSLClient cli(host, port);
  1585. #else
  1586. auto port = 80;
  1587. Client cli(host, port);
  1588. #endif
  1589. {
  1590. auto res = cli.Get(path);
  1591. ASSERT_TRUE(res);
  1592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1593. }
  1594. {
  1595. auto res =
  1596. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1597. ASSERT_TRUE(res);
  1598. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1599. remove_whitespace(res->body));
  1600. EXPECT_EQ(StatusCode::OK_200, res->status);
  1601. }
  1602. {
  1603. cli.set_basic_auth("hello", "world");
  1604. auto res = cli.Get(path);
  1605. ASSERT_TRUE(res);
  1606. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1607. remove_whitespace(res->body));
  1608. EXPECT_EQ(StatusCode::OK_200, res->status);
  1609. }
  1610. {
  1611. cli.set_basic_auth("hello", "bad");
  1612. auto res = cli.Get(path);
  1613. ASSERT_TRUE(res);
  1614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1615. }
  1616. {
  1617. cli.set_basic_auth("bad", "world");
  1618. auto res = cli.Get(path);
  1619. ASSERT_TRUE(res);
  1620. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1621. }
  1622. }
  1623. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1624. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1625. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1626. auto host = "httpcan.org";
  1627. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1628. auto paths = std::vector<std::string>{
  1629. "/digest-auth/auth/hello/world/MD5",
  1630. "/digest-auth/auth/hello/world/SHA-256",
  1631. "/digest-auth/auth/hello/world/SHA-512",
  1632. };
  1633. #else
  1634. auto host = "nghttp2.org";
  1635. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1636. auto paths = std::vector<std::string>{
  1637. "/httpbin/digest-auth/auth/hello/world/MD5",
  1638. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1639. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1640. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1641. };
  1642. #endif
  1643. auto port = 443;
  1644. SSLClient cli(host, port);
  1645. {
  1646. auto res = cli.Get(unauth_path);
  1647. ASSERT_TRUE(res);
  1648. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1649. }
  1650. {
  1651. cli.set_digest_auth("hello", "world");
  1652. for (const auto &path : paths) {
  1653. auto res = cli.Get(path.c_str());
  1654. ASSERT_TRUE(res);
  1655. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1656. std::string algo(path.substr(path.rfind('/') + 1));
  1657. EXPECT_EQ(
  1658. remove_whitespace("{\"algorithm\":\"" + algo +
  1659. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1660. remove_whitespace(res->body));
  1661. #else
  1662. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1663. remove_whitespace(res->body));
  1664. #endif
  1665. EXPECT_EQ(StatusCode::OK_200, res->status);
  1666. }
  1667. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1668. cli.set_digest_auth("hello", "bad");
  1669. for (const auto &path : paths) {
  1670. auto res = cli.Get(path.c_str());
  1671. ASSERT_TRUE(res);
  1672. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1673. }
  1674. #endif
  1675. }
  1676. }
  1677. #endif
  1678. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1679. auto host = "google.com";
  1680. auto another_host = "example.com";
  1681. auto wrong_ip = "0.0.0.0";
  1682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1683. SSLClient cli(host);
  1684. #else
  1685. Client cli(host);
  1686. #endif
  1687. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1688. auto res = cli.Get("/");
  1689. ASSERT_TRUE(res);
  1690. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1691. }
  1692. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1693. auto host = "google.com";
  1694. auto wrong_ip = "0.0.0.0";
  1695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1696. SSLClient cli(host);
  1697. #else
  1698. Client cli(host);
  1699. #endif
  1700. cli.set_hostname_addr_map({{host, wrong_ip}});
  1701. auto res = cli.Get("/");
  1702. ASSERT_TRUE(!res);
  1703. EXPECT_EQ(Error::Connection, res.error());
  1704. }
  1705. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1706. auto host = "nghttp2.org";
  1707. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1708. SSLClient cli(host);
  1709. #else
  1710. Client cli(host);
  1711. #endif
  1712. cli.set_follow_location(true);
  1713. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1714. ASSERT_TRUE(res);
  1715. EXPECT_EQ(StatusCode::OK_200, res->status);
  1716. }
  1717. TEST(RedirectTest, Redirect_Online) {
  1718. auto host = "nghttp2.org";
  1719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1720. SSLClient cli(host);
  1721. #else
  1722. Client cli(host);
  1723. #endif
  1724. cli.set_follow_location(true);
  1725. auto res = cli.Get("/httpbin/redirect/3");
  1726. ASSERT_TRUE(res);
  1727. EXPECT_EQ(StatusCode::OK_200, res->status);
  1728. }
  1729. TEST(RelativeRedirectTest, Redirect_Online) {
  1730. auto host = "nghttp2.org";
  1731. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1732. SSLClient cli(host);
  1733. #else
  1734. Client cli(host);
  1735. #endif
  1736. cli.set_follow_location(true);
  1737. auto res = cli.Get("/httpbin/relative-redirect/3");
  1738. ASSERT_TRUE(res);
  1739. EXPECT_EQ(StatusCode::OK_200, res->status);
  1740. }
  1741. TEST(TooManyRedirectTest, Redirect_Online) {
  1742. auto host = "nghttp2.org";
  1743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1744. SSLClient cli(host);
  1745. #else
  1746. Client cli(host);
  1747. #endif
  1748. cli.set_follow_location(true);
  1749. auto res = cli.Get("/httpbin/redirect/21");
  1750. ASSERT_TRUE(!res);
  1751. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1752. }
  1753. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1754. TEST(YahooRedirectTest, Redirect_Online) {
  1755. Client cli("yahoo.com");
  1756. auto res = cli.Get("/");
  1757. ASSERT_TRUE(res);
  1758. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1759. cli.set_follow_location(true);
  1760. res = cli.Get("/");
  1761. ASSERT_TRUE(res);
  1762. EXPECT_EQ(StatusCode::OK_200, res->status);
  1763. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1764. }
  1765. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1766. #define REDIR_HOST "httpbingo.org"
  1767. #define REDIR_PATH "/redirect-to"
  1768. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1769. SSLClient cli(REDIR_HOST);
  1770. cli.set_follow_location(true);
  1771. auto res =
  1772. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1773. ASSERT_TRUE(res);
  1774. EXPECT_EQ(StatusCode::OK_200, res->status);
  1775. }
  1776. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1777. SSLClient cli(REDIR_HOST);
  1778. cli.set_follow_location(true);
  1779. Params params;
  1780. params.emplace("url", "http://example.com");
  1781. params.emplace("status_code", "302");
  1782. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1783. ASSERT_TRUE(res);
  1784. EXPECT_EQ(StatusCode::OK_200, res->status);
  1785. }
  1786. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1787. SSLClient cli(REDIR_HOST);
  1788. cli.set_follow_location(true);
  1789. Params params;
  1790. params.emplace("url", "http://example.com");
  1791. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1792. ASSERT_TRUE(res);
  1793. EXPECT_EQ(StatusCode::OK_200, res->status);
  1794. }
  1795. TEST(UrlWithSpace, Redirect_Online) {
  1796. SSLClient cli("edge.forgecdn.net");
  1797. cli.set_follow_location(true);
  1798. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1802. }
  1803. #endif
  1804. #if !defined(_WIN32) && !defined(_WIN64)
  1805. TEST(ReceiveSignals, Signal) {
  1806. auto setupSignalHandlers = []() {
  1807. struct sigaction act;
  1808. sigemptyset(&act.sa_mask);
  1809. act.sa_flags = SA_SIGINFO;
  1810. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1811. switch (sig) {
  1812. case SIGINT:
  1813. default: break;
  1814. }
  1815. };
  1816. ::sigaction(SIGINT, &act, nullptr);
  1817. };
  1818. Server svr;
  1819. int port = 0;
  1820. auto thread = std::thread([&]() {
  1821. setupSignalHandlers();
  1822. port = svr.bind_to_any_port("localhost");
  1823. svr.listen_after_bind();
  1824. });
  1825. auto se = detail::scope_exit([&] {
  1826. svr.stop();
  1827. thread.join();
  1828. ASSERT_FALSE(svr.is_running());
  1829. });
  1830. svr.wait_until_ready();
  1831. ASSERT_TRUE(svr.is_running());
  1832. pthread_kill(thread.native_handle(), SIGINT);
  1833. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1834. ASSERT_TRUE(svr.is_running());
  1835. }
  1836. #endif
  1837. TEST(RedirectToDifferentPort, Redirect) {
  1838. Server svr1;
  1839. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1840. res.set_content("Hello World!", "text/plain");
  1841. });
  1842. int svr1_port = 0;
  1843. auto thread1 = std::thread([&]() {
  1844. svr1_port = svr1.bind_to_any_port("localhost");
  1845. svr1.listen_after_bind();
  1846. });
  1847. Server svr2;
  1848. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1849. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1850. });
  1851. int svr2_port = 0;
  1852. auto thread2 = std::thread([&]() {
  1853. svr2_port = svr2.bind_to_any_port("localhost");
  1854. svr2.listen_after_bind();
  1855. });
  1856. auto se = detail::scope_exit([&] {
  1857. svr2.stop();
  1858. thread2.join();
  1859. svr1.stop();
  1860. thread1.join();
  1861. ASSERT_FALSE(svr2.is_running());
  1862. ASSERT_FALSE(svr1.is_running());
  1863. });
  1864. svr1.wait_until_ready();
  1865. svr2.wait_until_ready();
  1866. Client cli("localhost", svr2_port);
  1867. cli.set_follow_location(true);
  1868. auto res = cli.Get("/2");
  1869. ASSERT_TRUE(res);
  1870. EXPECT_EQ(StatusCode::OK_200, res->status);
  1871. EXPECT_EQ("Hello World!", res->body);
  1872. }
  1873. TEST(RedirectFromPageWithContent, Redirect) {
  1874. Server svr;
  1875. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1876. res.set_content("___", "text/plain");
  1877. res.set_redirect("/2");
  1878. });
  1879. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1880. res.set_content("Hello World!", "text/plain");
  1881. });
  1882. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1883. auto se = detail::scope_exit([&] {
  1884. svr.stop();
  1885. th.join();
  1886. ASSERT_FALSE(svr.is_running());
  1887. });
  1888. svr.wait_until_ready();
  1889. {
  1890. Client cli("localhost", PORT);
  1891. cli.set_follow_location(true);
  1892. std::string body;
  1893. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1894. body.append(data, data_length);
  1895. return true;
  1896. });
  1897. ASSERT_TRUE(res);
  1898. EXPECT_EQ(StatusCode::OK_200, res->status);
  1899. EXPECT_EQ("Hello World!", body);
  1900. }
  1901. {
  1902. Client cli("localhost", PORT);
  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::Found_302, res->status);
  1910. EXPECT_EQ("___", body);
  1911. }
  1912. }
  1913. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1914. Server svr;
  1915. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1916. res.set_content("___", "text/plain");
  1917. // res.set_redirect("/2");
  1918. res.set_redirect("http://[::1]:1234/2");
  1919. });
  1920. svr.Get("/2", [&](const Request &req, Response &res) {
  1921. auto host_header = req.headers.find("Host");
  1922. ASSERT_TRUE(host_header != req.headers.end());
  1923. EXPECT_EQ("[::1]:1234", host_header->second);
  1924. res.set_content("Hello World!", "text/plain");
  1925. });
  1926. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1927. auto se = detail::scope_exit([&] {
  1928. svr.stop();
  1929. th.join();
  1930. ASSERT_FALSE(svr.is_running());
  1931. });
  1932. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1933. // actually starts anything, so the condition !svr.is_running() will
  1934. // always remain true, and the loop never stops.
  1935. // This basically counts how many milliseconds have passed since the
  1936. // call to svr.listen(), and if after 5 seconds nothing started yet
  1937. // aborts the test.
  1938. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1939. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1940. ASSERT_LT(milliseconds, 5000U);
  1941. }
  1942. {
  1943. Client cli("http://[::1]:1234");
  1944. cli.set_follow_location(true);
  1945. std::string body;
  1946. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1947. body.append(data, data_length);
  1948. return true;
  1949. });
  1950. ASSERT_TRUE(res);
  1951. EXPECT_EQ(StatusCode::OK_200, res->status);
  1952. EXPECT_EQ("Hello World!", body);
  1953. }
  1954. {
  1955. Client cli("http://[::1]:1234");
  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::Found_302, res->status);
  1963. EXPECT_EQ("___", body);
  1964. }
  1965. }
  1966. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1967. Server svr;
  1968. svr.Get("/foo", [](const Request &req, Response &res) {
  1969. auto a = req.params.find("a");
  1970. if (a != req.params.end()) {
  1971. res.set_content((*a).second, "text/plain");
  1972. res.status = StatusCode::OK_200;
  1973. } else {
  1974. res.status = StatusCode::BadRequest_400;
  1975. }
  1976. });
  1977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1978. auto se = detail::scope_exit([&] {
  1979. svr.stop();
  1980. thread.join();
  1981. ASSERT_FALSE(svr.is_running());
  1982. });
  1983. svr.wait_until_ready();
  1984. {
  1985. Client cli(HOST, PORT);
  1986. cli.set_path_encode(false);
  1987. auto res = cli.Get("/foo?a=explicitly+encoded");
  1988. ASSERT_TRUE(res);
  1989. EXPECT_EQ(StatusCode::OK_200, res->status);
  1990. // This expects it back with a space, as the `+` won't have been
  1991. // url-encoded, and server-side the params get decoded turning `+`
  1992. // into spaces.
  1993. EXPECT_EQ("explicitly encoded", res->body);
  1994. }
  1995. }
  1996. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1997. Server svr;
  1998. svr.Get("/", [](const Request &req, Response &) {
  1999. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2000. });
  2001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2002. auto se = detail::scope_exit([&] {
  2003. svr.stop();
  2004. thread.join();
  2005. ASSERT_FALSE(svr.is_running());
  2006. });
  2007. svr.wait_until_ready();
  2008. {
  2009. Client cli(HOST, PORT);
  2010. cli.set_path_encode(false);
  2011. auto res = cli.Get("/?something=%0A");
  2012. ASSERT_TRUE(res);
  2013. EXPECT_EQ(StatusCode::OK_200, res->status);
  2014. }
  2015. }
  2016. TEST(BindServerTest, DISABLED_BindDualStack) {
  2017. Server svr;
  2018. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2019. res.set_content("Hello World!", "text/plain");
  2020. });
  2021. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2022. auto se = detail::scope_exit([&] {
  2023. svr.stop();
  2024. thread.join();
  2025. ASSERT_FALSE(svr.is_running());
  2026. });
  2027. svr.wait_until_ready();
  2028. {
  2029. Client cli("127.0.0.1", PORT);
  2030. auto res = cli.Get("/1");
  2031. ASSERT_TRUE(res);
  2032. EXPECT_EQ(StatusCode::OK_200, res->status);
  2033. EXPECT_EQ("Hello World!", res->body);
  2034. }
  2035. {
  2036. Client cli("::1", PORT);
  2037. auto res = cli.Get("/1");
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. EXPECT_EQ("Hello World!", res->body);
  2041. }
  2042. }
  2043. TEST(BindServerTest, BindAndListenSeparately) {
  2044. Server svr;
  2045. int port = svr.bind_to_any_port("0.0.0.0");
  2046. ASSERT_TRUE(svr.is_valid());
  2047. ASSERT_TRUE(port > 0);
  2048. svr.stop();
  2049. }
  2050. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2051. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2053. CLIENT_CA_CERT_DIR);
  2054. int port = svr.bind_to_any_port("0.0.0.0");
  2055. ASSERT_TRUE(svr.is_valid());
  2056. ASSERT_TRUE(port > 0);
  2057. svr.stop();
  2058. }
  2059. #endif
  2060. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2061. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2062. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2063. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2064. int port = svr.bind_to_any_port("0.0.0.0");
  2065. ASSERT_TRUE(svr.is_valid());
  2066. ASSERT_TRUE(port > 0);
  2067. svr.stop();
  2068. }
  2069. #endif
  2070. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2071. X509 *readCertificate(const std::string &strFileName) {
  2072. std::ifstream inStream(strFileName);
  2073. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2074. std::istreambuf_iterator<char>());
  2075. if (strCertPEM.empty()) return (nullptr);
  2076. BIO *pbCert = BIO_new(BIO_s_mem());
  2077. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2078. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2079. BIO_free(pbCert);
  2080. return (pCert);
  2081. }
  2082. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2083. std::ifstream inStream(strFileName);
  2084. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2085. std::istreambuf_iterator<char>());
  2086. if (strPrivateKeyPEM.empty()) return (nullptr);
  2087. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2088. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2089. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2090. BIO_free(pbPrivKey);
  2091. return (pPrivateKey);
  2092. }
  2093. TEST(BindServerTest, UpdateCerts) {
  2094. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2095. int port = svr.bind_to_any_port("0.0.0.0");
  2096. ASSERT_TRUE(svr.is_valid());
  2097. ASSERT_TRUE(port > 0);
  2098. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2099. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2100. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2101. ASSERT_TRUE(cert != nullptr);
  2102. ASSERT_TRUE(ca_cert != nullptr);
  2103. ASSERT_TRUE(key != nullptr);
  2104. X509_STORE *cert_store = X509_STORE_new();
  2105. X509_STORE_add_cert(cert_store, ca_cert);
  2106. svr.update_certs(cert, key, cert_store);
  2107. ASSERT_TRUE(svr.is_valid());
  2108. svr.stop();
  2109. X509_free(cert);
  2110. X509_free(ca_cert);
  2111. EVP_PKEY_free(key);
  2112. }
  2113. #endif
  2114. TEST(ErrorHandlerTest, ContentLength) {
  2115. Server svr;
  2116. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2117. res.status = StatusCode::OK_200;
  2118. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2119. "text/html"); // <= Content-Length still 13
  2120. });
  2121. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2122. res.set_content("Hello World!\n", "text/plain");
  2123. res.status = 524;
  2124. });
  2125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2126. auto se = detail::scope_exit([&] {
  2127. svr.stop();
  2128. thread.join();
  2129. ASSERT_FALSE(svr.is_running());
  2130. });
  2131. svr.wait_until_ready();
  2132. {
  2133. Client cli(HOST, PORT);
  2134. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2135. ASSERT_TRUE(res);
  2136. EXPECT_EQ(StatusCode::OK_200, res->status);
  2137. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2138. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2139. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2140. }
  2141. }
  2142. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2143. TEST(ExceptionTest, WithoutExceptionHandler) {
  2144. Server svr;
  2145. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2146. throw std::runtime_error("exception...");
  2147. });
  2148. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2149. throw std::runtime_error("exception\r\n...");
  2150. });
  2151. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2152. auto se = detail::scope_exit([&] {
  2153. svr.stop();
  2154. listen_thread.join();
  2155. ASSERT_FALSE(svr.is_running());
  2156. });
  2157. svr.wait_until_ready();
  2158. Client cli("localhost", PORT);
  2159. {
  2160. auto res = cli.Get("/exception");
  2161. ASSERT_TRUE(res);
  2162. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2163. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2164. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2165. }
  2166. {
  2167. auto res = cli.Get("/unknown");
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2170. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2171. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2172. }
  2173. }
  2174. TEST(ExceptionTest, WithExceptionHandler) {
  2175. Server svr;
  2176. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2177. std::exception_ptr ep) {
  2178. EXPECT_FALSE(ep == nullptr);
  2179. try {
  2180. std::rethrow_exception(ep);
  2181. } catch (std::exception &e) {
  2182. EXPECT_EQ("abc", std::string(e.what()));
  2183. } catch (...) {}
  2184. res.status = StatusCode::InternalServerError_500;
  2185. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2186. "text/html"); // <= Content-Length still 13 at this point
  2187. });
  2188. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2189. res.set_content("Hello World!\n", "text/plain");
  2190. throw std::runtime_error("abc");
  2191. });
  2192. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2193. auto se = detail::scope_exit([&] {
  2194. svr.stop();
  2195. thread.join();
  2196. ASSERT_FALSE(svr.is_running());
  2197. });
  2198. svr.wait_until_ready();
  2199. for (size_t i = 0; i < 10; i++) {
  2200. Client cli(HOST, PORT);
  2201. for (size_t j = 0; j < 100; j++) {
  2202. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2203. ASSERT_TRUE(res);
  2204. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2205. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2206. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2207. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2208. }
  2209. cli.set_keep_alive(true);
  2210. for (size_t j = 0; j < 100; j++) {
  2211. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2215. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2216. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2217. }
  2218. }
  2219. }
  2220. TEST(ExceptionTest, AndErrorHandler) {
  2221. Server svr;
  2222. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2223. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2224. });
  2225. svr.set_exception_handler(
  2226. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2227. EXPECT_FALSE(ep == nullptr);
  2228. try {
  2229. std::rethrow_exception(ep);
  2230. } catch (std::exception &e) {
  2231. res.set_content(e.what(), "text/html");
  2232. } catch (...) {}
  2233. res.status = StatusCode::InternalServerError_500;
  2234. });
  2235. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2236. throw std::runtime_error("EXCEPTION");
  2237. });
  2238. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2239. res.set_content("ERROR", "text/html");
  2240. res.status = StatusCode::InternalServerError_500;
  2241. });
  2242. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2243. auto se = detail::scope_exit([&] {
  2244. svr.stop();
  2245. thread.join();
  2246. ASSERT_FALSE(svr.is_running());
  2247. });
  2248. svr.wait_until_ready();
  2249. Client cli(HOST, PORT);
  2250. {
  2251. auto res = cli.Get("/exception");
  2252. ASSERT_TRUE(res);
  2253. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2254. EXPECT_EQ("EXCEPTION", res->body);
  2255. }
  2256. {
  2257. auto res = cli.Get("/error");
  2258. ASSERT_TRUE(res);
  2259. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2260. EXPECT_EQ("ERROR", res->body);
  2261. }
  2262. {
  2263. auto res = cli.Get("/invalid");
  2264. ASSERT_TRUE(res);
  2265. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2266. EXPECT_EQ("NOT_FOUND", res->body);
  2267. }
  2268. }
  2269. #endif
  2270. TEST(NoContentTest, ContentLength) {
  2271. Server svr;
  2272. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2273. res.status = StatusCode::NoContent_204;
  2274. });
  2275. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2276. auto se = detail::scope_exit([&] {
  2277. svr.stop();
  2278. thread.join();
  2279. ASSERT_FALSE(svr.is_running());
  2280. });
  2281. svr.wait_until_ready();
  2282. {
  2283. Client cli(HOST, PORT);
  2284. auto res = cli.Get("/hi");
  2285. ASSERT_TRUE(res);
  2286. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2287. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2288. }
  2289. }
  2290. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2291. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2293. ASSERT_TRUE(svr.is_valid());
  2294. #else
  2295. Server svr;
  2296. #endif
  2297. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2298. if (req.path == "/routing_handler") {
  2299. res.set_header("PRE_ROUTING", "on");
  2300. res.set_content("Routing Handler", "text/plain");
  2301. return httplib::Server::HandlerResponse::Handled;
  2302. }
  2303. return httplib::Server::HandlerResponse::Unhandled;
  2304. });
  2305. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2306. res.set_content("Error", "text/html");
  2307. });
  2308. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2309. if (req.path == "/routing_handler") {
  2310. res.set_header("POST_ROUTING", "on");
  2311. }
  2312. });
  2313. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2314. res.set_content("Hello World!\n", "text/plain");
  2315. });
  2316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2317. auto se = detail::scope_exit([&] {
  2318. svr.stop();
  2319. thread.join();
  2320. ASSERT_FALSE(svr.is_running());
  2321. });
  2322. svr.wait_until_ready();
  2323. {
  2324. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2325. SSLClient cli(HOST, PORT);
  2326. cli.enable_server_certificate_verification(false);
  2327. #else
  2328. Client cli(HOST, PORT);
  2329. #endif
  2330. auto res = cli.Get("/routing_handler");
  2331. ASSERT_TRUE(res);
  2332. EXPECT_EQ(StatusCode::OK_200, res->status);
  2333. EXPECT_EQ("Routing Handler", res->body);
  2334. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2335. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2336. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2337. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2338. }
  2339. {
  2340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2341. SSLClient cli(HOST, PORT);
  2342. cli.enable_server_certificate_verification(false);
  2343. #else
  2344. Client cli(HOST, PORT);
  2345. #endif
  2346. auto res = cli.Get("/hi");
  2347. ASSERT_TRUE(res);
  2348. EXPECT_EQ(StatusCode::OK_200, res->status);
  2349. EXPECT_EQ("Hello World!\n", res->body);
  2350. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2351. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2352. }
  2353. {
  2354. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2355. SSLClient cli(HOST, PORT);
  2356. cli.enable_server_certificate_verification(false);
  2357. #else
  2358. Client cli(HOST, PORT);
  2359. #endif
  2360. auto res = cli.Get("/aaa");
  2361. ASSERT_TRUE(res);
  2362. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2363. EXPECT_EQ("Error", res->body);
  2364. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2365. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2366. }
  2367. }
  2368. TEST(RequestHandlerTest, PreRequestHandler) {
  2369. auto route_path = "/user/:user";
  2370. Server svr;
  2371. svr.Get("/hi", [](const Request &, Response &res) {
  2372. res.set_content("hi", "text/plain");
  2373. });
  2374. svr.Get(route_path, [](const Request &req, Response &res) {
  2375. res.set_content(req.path_params.at("user"), "text/plain");
  2376. });
  2377. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2378. if (req.matched_route == route_path) {
  2379. auto user = req.path_params.at("user");
  2380. if (user != "john") {
  2381. res.status = StatusCode::Forbidden_403;
  2382. res.set_content("error", "text/html");
  2383. return Server::HandlerResponse::Handled;
  2384. }
  2385. }
  2386. return Server::HandlerResponse::Unhandled;
  2387. });
  2388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2389. auto se = detail::scope_exit([&] {
  2390. svr.stop();
  2391. thread.join();
  2392. ASSERT_FALSE(svr.is_running());
  2393. });
  2394. svr.wait_until_ready();
  2395. Client cli(HOST, PORT);
  2396. {
  2397. auto res = cli.Get("/hi");
  2398. ASSERT_TRUE(res);
  2399. EXPECT_EQ(StatusCode::OK_200, res->status);
  2400. EXPECT_EQ("hi", res->body);
  2401. }
  2402. {
  2403. auto res = cli.Get("/user/john");
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(StatusCode::OK_200, res->status);
  2406. EXPECT_EQ("john", res->body);
  2407. }
  2408. {
  2409. auto res = cli.Get("/user/invalid-user");
  2410. ASSERT_TRUE(res);
  2411. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2412. EXPECT_EQ("error", res->body);
  2413. }
  2414. }
  2415. TEST(InvalidFormatTest, StatusCode) {
  2416. Server svr;
  2417. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2418. res.set_content("Hello World!\n", "text/plain");
  2419. res.status = 9999; // Status should be a three-digit code...
  2420. });
  2421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. {
  2429. Client cli(HOST, PORT);
  2430. auto res = cli.Get("/hi");
  2431. ASSERT_FALSE(res);
  2432. }
  2433. }
  2434. TEST(URLFragmentTest, WithFragment) {
  2435. Server svr;
  2436. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2437. EXPECT_TRUE(req.target == "/hi");
  2438. });
  2439. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2440. auto se = detail::scope_exit([&] {
  2441. svr.stop();
  2442. thread.join();
  2443. ASSERT_FALSE(svr.is_running());
  2444. });
  2445. svr.wait_until_ready();
  2446. {
  2447. Client cli(HOST, PORT);
  2448. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2449. EXPECT_TRUE(res);
  2450. EXPECT_EQ(StatusCode::OK_200, res->status);
  2451. res = cli.Get("/hi%23key1=val1=key2=val2");
  2452. EXPECT_TRUE(res);
  2453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2454. }
  2455. }
  2456. TEST(HeaderWriter, SetHeaderWriter) {
  2457. Server svr;
  2458. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2459. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2460. return detail::write_headers(strm, hdrs);
  2461. });
  2462. svr.Get("/hi", [](const Request &req, Response &res) {
  2463. auto it = req.headers.find("CustomClientHeader");
  2464. EXPECT_TRUE(it != req.headers.end());
  2465. EXPECT_EQ(it->second, "CustomClientValue");
  2466. res.set_content("Hello World!\n", "text/plain");
  2467. });
  2468. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2469. auto se = detail::scope_exit([&] {
  2470. svr.stop();
  2471. thread.join();
  2472. ASSERT_FALSE(svr.is_running());
  2473. });
  2474. svr.wait_until_ready();
  2475. {
  2476. Client cli(HOST, PORT);
  2477. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2478. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2479. return detail::write_headers(strm, hdrs);
  2480. });
  2481. auto res = cli.Get("/hi");
  2482. EXPECT_TRUE(res);
  2483. EXPECT_EQ(StatusCode::OK_200, res->status);
  2484. auto it = res->headers.find("CustomServerHeader");
  2485. EXPECT_TRUE(it != res->headers.end());
  2486. EXPECT_EQ(it->second, "CustomServerValue");
  2487. }
  2488. }
  2489. class ServerTest : public ::testing::Test {
  2490. protected:
  2491. ServerTest()
  2492. : cli_(HOST, PORT)
  2493. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2494. ,
  2495. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2496. #endif
  2497. {
  2498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2499. cli_.enable_server_certificate_verification(false);
  2500. #endif
  2501. }
  2502. virtual void SetUp() {
  2503. svr_.set_mount_point("/", "./www");
  2504. svr_.set_mount_point("/mount", "./www2");
  2505. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2506. svr_.Get("/hi",
  2507. [&](const Request & /*req*/, Response &res) {
  2508. res.set_content("Hello World!", "text/plain");
  2509. })
  2510. .Get("/file_content",
  2511. [&](const Request & /*req*/, Response &res) {
  2512. res.set_file_content("./www/dir/test.html");
  2513. })
  2514. .Get("/file_content_with_content_type",
  2515. [&](const Request & /*req*/, Response &res) {
  2516. res.set_file_content("./www/file", "text/plain");
  2517. })
  2518. .Get("/invalid_file_content",
  2519. [&](const Request & /*req*/, Response &res) {
  2520. res.set_file_content("./www/dir/invalid_file_path");
  2521. })
  2522. .Get("/http_response_splitting",
  2523. [&](const Request & /*req*/, Response &res) {
  2524. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2525. EXPECT_EQ(0U, res.headers.size());
  2526. EXPECT_FALSE(res.has_header("a"));
  2527. res.set_header("a", "1\nSet-Cookie: a=1");
  2528. EXPECT_EQ(0U, res.headers.size());
  2529. EXPECT_FALSE(res.has_header("a"));
  2530. res.set_header("a", "1\rSet-Cookie: a=1");
  2531. EXPECT_EQ(0U, res.headers.size());
  2532. EXPECT_FALSE(res.has_header("a"));
  2533. res.set_header("a\r\nb", "0");
  2534. EXPECT_EQ(0U, res.headers.size());
  2535. EXPECT_FALSE(res.has_header("a"));
  2536. res.set_header("a\rb", "0");
  2537. EXPECT_EQ(0U, res.headers.size());
  2538. EXPECT_FALSE(res.has_header("a"));
  2539. res.set_header("a\nb", "0");
  2540. EXPECT_EQ(0U, res.headers.size());
  2541. EXPECT_FALSE(res.has_header("a"));
  2542. res.set_redirect("1\r\nSet-Cookie: a=1");
  2543. EXPECT_EQ(0U, res.headers.size());
  2544. EXPECT_FALSE(res.has_header("Location"));
  2545. })
  2546. .Get("/slow",
  2547. [&](const Request & /*req*/, Response &res) {
  2548. std::this_thread::sleep_for(std::chrono::seconds(2));
  2549. res.set_content("slow", "text/plain");
  2550. })
  2551. #if 0
  2552. .Post("/slowpost",
  2553. [&](const Request & /*req*/, Response &res) {
  2554. std::this_thread::sleep_for(std::chrono::seconds(2));
  2555. res.set_content("slow", "text/plain");
  2556. })
  2557. #endif
  2558. .Get("/remote_addr",
  2559. [&](const Request &req, Response &res) {
  2560. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2561. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2562. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2563. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2564. res.set_content(req.remote_addr, "text/plain");
  2565. })
  2566. .Get("/local_addr",
  2567. [&](const Request &req, Response &res) {
  2568. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2569. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2570. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2571. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2572. auto local_addr = req.local_addr;
  2573. auto local_port = std::to_string(req.local_port);
  2574. res.set_content(local_addr.append(":").append(local_port),
  2575. "text/plain");
  2576. })
  2577. .Get("/endwith%",
  2578. [&](const Request & /*req*/, Response &res) {
  2579. res.set_content("Hello World!", "text/plain");
  2580. })
  2581. .Get("/a\\+\\+b",
  2582. [&](const Request &req, Response &res) {
  2583. ASSERT_TRUE(req.has_param("a +b"));
  2584. auto val = req.get_param_value("a +b");
  2585. res.set_content(val, "text/plain");
  2586. })
  2587. .Get("/", [&](const Request & /*req*/,
  2588. Response &res) { res.set_redirect("/hi"); })
  2589. .Post("/1",
  2590. [](const Request & /*req*/, Response &res) {
  2591. res.set_redirect("/2", StatusCode::SeeOther_303);
  2592. })
  2593. .Get("/2",
  2594. [](const Request & /*req*/, Response &res) {
  2595. res.set_content("redirected.", "text/plain");
  2596. res.status = StatusCode::OK_200;
  2597. })
  2598. .Post("/person",
  2599. [&](const Request &req, Response &res) {
  2600. if (req.has_param("name") && req.has_param("note")) {
  2601. persons_[req.get_param_value("name")] =
  2602. req.get_param_value("note");
  2603. } else {
  2604. res.status = StatusCode::BadRequest_400;
  2605. }
  2606. })
  2607. .Put("/person",
  2608. [&](const Request &req, Response &res) {
  2609. if (req.has_param("name") && req.has_param("note")) {
  2610. persons_[req.get_param_value("name")] =
  2611. req.get_param_value("note");
  2612. } else {
  2613. res.status = StatusCode::BadRequest_400;
  2614. }
  2615. })
  2616. .Get("/person/(.*)",
  2617. [&](const Request &req, Response &res) {
  2618. string name = req.matches[1];
  2619. if (persons_.find(name) != persons_.end()) {
  2620. auto note = persons_[name];
  2621. res.set_content(note, "text/plain");
  2622. } else {
  2623. res.status = StatusCode::NotFound_404;
  2624. }
  2625. })
  2626. .Delete("/person",
  2627. [&](const Request &req, Response &res) {
  2628. if (req.has_param("name")) {
  2629. string name = req.get_param_value("name");
  2630. if (persons_.find(name) != persons_.end()) {
  2631. persons_.erase(name);
  2632. res.set_content("DELETED", "text/plain");
  2633. } else {
  2634. res.status = StatusCode::NotFound_404;
  2635. }
  2636. } else {
  2637. res.status = StatusCode::BadRequest_400;
  2638. }
  2639. })
  2640. .Post("/x-www-form-urlencoded-json",
  2641. [&](const Request &req, Response &res) {
  2642. auto json = req.get_param_value("json");
  2643. ASSERT_EQ(JSON_DATA, json);
  2644. res.set_content(json, "appliation/json");
  2645. res.status = StatusCode::OK_200;
  2646. })
  2647. .Get("/streamed-chunked",
  2648. [&](const Request & /*req*/, Response &res) {
  2649. res.set_chunked_content_provider(
  2650. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2651. sink.os << "123";
  2652. sink.os << "456";
  2653. sink.os << "789";
  2654. sink.done();
  2655. return true;
  2656. });
  2657. })
  2658. .Get("/streamed-chunked-with-prohibited-trailer",
  2659. [&](const Request & /*req*/, Response &res) {
  2660. auto i = new int(0);
  2661. // Declare both a prohibited trailer (Content-Length) and an
  2662. // allowed one
  2663. res.set_header("Trailer", "Content-Length, X-Allowed");
  2664. res.set_chunked_content_provider(
  2665. "text/plain",
  2666. [i](size_t /*offset*/, DataSink &sink) {
  2667. switch (*i) {
  2668. case 0: sink.os << "123"; break;
  2669. case 1: sink.os << "456"; break;
  2670. case 2: sink.os << "789"; break;
  2671. case 3: {
  2672. sink.done_with_trailer(
  2673. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2674. } break;
  2675. }
  2676. (*i)++;
  2677. return true;
  2678. },
  2679. [i](bool success) {
  2680. EXPECT_TRUE(success);
  2681. delete i;
  2682. });
  2683. })
  2684. .Get("/streamed-chunked2",
  2685. [&](const Request & /*req*/, Response &res) {
  2686. auto i = new int(0);
  2687. res.set_chunked_content_provider(
  2688. "text/plain",
  2689. [i](size_t /*offset*/, DataSink &sink) {
  2690. switch (*i) {
  2691. case 0: sink.os << "123"; break;
  2692. case 1: sink.os << "456"; break;
  2693. case 2: sink.os << "789"; break;
  2694. case 3: sink.done(); break;
  2695. }
  2696. (*i)++;
  2697. return true;
  2698. },
  2699. [i](bool success) {
  2700. EXPECT_TRUE(success);
  2701. delete i;
  2702. });
  2703. })
  2704. .Get("/streamed-chunked-with-trailer",
  2705. [&](const Request & /*req*/, Response &res) {
  2706. auto i = new int(0);
  2707. res.set_header("Trailer", "Dummy1, Dummy2");
  2708. res.set_chunked_content_provider(
  2709. "text/plain",
  2710. [i](size_t /*offset*/, DataSink &sink) {
  2711. switch (*i) {
  2712. case 0: sink.os << "123"; break;
  2713. case 1: sink.os << "456"; break;
  2714. case 2: sink.os << "789"; break;
  2715. case 3: {
  2716. sink.done_with_trailer(
  2717. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2718. } break;
  2719. }
  2720. (*i)++;
  2721. return true;
  2722. },
  2723. [i](bool success) {
  2724. EXPECT_TRUE(success);
  2725. delete i;
  2726. });
  2727. })
  2728. .Get("/streamed",
  2729. [&](const Request & /*req*/, Response &res) {
  2730. res.set_content_provider(
  2731. 6, "text/plain",
  2732. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2733. sink.os << (offset < 3 ? "a" : "b");
  2734. return true;
  2735. });
  2736. })
  2737. .Get("/streamed-with-range",
  2738. [&](const Request &req, Response &res) {
  2739. auto data = new std::string("abcdefg");
  2740. res.set_content_provider(
  2741. data->size(), "text/plain",
  2742. [data](size_t offset, size_t length, DataSink &sink) {
  2743. size_t DATA_CHUNK_SIZE = 4;
  2744. const auto &d = *data;
  2745. auto out_len =
  2746. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2747. auto ret =
  2748. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2749. EXPECT_TRUE(ret);
  2750. return true;
  2751. },
  2752. [data, &req](bool success) {
  2753. EXPECT_EQ(success, !req.has_param("error"));
  2754. delete data;
  2755. });
  2756. })
  2757. .Get("/streamed-cancel",
  2758. [&](const Request & /*req*/, Response &res) {
  2759. res.set_content_provider(
  2760. size_t(-1), "text/plain",
  2761. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2762. sink.os << "data_chunk";
  2763. return true;
  2764. });
  2765. })
  2766. .Get("/regex-with-delimiter",
  2767. [&](const Request &req, Response & /*res*/) {
  2768. ASSERT_TRUE(req.has_param("key"));
  2769. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2770. })
  2771. .Get("/with-range",
  2772. [&](const Request & /*req*/, Response &res) {
  2773. res.set_content("abcdefg", "text/plain");
  2774. })
  2775. .Get("/test-start-time",
  2776. [&](const Request &req, Response & /*res*/) {
  2777. EXPECT_NE(req.start_time_,
  2778. std::chrono::steady_clock::time_point::min());
  2779. })
  2780. .Get("/with-range-customized-response",
  2781. [&](const Request & /*req*/, Response &res) {
  2782. res.status = StatusCode::BadRequest_400;
  2783. res.set_content(JSON_DATA, "application/json");
  2784. })
  2785. .Post("/chunked",
  2786. [&](const Request &req, Response & /*res*/) {
  2787. EXPECT_EQ(req.body, "dechunked post body");
  2788. })
  2789. .Post("/large-chunked",
  2790. [&](const Request &req, Response & /*res*/) {
  2791. std::string expected(6 * 30 * 1024u, 'a');
  2792. EXPECT_EQ(req.body, expected);
  2793. })
  2794. .Post("/multipart",
  2795. [&](const Request &req, Response & /*res*/) {
  2796. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2797. req.form.get_field_count("text2") +
  2798. req.form.get_field_count("file3") +
  2799. req.form.get_field_count("file4"));
  2800. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2801. req.form.get_file_count("file2"));
  2802. ASSERT_TRUE(!req.form.has_file("???"));
  2803. ASSERT_TRUE(!req.form.has_field("???"));
  2804. ASSERT_TRUE(req.body.empty());
  2805. {
  2806. const auto &text = req.form.get_field("text1");
  2807. EXPECT_EQ("text default", text);
  2808. }
  2809. {
  2810. const auto &text = req.form.get_field("text2");
  2811. EXPECT_EQ("aωb", text);
  2812. }
  2813. {
  2814. const auto &file = req.form.get_file("file1");
  2815. EXPECT_EQ("hello.txt", file.filename);
  2816. EXPECT_EQ("text/plain", file.content_type);
  2817. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2818. }
  2819. {
  2820. const auto &file = req.form.get_file("file2");
  2821. EXPECT_EQ("world.json", file.filename);
  2822. EXPECT_EQ("application/json", file.content_type);
  2823. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2824. }
  2825. {
  2826. const auto &text = req.form.get_field("file3");
  2827. EXPECT_EQ(0u, text.size());
  2828. }
  2829. {
  2830. const auto &text = req.form.get_field("file4");
  2831. EXPECT_EQ(0u, text.size());
  2832. }
  2833. })
  2834. .Post("/multipart/multi_file_values",
  2835. [&](const Request &req, Response & /*res*/) {
  2836. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2837. req.form.get_field_count("multi_text1"));
  2838. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2839. ASSERT_TRUE(!req.form.has_file("???"));
  2840. ASSERT_TRUE(!req.form.has_field("???"));
  2841. ASSERT_TRUE(req.body.empty());
  2842. {
  2843. const auto &text = req.form.get_field("text");
  2844. EXPECT_EQ("default text", text);
  2845. }
  2846. {
  2847. const auto &text1_values = req.form.get_fields("multi_text1");
  2848. EXPECT_EQ(2u, text1_values.size());
  2849. EXPECT_EQ("aaaaa", text1_values[0]);
  2850. EXPECT_EQ("bbbbb", text1_values[1]);
  2851. }
  2852. {
  2853. const auto &file1_values = req.form.get_files("multi_file1");
  2854. EXPECT_EQ(2u, file1_values.size());
  2855. auto file1 = file1_values[0];
  2856. EXPECT_EQ(file1.filename, "hello.txt");
  2857. EXPECT_EQ(file1.content_type, "text/plain");
  2858. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2859. auto file2 = file1_values[1];
  2860. EXPECT_EQ(file2.filename, "world.json");
  2861. EXPECT_EQ(file2.content_type, "application/json");
  2862. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2863. }
  2864. })
  2865. .Post("/empty",
  2866. [&](const Request &req, Response &res) {
  2867. EXPECT_EQ(req.body, "");
  2868. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2869. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2870. res.set_content("empty", "text/plain");
  2871. })
  2872. .Post("/empty-no-content-type",
  2873. [&](const Request &req, Response &res) {
  2874. EXPECT_EQ(req.body, "");
  2875. EXPECT_FALSE(req.has_header("Content-Type"));
  2876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2877. res.set_content("empty-no-content-type", "text/plain");
  2878. })
  2879. .Post("/path-only",
  2880. [&](const Request &req, Response &res) {
  2881. EXPECT_EQ(req.body, "");
  2882. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2883. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2884. res.set_content("path-only", "text/plain");
  2885. })
  2886. .Post("/path-headers-only",
  2887. [&](const Request &req, Response &res) {
  2888. EXPECT_EQ(req.body, "");
  2889. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2890. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2891. EXPECT_EQ("world", req.get_header_value("hello"));
  2892. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2893. res.set_content("path-headers-only", "text/plain");
  2894. })
  2895. .Post("/post-large",
  2896. [&](const Request &req, Response &res) {
  2897. EXPECT_EQ(req.body, LARGE_DATA);
  2898. res.set_content(req.body, "text/plain");
  2899. })
  2900. .Post("/post-loopback",
  2901. [&](const Request &, Response &res,
  2902. ContentReader const &content_reader) {
  2903. std::string body;
  2904. content_reader([&](const char *data, size_t data_length) {
  2905. body.append(data, data_length);
  2906. return true;
  2907. });
  2908. res.set_content(body, "text/plain");
  2909. })
  2910. .Put("/put-loopback",
  2911. [&](const Request &, Response &res,
  2912. ContentReader const &content_reader) {
  2913. std::string body;
  2914. content_reader([&](const char *data, size_t data_length) {
  2915. body.append(data, data_length);
  2916. return true;
  2917. });
  2918. res.set_content(body, "text/plain");
  2919. })
  2920. .Patch("/patch-loopback",
  2921. [&](const Request &, Response &res,
  2922. ContentReader const &content_reader) {
  2923. std::string body;
  2924. content_reader([&](const char *data, size_t data_length) {
  2925. body.append(data, data_length);
  2926. return true;
  2927. });
  2928. res.set_content(body, "text/plain");
  2929. })
  2930. .Put("/empty-no-content-type",
  2931. [&](const Request &req, Response &res) {
  2932. EXPECT_EQ(req.body, "");
  2933. EXPECT_FALSE(req.has_header("Content-Type"));
  2934. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2935. res.set_content("empty-no-content-type", "text/plain");
  2936. })
  2937. .Put("/put",
  2938. [&](const Request &req, Response &res) {
  2939. EXPECT_EQ(req.body, "PUT");
  2940. res.set_content(req.body, "text/plain");
  2941. })
  2942. .Put("/put-large",
  2943. [&](const Request &req, Response &res) {
  2944. EXPECT_EQ(req.body, LARGE_DATA);
  2945. res.set_content(req.body, "text/plain");
  2946. })
  2947. .Patch("/patch",
  2948. [&](const Request &req, Response &res) {
  2949. EXPECT_EQ(req.body, "PATCH");
  2950. res.set_content(req.body, "text/plain");
  2951. })
  2952. .Delete("/delete",
  2953. [&](const Request & /*req*/, Response &res) {
  2954. res.set_content("DELETE", "text/plain");
  2955. })
  2956. .Delete("/delete-body",
  2957. [&](const Request &req, Response &res) {
  2958. EXPECT_EQ(req.body, "content");
  2959. res.set_content(req.body, "text/plain");
  2960. })
  2961. .Options(R"(\*)",
  2962. [&](const Request & /*req*/, Response &res) {
  2963. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2964. })
  2965. .Get("/request-target",
  2966. [&](const Request &req, Response & /*res*/) {
  2967. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2968. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2969. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2970. })
  2971. .Get("/long-query-value",
  2972. [&](const Request &req, Response & /*res*/) {
  2973. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2974. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2975. })
  2976. .Get("/too-long-query-value",
  2977. [&](const Request &req, Response & /*res*/) {
  2978. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2979. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2980. })
  2981. .Get("/array-param",
  2982. [&](const Request &req, Response & /*res*/) {
  2983. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2984. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2985. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2986. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2987. })
  2988. .Post("/validate-no-multiple-headers",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2991. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2992. })
  2993. .Post("/content_receiver",
  2994. [&](const Request &req, Response &res,
  2995. const ContentReader &content_reader) {
  2996. if (req.is_multipart_form_data()) {
  2997. std::vector<FormData> items;
  2998. content_reader(
  2999. [&](const FormData &file) {
  3000. items.push_back(file);
  3001. return true;
  3002. },
  3003. [&](const char *data, size_t data_length) {
  3004. items.back().content.append(data, data_length);
  3005. return true;
  3006. });
  3007. EXPECT_EQ(5u, items.size());
  3008. {
  3009. const auto &file = get_file_value(items, "text1");
  3010. EXPECT_TRUE(file.filename.empty());
  3011. EXPECT_EQ("text default", file.content);
  3012. }
  3013. {
  3014. const auto &file = get_file_value(items, "text2");
  3015. EXPECT_TRUE(file.filename.empty());
  3016. EXPECT_EQ("aωb", file.content);
  3017. }
  3018. {
  3019. const auto &file = get_file_value(items, "file1");
  3020. EXPECT_EQ("hello.txt", file.filename);
  3021. EXPECT_EQ("text/plain", file.content_type);
  3022. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3023. }
  3024. {
  3025. const auto &file = get_file_value(items, "file2");
  3026. EXPECT_EQ("world.json", file.filename);
  3027. EXPECT_EQ("application/json", file.content_type);
  3028. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3029. }
  3030. {
  3031. const auto &file = get_file_value(items, "file3");
  3032. EXPECT_TRUE(file.filename.empty());
  3033. EXPECT_EQ("application/octet-stream", file.content_type);
  3034. EXPECT_EQ(0u, file.content.size());
  3035. }
  3036. } else {
  3037. std::string body;
  3038. content_reader([&](const char *data, size_t data_length) {
  3039. EXPECT_EQ(7U, data_length);
  3040. body.append(data, data_length);
  3041. return true;
  3042. });
  3043. EXPECT_EQ(body, "content");
  3044. res.set_content(body, "text/plain");
  3045. }
  3046. })
  3047. .Put("/content_receiver",
  3048. [&](const Request & /*req*/, Response &res,
  3049. const ContentReader &content_reader) {
  3050. std::string body;
  3051. content_reader([&](const char *data, size_t data_length) {
  3052. body.append(data, data_length);
  3053. return true;
  3054. });
  3055. EXPECT_EQ(body, "content");
  3056. res.set_content(body, "text/plain");
  3057. })
  3058. .Patch("/content_receiver",
  3059. [&](const Request & /*req*/, Response &res,
  3060. const ContentReader &content_reader) {
  3061. std::string body;
  3062. content_reader([&](const char *data, size_t data_length) {
  3063. body.append(data, data_length);
  3064. return true;
  3065. });
  3066. EXPECT_EQ(body, "content");
  3067. res.set_content(body, "text/plain");
  3068. })
  3069. .Post("/query-string-and-body",
  3070. [&](const Request &req, Response & /*res*/) {
  3071. ASSERT_TRUE(req.has_param("key"));
  3072. EXPECT_EQ(req.get_param_value("key"), "value");
  3073. EXPECT_EQ(req.body, "content");
  3074. })
  3075. .Get("/last-request",
  3076. [&](const Request &req, Response & /*res*/) {
  3077. EXPECT_EQ("close", req.get_header_value("Connection"));
  3078. })
  3079. .Get(R"(/redirect/(\d+))",
  3080. [&](const Request &req, Response &res) {
  3081. auto num = std::stoi(req.matches[1]) + 1;
  3082. std::string url = "/redirect/" + std::to_string(num);
  3083. res.set_redirect(url);
  3084. })
  3085. .Post("/binary",
  3086. [&](const Request &req, Response &res) {
  3087. EXPECT_EQ(4U, req.body.size());
  3088. EXPECT_EQ("application/octet-stream",
  3089. req.get_header_value("Content-Type"));
  3090. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3091. res.set_content(req.body, "application/octet-stream");
  3092. })
  3093. .Put("/binary",
  3094. [&](const Request &req, Response &res) {
  3095. EXPECT_EQ(4U, req.body.size());
  3096. EXPECT_EQ("application/octet-stream",
  3097. req.get_header_value("Content-Type"));
  3098. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3099. res.set_content(req.body, "application/octet-stream");
  3100. })
  3101. .Patch("/binary",
  3102. [&](const Request &req, Response &res) {
  3103. EXPECT_EQ(4U, req.body.size());
  3104. EXPECT_EQ("application/octet-stream",
  3105. req.get_header_value("Content-Type"));
  3106. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3107. res.set_content(req.body, "application/octet-stream");
  3108. })
  3109. .Delete("/binary",
  3110. [&](const Request &req, Response &res) {
  3111. EXPECT_EQ(4U, req.body.size());
  3112. EXPECT_EQ("application/octet-stream",
  3113. req.get_header_value("Content-Type"));
  3114. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3115. res.set_content(req.body, "application/octet-stream");
  3116. })
  3117. .Get("/issue1772",
  3118. [&](const Request & /*req*/, Response &res) {
  3119. res.status = 401;
  3120. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3121. })
  3122. .Delete("/issue609",
  3123. [](const httplib::Request &, httplib::Response &res,
  3124. const httplib::ContentReader &) {
  3125. res.set_content("ok", "text/plain");
  3126. })
  3127. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3128. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3129. .Get("/compress",
  3130. [&](const Request & /*req*/, Response &res) {
  3131. res.set_content(
  3132. "12345678901234567890123456789012345678901234567890123456789"
  3133. "01234567890123456789012345678901234567890",
  3134. "text/plain");
  3135. })
  3136. .Get("/nocompress",
  3137. [&](const Request & /*req*/, Response &res) {
  3138. res.set_content(
  3139. "12345678901234567890123456789012345678901234567890123456789"
  3140. "01234567890123456789012345678901234567890",
  3141. "application/octet-stream");
  3142. })
  3143. .Post("/compress-multipart",
  3144. [&](const Request &req, Response & /*res*/) {
  3145. EXPECT_EQ(2u, req.form.fields.size());
  3146. ASSERT_TRUE(!req.form.has_field("???"));
  3147. {
  3148. const auto &text = req.form.get_field("key1");
  3149. EXPECT_EQ("test", text);
  3150. }
  3151. {
  3152. const auto &text = req.form.get_field("key2");
  3153. EXPECT_EQ("--abcdefg123", text);
  3154. }
  3155. })
  3156. #endif
  3157. ;
  3158. persons_["john"] = "programmer";
  3159. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3160. svr_.wait_until_ready();
  3161. }
  3162. virtual void TearDown() {
  3163. svr_.stop();
  3164. if (!request_threads_.empty()) {
  3165. std::this_thread::sleep_for(std::chrono::seconds(1));
  3166. for (auto &t : request_threads_) {
  3167. t.join();
  3168. }
  3169. }
  3170. t_.join();
  3171. }
  3172. map<string, string> persons_;
  3173. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3174. SSLClient cli_;
  3175. SSLServer svr_;
  3176. #else
  3177. Client cli_;
  3178. Server svr_;
  3179. #endif
  3180. thread t_;
  3181. std::vector<thread> request_threads_;
  3182. };
  3183. TEST_F(ServerTest, GetMethod200) {
  3184. auto res = cli_.Get("/hi");
  3185. ASSERT_TRUE(res);
  3186. EXPECT_EQ("HTTP/1.1", res->version);
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. EXPECT_EQ("OK", res->reason);
  3189. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3190. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3191. EXPECT_EQ("Hello World!", res->body);
  3192. }
  3193. TEST_F(ServerTest, GetEmptyFile) {
  3194. auto res = cli_.Get("/empty_file");
  3195. ASSERT_TRUE(res);
  3196. EXPECT_EQ(StatusCode::OK_200, res->status);
  3197. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3198. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3199. EXPECT_EQ("", res->body);
  3200. }
  3201. TEST_F(ServerTest, GetFileContent) {
  3202. auto res = cli_.Get("/file_content");
  3203. ASSERT_TRUE(res);
  3204. EXPECT_EQ(StatusCode::OK_200, res->status);
  3205. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3206. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3207. EXPECT_EQ("test.html", res->body);
  3208. }
  3209. TEST_F(ServerTest, GetFileContentWithRange) {
  3210. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3211. ASSERT_TRUE(res);
  3212. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3214. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3215. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3216. EXPECT_EQ("est", res->body);
  3217. }
  3218. TEST_F(ServerTest, GetFileContentWithContentType) {
  3219. auto res = cli_.Get("/file_content_with_content_type");
  3220. ASSERT_TRUE(res);
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3223. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3224. EXPECT_EQ("file\n", res->body);
  3225. }
  3226. TEST_F(ServerTest, GetInvalidFileContent) {
  3227. auto res = cli_.Get("/invalid_file_content");
  3228. ASSERT_TRUE(res);
  3229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3230. }
  3231. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3232. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ("HTTP/1.1", res->version);
  3235. EXPECT_EQ(StatusCode::OK_200, res->status);
  3236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3237. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3238. EXPECT_EQ("Hello World!", res->body);
  3239. }
  3240. TEST_F(ServerTest, GetMethod302) {
  3241. auto res = cli_.Get("/");
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::Found_302, res->status);
  3244. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3245. }
  3246. TEST_F(ServerTest, GetMethod302Redirect) {
  3247. cli_.set_follow_location(true);
  3248. auto res = cli_.Get("/");
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::OK_200, res->status);
  3251. EXPECT_EQ("Hello World!", res->body);
  3252. EXPECT_EQ("/hi", res->location);
  3253. }
  3254. TEST_F(ServerTest, GetMethod404) {
  3255. auto res = cli_.Get("/invalid");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3258. }
  3259. TEST_F(ServerTest, HeadMethod200) {
  3260. auto res = cli_.Head("/hi");
  3261. ASSERT_TRUE(res);
  3262. EXPECT_EQ(StatusCode::OK_200, res->status);
  3263. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3264. EXPECT_TRUE(res->body.empty());
  3265. }
  3266. TEST_F(ServerTest, HeadMethod200Static) {
  3267. auto res = cli_.Head("/mount/dir/index.html");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3271. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3272. EXPECT_TRUE(res->body.empty());
  3273. }
  3274. TEST_F(ServerTest, HeadMethod404) {
  3275. auto res = cli_.Head("/invalid");
  3276. ASSERT_TRUE(res);
  3277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3278. EXPECT_TRUE(res->body.empty());
  3279. }
  3280. TEST_F(ServerTest, GetMethodPersonJohn) {
  3281. auto res = cli_.Get("/person/john");
  3282. ASSERT_TRUE(res);
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3285. EXPECT_EQ("programmer", res->body);
  3286. }
  3287. TEST_F(ServerTest, PostMethod1) {
  3288. auto res = cli_.Get("/person/john1");
  3289. ASSERT_TRUE(res);
  3290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3291. res = cli_.Post("/person", "name=john1&note=coder",
  3292. "application/x-www-form-urlencoded");
  3293. ASSERT_TRUE(res);
  3294. ASSERT_EQ(StatusCode::OK_200, res->status);
  3295. res = cli_.Get("/person/john1");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::OK_200, res->status);
  3298. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3299. ASSERT_EQ("coder", res->body);
  3300. }
  3301. TEST_F(ServerTest, PostMethod2) {
  3302. auto res = cli_.Get("/person/john2");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3305. Params params;
  3306. params.emplace("name", "john2");
  3307. params.emplace("note", "coder");
  3308. res = cli_.Post("/person", params);
  3309. ASSERT_TRUE(res);
  3310. ASSERT_EQ(StatusCode::OK_200, res->status);
  3311. res = cli_.Get("/person/john2");
  3312. ASSERT_TRUE(res);
  3313. ASSERT_EQ(StatusCode::OK_200, res->status);
  3314. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3315. ASSERT_EQ("coder", res->body);
  3316. }
  3317. TEST_F(ServerTest, PutMethod3) {
  3318. auto res = cli_.Get("/person/john3");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3321. Params params;
  3322. params.emplace("name", "john3");
  3323. params.emplace("note", "coder");
  3324. res = cli_.Put("/person", params);
  3325. ASSERT_TRUE(res);
  3326. ASSERT_EQ(StatusCode::OK_200, res->status);
  3327. res = cli_.Get("/person/john3");
  3328. ASSERT_TRUE(res);
  3329. ASSERT_EQ(StatusCode::OK_200, res->status);
  3330. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3331. ASSERT_EQ("coder", res->body);
  3332. }
  3333. TEST_F(ServerTest, DeleteMethod1) {
  3334. auto res = cli_.Get("/person/john4");
  3335. ASSERT_TRUE(res);
  3336. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3337. Params params;
  3338. params.emplace("name", "john4");
  3339. params.emplace("note", "coder");
  3340. res = cli_.Post("/person", params);
  3341. ASSERT_TRUE(res);
  3342. ASSERT_EQ(StatusCode::OK_200, res->status);
  3343. res = cli_.Get("/person/john4");
  3344. ASSERT_TRUE(res);
  3345. ASSERT_EQ(StatusCode::OK_200, res->status);
  3346. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3347. ASSERT_EQ("coder", res->body);
  3348. Params delete_params;
  3349. delete_params.emplace("name", "john4");
  3350. res = cli_.Delete("/person", delete_params);
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ("DELETED", res->body);
  3354. res = cli_.Get("/person/john4");
  3355. ASSERT_TRUE(res);
  3356. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3357. }
  3358. TEST_F(ServerTest, DeleteMethod2) {
  3359. auto res = cli_.Get("/person/john5");
  3360. ASSERT_TRUE(res);
  3361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3362. Params params;
  3363. params.emplace("name", "john5");
  3364. params.emplace("note", "developer");
  3365. res = cli_.Post("/person", params);
  3366. ASSERT_TRUE(res);
  3367. ASSERT_EQ(StatusCode::OK_200, res->status);
  3368. res = cli_.Get("/person/john5");
  3369. ASSERT_TRUE(res);
  3370. ASSERT_EQ(StatusCode::OK_200, res->status);
  3371. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3372. ASSERT_EQ("developer", res->body);
  3373. Params delete_params;
  3374. delete_params.emplace("name", "john5");
  3375. Headers headers;
  3376. headers.emplace("Custom-Header", "test-value");
  3377. res = cli_.Delete("/person", headers, delete_params);
  3378. ASSERT_TRUE(res);
  3379. ASSERT_EQ(StatusCode::OK_200, res->status);
  3380. ASSERT_EQ("DELETED", res->body);
  3381. res = cli_.Get("/person/john5");
  3382. ASSERT_TRUE(res);
  3383. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3384. }
  3385. TEST_F(ServerTest, DeleteMethod3) {
  3386. auto res = cli_.Get("/person/john6");
  3387. ASSERT_TRUE(res);
  3388. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3389. Params params;
  3390. params.emplace("name", "john6");
  3391. params.emplace("note", "tester");
  3392. res = cli_.Post("/person", params);
  3393. ASSERT_TRUE(res);
  3394. ASSERT_EQ(StatusCode::OK_200, res->status);
  3395. res = cli_.Get("/person/john6");
  3396. ASSERT_TRUE(res);
  3397. ASSERT_EQ(StatusCode::OK_200, res->status);
  3398. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3399. ASSERT_EQ("tester", res->body);
  3400. Params delete_params;
  3401. delete_params.emplace("name", "john6");
  3402. Headers headers;
  3403. headers.emplace("Custom-Header", "test-value");
  3404. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3405. ASSERT_TRUE(res);
  3406. ASSERT_EQ(StatusCode::OK_200, res->status);
  3407. ASSERT_EQ("DELETED", res->body);
  3408. res = cli_.Get("/person/john6");
  3409. ASSERT_TRUE(res);
  3410. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3411. }
  3412. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3413. Params params;
  3414. params.emplace("json", JSON_DATA);
  3415. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3416. ASSERT_TRUE(res);
  3417. ASSERT_EQ(StatusCode::OK_200, res->status);
  3418. ASSERT_EQ(JSON_DATA, res->body);
  3419. }
  3420. TEST_F(ServerTest, PostEmptyContent) {
  3421. auto res = cli_.Post("/empty", "", "text/plain");
  3422. ASSERT_TRUE(res);
  3423. ASSERT_EQ(StatusCode::OK_200, res->status);
  3424. ASSERT_EQ("empty", res->body);
  3425. }
  3426. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3427. auto res = cli_.Post("/empty-no-content-type");
  3428. ASSERT_TRUE(res);
  3429. ASSERT_EQ(StatusCode::OK_200, res->status);
  3430. ASSERT_EQ("empty-no-content-type", res->body);
  3431. }
  3432. TEST_F(ServerTest, PostPathOnly) {
  3433. auto res = cli_.Post("/path-only");
  3434. ASSERT_TRUE(res);
  3435. ASSERT_EQ(StatusCode::OK_200, res->status);
  3436. ASSERT_EQ("path-only", res->body);
  3437. }
  3438. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3439. auto res = cli_.Post("/path-headers-only",
  3440. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. ASSERT_EQ("path-headers-only", res->body);
  3444. }
  3445. TEST_F(ServerTest, PostLarge) {
  3446. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3447. ASSERT_TRUE(res);
  3448. ASSERT_EQ(StatusCode::OK_200, res->status);
  3449. EXPECT_EQ(LARGE_DATA, res->body);
  3450. }
  3451. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3452. auto res = cli_.Put("/empty-no-content-type");
  3453. ASSERT_TRUE(res);
  3454. ASSERT_EQ(StatusCode::OK_200, res->status);
  3455. ASSERT_EQ("empty-no-content-type", res->body);
  3456. }
  3457. TEST_F(ServerTest, GetMethodDir) {
  3458. auto res = cli_.Get("/dir/");
  3459. ASSERT_TRUE(res);
  3460. EXPECT_EQ(StatusCode::OK_200, res->status);
  3461. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3462. auto body = R"(<html>
  3463. <head>
  3464. </head>
  3465. <body>
  3466. <a href="/dir/test.html">Test</a>
  3467. <a href="/hi">hi</a>
  3468. </body>
  3469. </html>
  3470. )";
  3471. EXPECT_EQ(body, res->body);
  3472. }
  3473. TEST_F(ServerTest, GetMethodDirTest) {
  3474. auto res = cli_.Get("/dir/test.html");
  3475. ASSERT_TRUE(res);
  3476. EXPECT_EQ(StatusCode::OK_200, res->status);
  3477. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3478. EXPECT_EQ("test.html", res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3481. auto res = cli_.Get("/dir/../dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodInvalidPath) {
  3488. auto res = cli_.Get("/dir/../test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3491. }
  3492. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3493. auto res = cli_.Get("/../www/dir/test.html");
  3494. ASSERT_TRUE(res);
  3495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3496. }
  3497. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3498. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3501. }
  3502. TEST_F(ServerTest, GetMethodDirMountTest) {
  3503. auto res = cli_.Get("/mount/dir/test.html");
  3504. ASSERT_TRUE(res);
  3505. EXPECT_EQ(StatusCode::OK_200, res->status);
  3506. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3507. EXPECT_EQ("test.html", res->body);
  3508. }
  3509. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3510. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("test.html", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3517. auto res = cli_.Get("/mount/dir/../test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3520. }
  3521. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3522. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3523. ASSERT_TRUE(res);
  3524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3525. }
  3526. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3527. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3530. }
  3531. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3532. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3535. }
  3536. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3537. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3538. ASSERT_TRUE(res);
  3539. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3540. }
  3541. TEST_F(ServerTest, PostMethod303) {
  3542. auto res = cli_.Post("/1", "body", "text/plain");
  3543. ASSERT_TRUE(res);
  3544. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3545. EXPECT_EQ("/2", res->get_header_value("Location"));
  3546. }
  3547. TEST_F(ServerTest, PostMethod303Redirect) {
  3548. cli_.set_follow_location(true);
  3549. auto res = cli_.Post("/1", "body", "text/plain");
  3550. ASSERT_TRUE(res);
  3551. EXPECT_EQ(StatusCode::OK_200, res->status);
  3552. EXPECT_EQ("redirected.", res->body);
  3553. EXPECT_EQ("/2", res->location);
  3554. }
  3555. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3556. auto res = cli_.Get("/dir/test.abcde");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3560. EXPECT_EQ("abcde", res->body);
  3561. }
  3562. TEST_F(ServerTest, StaticFileRange) {
  3563. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3564. ASSERT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3566. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3567. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3568. EXPECT_EQ(true, res->has_header("Content-Range"));
  3569. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3570. EXPECT_EQ(std::string("cd"), res->body);
  3571. }
  3572. TEST_F(ServerTest, StaticFileRanges) {
  3573. auto res =
  3574. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3575. ASSERT_TRUE(res);
  3576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3577. EXPECT_TRUE(
  3578. res->get_header_value("Content-Type")
  3579. .find(
  3580. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3581. 0);
  3582. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3583. }
  3584. TEST_F(ServerTest, StaticFileRangeHead) {
  3585. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3588. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3589. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3590. EXPECT_EQ(true, res->has_header("Content-Range"));
  3591. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3592. }
  3593. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3594. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3595. ASSERT_TRUE(res);
  3596. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3598. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3599. EXPECT_EQ(true, res->has_header("Content-Range"));
  3600. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3601. res->get_header_value("Content-Range"));
  3602. EXPECT_EQ("LAST\n", res->body);
  3603. }
  3604. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3605. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3606. ASSERT_TRUE(res);
  3607. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3608. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3609. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3610. EXPECT_EQ(true, res->has_header("Content-Range"));
  3611. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3612. }
  3613. TEST_F(ServerTest, StaticFileBigFile) {
  3614. auto res = cli_.Get("/dir/1MB.txt");
  3615. ASSERT_TRUE(res);
  3616. EXPECT_EQ(StatusCode::OK_200, res->status);
  3617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3618. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3619. }
  3620. TEST_F(ServerTest, InvalidBaseDirMount) {
  3621. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3622. }
  3623. TEST_F(ServerTest, Binary) {
  3624. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3625. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3626. "application/octet-stream");
  3627. ASSERT_TRUE(res);
  3628. ASSERT_EQ(StatusCode::OK_200, res->status);
  3629. ASSERT_EQ(4U, res->body.size());
  3630. res = cli_.Put("/binary", binary.data(), binary.size(),
  3631. "application/octet-stream");
  3632. ASSERT_TRUE(res);
  3633. ASSERT_EQ(StatusCode::OK_200, res->status);
  3634. ASSERT_EQ(4U, res->body.size());
  3635. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3636. "application/octet-stream");
  3637. ASSERT_TRUE(res);
  3638. ASSERT_EQ(StatusCode::OK_200, res->status);
  3639. ASSERT_EQ(4U, res->body.size());
  3640. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3641. "application/octet-stream");
  3642. ASSERT_TRUE(res);
  3643. ASSERT_EQ(StatusCode::OK_200, res->status);
  3644. ASSERT_EQ(4U, res->body.size());
  3645. }
  3646. TEST_F(ServerTest, BinaryString) {
  3647. auto binary = std::string("\x00\x01\x02\x03", 4);
  3648. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ(4U, res->body.size());
  3652. res = cli_.Put("/binary", binary, "application/octet-stream");
  3653. ASSERT_TRUE(res);
  3654. ASSERT_EQ(StatusCode::OK_200, res->status);
  3655. ASSERT_EQ(4U, res->body.size());
  3656. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3657. ASSERT_TRUE(res);
  3658. ASSERT_EQ(StatusCode::OK_200, res->status);
  3659. ASSERT_EQ(4U, res->body.size());
  3660. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3661. ASSERT_TRUE(res);
  3662. ASSERT_EQ(StatusCode::OK_200, res->status);
  3663. ASSERT_EQ(4U, res->body.size());
  3664. }
  3665. TEST_F(ServerTest, EmptyRequest) {
  3666. auto res = cli_.Get("");
  3667. ASSERT_TRUE(!res);
  3668. EXPECT_EQ(Error::Connection, res.error());
  3669. }
  3670. TEST_F(ServerTest, LongRequest) {
  3671. std::string request;
  3672. for (size_t i = 0; i < 545; i++) {
  3673. request += "/TooLongRequest";
  3674. }
  3675. request += "OK";
  3676. auto res = cli_.Get(request.c_str());
  3677. ASSERT_TRUE(res);
  3678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3679. }
  3680. TEST_F(ServerTest, TooLongRequest) {
  3681. std::string request;
  3682. for (size_t i = 0; i < 546; i++) {
  3683. request += "/TooLongRequest";
  3684. }
  3685. request += "_NG";
  3686. auto start = std::chrono::high_resolution_clock::now();
  3687. cli_.set_keep_alive(true);
  3688. auto res = cli_.Get(request.c_str());
  3689. auto end = std::chrono::high_resolution_clock::now();
  3690. auto elapsed =
  3691. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3692. .count();
  3693. ASSERT_TRUE(res);
  3694. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3695. EXPECT_LE(elapsed, 100);
  3696. EXPECT_EQ("close", res->get_header_value("Connection"));
  3697. EXPECT_FALSE(cli_.is_socket_open());
  3698. }
  3699. TEST_F(ServerTest, AlmostTooLongRequest) {
  3700. // test for #2046 - URI length check shouldn't include other content on req
  3701. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3702. // leading /, space, HTTP/1.1)
  3703. std::string request =
  3704. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3705. auto res = cli_.Get(request.c_str());
  3706. ASSERT_TRUE(res);
  3707. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3708. }
  3709. TEST_F(ServerTest, LongHeader) {
  3710. Request req;
  3711. req.method = "GET";
  3712. req.path = "/hi";
  3713. std::string host_and_port;
  3714. host_and_port += HOST;
  3715. host_and_port += ":";
  3716. host_and_port += std::to_string(PORT);
  3717. req.headers.emplace("Host", host_and_port.c_str());
  3718. req.headers.emplace("Accept", "*/*");
  3719. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3720. req.headers.emplace(
  3721. "Header-Name",
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@");
  3751. auto res = std::make_shared<Response>();
  3752. auto error = Error::Success;
  3753. auto ret = cli_.send(req, *res, error);
  3754. ASSERT_TRUE(ret);
  3755. EXPECT_EQ(StatusCode::OK_200, res->status);
  3756. }
  3757. TEST_F(ServerTest, LongQueryValue) {
  3758. auto start = std::chrono::high_resolution_clock::now();
  3759. cli_.set_keep_alive(true);
  3760. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3761. auto end = std::chrono::high_resolution_clock::now();
  3762. auto elapsed =
  3763. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3764. .count();
  3765. ASSERT_TRUE(res);
  3766. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3767. EXPECT_LE(elapsed, 100);
  3768. EXPECT_EQ("close", res->get_header_value("Connection"));
  3769. EXPECT_FALSE(cli_.is_socket_open());
  3770. }
  3771. TEST_F(ServerTest, TooLongQueryValue) {
  3772. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3773. ASSERT_FALSE(res);
  3774. EXPECT_EQ(Error::Read, res.error());
  3775. }
  3776. TEST_F(ServerTest, TooLongHeader) {
  3777. Request req;
  3778. req.method = "GET";
  3779. req.path = "/hi";
  3780. std::string host_and_port;
  3781. host_and_port += HOST;
  3782. host_and_port += ":";
  3783. host_and_port += std::to_string(PORT);
  3784. req.headers.emplace("Host", host_and_port.c_str());
  3785. req.headers.emplace("Accept", "*/*");
  3786. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3787. req.headers.emplace(
  3788. "Header-Name",
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  3819. auto error = Error::Success;
  3820. auto ret = cli_.send(req, *res, error);
  3821. ASSERT_TRUE(ret);
  3822. EXPECT_EQ(StatusCode::OK_200, res->status);
  3823. }
  3824. TEST_F(ServerTest, HeaderCountAtLimit) {
  3825. // Test with headers just under the 100 limit
  3826. httplib::Headers headers;
  3827. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3828. // This should keep us just under the 100 header limit
  3829. for (int i = 0; i < 95; i++) {
  3830. std::string name = "X-Test-Header-" + std::to_string(i);
  3831. std::string value = "value" + std::to_string(i);
  3832. headers.emplace(name, value);
  3833. }
  3834. // This should work fine as we're under the limit
  3835. auto res = cli_.Get("/hi", headers);
  3836. EXPECT_TRUE(res);
  3837. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3838. }
  3839. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3840. // Test with many headers to exceed the 100 limit
  3841. httplib::Headers headers;
  3842. // Add 150 headers to definitely exceed the 100 limit
  3843. for (int i = 0; i < 150; i++) {
  3844. std::string name = "X-Test-Header-" + std::to_string(i);
  3845. std::string value = "value" + std::to_string(i);
  3846. headers.emplace(name, value);
  3847. }
  3848. // This should fail due to exceeding header count limit
  3849. cli_.set_keep_alive(true);
  3850. auto res = cli_.Get("/hi", headers);
  3851. // The request should either fail or return 400 Bad Request
  3852. if (res) {
  3853. // If we get a response, it should be 400 Bad Request
  3854. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3855. } else {
  3856. // Or the request should fail entirely
  3857. EXPECT_FALSE(res);
  3858. }
  3859. EXPECT_EQ("close", res->get_header_value("Connection"));
  3860. EXPECT_FALSE(cli_.is_socket_open());
  3861. }
  3862. TEST_F(ServerTest, PercentEncoding) {
  3863. auto res = cli_.Get("/e%6edwith%");
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ(StatusCode::OK_200, res->status);
  3866. }
  3867. TEST_F(ServerTest, PercentEncodingUnicode) {
  3868. auto res = cli_.Get("/e%u006edwith%");
  3869. ASSERT_TRUE(res);
  3870. EXPECT_EQ(StatusCode::OK_200, res->status);
  3871. }
  3872. TEST_F(ServerTest, InvalidPercentEncoding) {
  3873. auto res = cli_.Get("/%endwith%");
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3876. }
  3877. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3878. auto res = cli_.Get("/%uendwith%");
  3879. ASSERT_TRUE(res);
  3880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3881. }
  3882. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3883. auto res = cli_.Get("/hello?aaa=bbb%");
  3884. ASSERT_TRUE(res);
  3885. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3886. }
  3887. TEST_F(ServerTest, PlusSignEncoding) {
  3888. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3889. ASSERT_TRUE(res);
  3890. EXPECT_EQ(StatusCode::OK_200, res->status);
  3891. EXPECT_EQ("a +b", res->body);
  3892. }
  3893. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3894. // This test simulates a potential DoS attack using many headers
  3895. // to verify our security fix prevents memory exhaustion
  3896. httplib::Headers attack_headers;
  3897. // Attempt to add many headers like an attacker would (200 headers to far
  3898. // exceed limit)
  3899. for (int i = 0; i < 200; i++) {
  3900. std::string name = "X-Attack-Header-" + std::to_string(i);
  3901. std::string value = "attack_payload_" + std::to_string(i);
  3902. attack_headers.emplace(name, value);
  3903. }
  3904. // Try to POST with excessive headers
  3905. cli_.set_keep_alive(true);
  3906. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3907. // Should either fail or return 400 Bad Request due to security limit
  3908. if (res) {
  3909. // If we get a response, it should be 400 Bad Request
  3910. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3911. } else {
  3912. // Request failed, which is the expected behavior for DoS protection
  3913. EXPECT_FALSE(res);
  3914. }
  3915. EXPECT_EQ("close", res->get_header_value("Connection"));
  3916. EXPECT_FALSE(cli_.is_socket_open());
  3917. }
  3918. TEST_F(ServerTest, MultipartFormData) {
  3919. UploadFormDataItems items = {
  3920. {"text1", "text default", "", ""},
  3921. {"text2", "aωb", "", ""},
  3922. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3923. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3924. {"file3", "", "", "application/octet-stream"},
  3925. {"file4", "", "", " application/json tmp-string "}};
  3926. auto res = cli_.Post("/multipart", items);
  3927. ASSERT_TRUE(res);
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3931. UploadFormDataItems items = {
  3932. {"text", "default text", "", ""},
  3933. {"multi_text1", "aaaaa", "", ""},
  3934. {"multi_text1", "bbbbb", "", ""},
  3935. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3936. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3937. "application/json"},
  3938. };
  3939. auto res = cli_.Post("/multipart/multi_file_values", items);
  3940. ASSERT_TRUE(res);
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. }
  3943. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3944. auto res = cli_.Get("/hi");
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3948. EXPECT_EQ("Hello World!", res->body);
  3949. }
  3950. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3951. Request req;
  3952. req.method = "POST";
  3953. req.path = "/chunked";
  3954. std::string host_and_port;
  3955. host_and_port += HOST;
  3956. host_and_port += ":";
  3957. host_and_port += std::to_string(PORT);
  3958. req.headers.emplace("Host", host_and_port.c_str());
  3959. req.headers.emplace("Accept", "*/*");
  3960. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3961. req.headers.emplace("Content-Type", "text/plain");
  3962. req.headers.emplace("Content-Length", "0");
  3963. req.headers.emplace(
  3964. "Transfer-Encoding",
  3965. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3966. // Client does not chunk, so make a chunked body manually.
  3967. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3968. auto res = std::make_shared<Response>();
  3969. auto error = Error::Success;
  3970. auto ret = cli_.send(req, *res, error);
  3971. ASSERT_TRUE(ret);
  3972. EXPECT_EQ(StatusCode::OK_200, res->status);
  3973. }
  3974. TEST_F(ServerTest, GetStreamed2) {
  3975. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3976. ASSERT_TRUE(res);
  3977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3978. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3979. EXPECT_EQ(true, res->has_header("Content-Range"));
  3980. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3981. EXPECT_EQ(std::string("ab"), res->body);
  3982. }
  3983. TEST_F(ServerTest, GetStreamed) {
  3984. auto res = cli_.Get("/streamed");
  3985. ASSERT_TRUE(res);
  3986. EXPECT_EQ(StatusCode::OK_200, res->status);
  3987. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3988. EXPECT_EQ(std::string("aaabbb"), res->body);
  3989. }
  3990. TEST_F(ServerTest, GetStreamedWithRange1) {
  3991. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3994. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3995. EXPECT_EQ(true, res->has_header("Content-Range"));
  3996. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3997. EXPECT_EQ(std::string("def"), res->body);
  3998. }
  3999. TEST_F(ServerTest, GetStreamedWithRange2) {
  4000. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4001. ASSERT_TRUE(res);
  4002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4003. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4004. EXPECT_EQ(true, res->has_header("Content-Range"));
  4005. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4006. EXPECT_EQ(std::string("bcdefg"), res->body);
  4007. }
  4008. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4009. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4010. ASSERT_TRUE(res);
  4011. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4012. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4013. EXPECT_EQ(true, res->has_header("Content-Range"));
  4014. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4015. EXPECT_EQ(std::string("efg"), res->body);
  4016. }
  4017. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4018. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4019. ASSERT_TRUE(res);
  4020. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4021. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4022. EXPECT_EQ(false, res->has_header("Content-Range"));
  4023. EXPECT_EQ(0U, res->body.size());
  4024. }
  4025. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4026. auto res = cli_.Get("/streamed-with-range",
  4027. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4028. "92233720368547758079223372036854775807"}});
  4029. ASSERT_TRUE(res);
  4030. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4031. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4032. EXPECT_EQ(false, res->has_header("Content-Range"));
  4033. EXPECT_EQ(0U, res->body.size());
  4034. }
  4035. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4036. auto res = cli_.Get(
  4037. "/with-range",
  4038. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4039. {"Accept-Encoding", ""}});
  4040. ASSERT_TRUE(res);
  4041. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4042. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4043. EXPECT_EQ(true, res->has_header("Content-Range"));
  4044. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4045. EXPECT_EQ(std::string("abcdefg"), res->body);
  4046. }
  4047. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4048. auto res = cli_.Get("/with-range", {
  4049. {"Range", "bytes=0-"},
  4050. {"Accept-Encoding", ""},
  4051. });
  4052. ASSERT_TRUE(res);
  4053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4054. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4055. EXPECT_EQ(true, res->has_header("Content-Range"));
  4056. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4057. EXPECT_EQ(std::string("abcdefg"), res->body);
  4058. }
  4059. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4060. auto res =
  4061. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4062. ASSERT_TRUE(res);
  4063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4064. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4065. EXPECT_EQ(false, res->has_header("Content-Range"));
  4066. EXPECT_EQ(267U, res->body.size());
  4067. // Check that both range contents are present
  4068. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4069. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4070. // Check that Content-Range headers are present for both ranges
  4071. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4072. std::string::npos);
  4073. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4074. std::string::npos);
  4075. }
  4076. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4077. Ranges ranges;
  4078. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4079. ranges.emplace_back(0, -1);
  4080. }
  4081. auto res =
  4082. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4083. ASSERT_TRUE(res);
  4084. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4085. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4086. EXPECT_EQ(false, res->has_header("Content-Range"));
  4087. EXPECT_EQ(0U, res->body.size());
  4088. }
  4089. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4090. auto res =
  4091. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4092. ASSERT_TRUE(res);
  4093. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4094. EXPECT_EQ(5U, res->body.size());
  4095. // Check that overlapping ranges are coalesced into a single range
  4096. EXPECT_EQ("bcdef", res->body);
  4097. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4098. // Should be single range, not multipart
  4099. EXPECT_TRUE(res->has_header("Content-Range"));
  4100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4101. }
  4102. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4103. auto res =
  4104. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4105. ASSERT_TRUE(res);
  4106. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4107. EXPECT_EQ(268U, res->body.size());
  4108. // Check that both range contents are present
  4109. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4110. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4111. // Check that Content-Range headers are present for both ranges
  4112. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4113. std::string::npos);
  4114. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4115. std::string::npos);
  4116. }
  4117. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4118. auto res =
  4119. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4120. ASSERT_TRUE(res);
  4121. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4122. EXPECT_EQ(269U, res->body.size());
  4123. // Check that both duplicate range contents are present
  4124. size_t first_abc = res->body.find("abc\r\n");
  4125. EXPECT_TRUE(first_abc != std::string::npos);
  4126. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4127. EXPECT_TRUE(second_abc != std::string::npos);
  4128. // Check that Content-Range headers are present for both ranges
  4129. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4130. EXPECT_TRUE(first_range != std::string::npos);
  4131. size_t second_range =
  4132. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4133. EXPECT_TRUE(second_range != std::string::npos);
  4134. }
  4135. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4136. auto res = cli_.Get("/streamed-with-range?error",
  4137. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4138. ASSERT_TRUE(res);
  4139. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4140. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4141. EXPECT_EQ(false, res->has_header("Content-Range"));
  4142. EXPECT_EQ(0U, res->body.size());
  4143. }
  4144. TEST_F(ServerTest, GetStreamedEndless) {
  4145. uint64_t offset = 0;
  4146. auto res = cli_.Get("/streamed-cancel",
  4147. [&](const char * /*data*/, uint64_t data_length) {
  4148. if (offset < 100) {
  4149. offset += data_length;
  4150. return true;
  4151. }
  4152. return false;
  4153. });
  4154. ASSERT_TRUE(!res);
  4155. EXPECT_EQ(Error::Canceled, res.error());
  4156. }
  4157. TEST_F(ServerTest, ClientStop) {
  4158. std::atomic_size_t count{4};
  4159. std::vector<std::thread> threads;
  4160. for (auto i = count.load(); i != 0; --i) {
  4161. threads.emplace_back([&]() {
  4162. auto res = cli_.Get("/streamed-cancel",
  4163. [&](const char *, uint64_t) { return true; });
  4164. --count;
  4165. ASSERT_TRUE(!res);
  4166. EXPECT_TRUE(res.error() == Error::Canceled ||
  4167. res.error() == Error::Read || res.error() == Error::Write);
  4168. });
  4169. }
  4170. std::this_thread::sleep_for(std::chrono::seconds(2));
  4171. while (count != 0) {
  4172. cli_.stop();
  4173. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4174. }
  4175. for (auto &t : threads) {
  4176. t.join();
  4177. }
  4178. }
  4179. TEST_F(ServerTest, GetWithRange1) {
  4180. auto res = cli_.Get("/with-range", {
  4181. make_range_header({{3, 5}}),
  4182. {"Accept-Encoding", ""},
  4183. });
  4184. ASSERT_TRUE(res);
  4185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4186. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4187. EXPECT_EQ(true, res->has_header("Content-Range"));
  4188. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4189. EXPECT_EQ(std::string("def"), res->body);
  4190. }
  4191. TEST_F(ServerTest, GetWithRange2) {
  4192. auto res = cli_.Get("/with-range", {
  4193. make_range_header({{1, -1}}),
  4194. {"Accept-Encoding", ""},
  4195. });
  4196. ASSERT_TRUE(res);
  4197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4198. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4199. EXPECT_EQ(true, res->has_header("Content-Range"));
  4200. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4201. EXPECT_EQ(std::string("bcdefg"), res->body);
  4202. }
  4203. TEST_F(ServerTest, GetWithRange3) {
  4204. auto res = cli_.Get("/with-range", {
  4205. make_range_header({{0, 0}}),
  4206. {"Accept-Encoding", ""},
  4207. });
  4208. ASSERT_TRUE(res);
  4209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4210. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4211. EXPECT_EQ(true, res->has_header("Content-Range"));
  4212. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4213. EXPECT_EQ(std::string("a"), res->body);
  4214. }
  4215. TEST_F(ServerTest, GetWithRange4) {
  4216. auto res = cli_.Get("/with-range", {
  4217. make_range_header({{-1, 2}}),
  4218. {"Accept-Encoding", ""},
  4219. });
  4220. ASSERT_TRUE(res);
  4221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4222. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4223. EXPECT_EQ(true, res->has_header("Content-Range"));
  4224. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4225. EXPECT_EQ(std::string("fg"), res->body);
  4226. }
  4227. TEST_F(ServerTest, GetWithRange5) {
  4228. auto res = cli_.Get("/with-range", {
  4229. make_range_header({{0, 5}}),
  4230. {"Accept-Encoding", ""},
  4231. });
  4232. ASSERT_TRUE(res);
  4233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4235. EXPECT_EQ(true, res->has_header("Content-Range"));
  4236. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4237. EXPECT_EQ(std::string("abcdef"), res->body);
  4238. }
  4239. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4240. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4241. ASSERT_TRUE(res);
  4242. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4243. }
  4244. TEST_F(ServerTest, GetWithRangeMultipart) {
  4245. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4246. ASSERT_TRUE(res);
  4247. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4248. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4249. EXPECT_EQ(false, res->has_header("Content-Range"));
  4250. EXPECT_EQ(267U, res->body.size());
  4251. }
  4252. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4253. auto res =
  4254. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4255. ASSERT_TRUE(res);
  4256. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4257. }
  4258. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4259. auto res = cli_.Get("/with-range-customized-response",
  4260. {{make_range_header({{1, 2}})}});
  4261. ASSERT_TRUE(res);
  4262. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4263. EXPECT_EQ(true, res->has_header("Content-Length"));
  4264. EXPECT_EQ(false, res->has_header("Content-Range"));
  4265. EXPECT_EQ(JSON_DATA, res->body);
  4266. }
  4267. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4268. auto res = cli_.Get("/with-range-customized-response",
  4269. {{make_range_header({{1, 2}, {4, 5}})}});
  4270. ASSERT_TRUE(res);
  4271. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4272. EXPECT_EQ(true, res->has_header("Content-Length"));
  4273. EXPECT_EQ(false, res->has_header("Content-Range"));
  4274. EXPECT_EQ(JSON_DATA, res->body);
  4275. }
  4276. TEST_F(ServerTest, Issue1772) {
  4277. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4278. ASSERT_TRUE(res);
  4279. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4280. }
  4281. TEST_F(ServerTest, Issue609) {
  4282. auto res = cli_.Delete("/issue609");
  4283. ASSERT_TRUE(res);
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. EXPECT_EQ(std::string("ok"), res->body);
  4286. }
  4287. TEST_F(ServerTest, GetStreamedChunked) {
  4288. auto res = cli_.Get("/streamed-chunked");
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::OK_200, res->status);
  4291. EXPECT_EQ(std::string("123456789"), res->body);
  4292. }
  4293. TEST_F(ServerTest, GetStreamedChunked2) {
  4294. auto res = cli_.Get("/streamed-chunked2");
  4295. ASSERT_TRUE(res);
  4296. EXPECT_EQ(StatusCode::OK_200, res->status);
  4297. EXPECT_EQ(std::string("123456789"), res->body);
  4298. }
  4299. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4300. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4301. ASSERT_TRUE(res);
  4302. EXPECT_EQ(StatusCode::OK_200, res->status);
  4303. EXPECT_EQ(std::string("123456789"), res->body);
  4304. EXPECT_TRUE(res->has_header("Trailer"));
  4305. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4306. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4307. // Trailers are now stored separately from headers (security fix)
  4308. EXPECT_EQ(2U, res->trailers.size());
  4309. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4310. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4311. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4312. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4313. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4314. // Verify trailers are NOT in headers (security verification)
  4315. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4316. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4317. }
  4318. TEST_F(ServerTest, LargeChunkedPost) {
  4319. Request req;
  4320. req.method = "POST";
  4321. req.path = "/large-chunked";
  4322. std::string host_and_port;
  4323. host_and_port += HOST;
  4324. host_and_port += ":";
  4325. host_and_port += std::to_string(PORT);
  4326. req.headers.emplace("Host", host_and_port.c_str());
  4327. req.headers.emplace("Accept", "*/*");
  4328. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4329. req.headers.emplace("Content-Type", "text/plain");
  4330. req.headers.emplace("Content-Length", "0");
  4331. req.headers.emplace("Transfer-Encoding", "chunked");
  4332. std::string long_string(30 * 1024u, 'a');
  4333. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4334. // Attempt to make a large enough post to exceed OS buffers, to test that
  4335. // the server handles short reads if the full chunk data isn't available.
  4336. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4337. auto res = std::make_shared<Response>();
  4338. auto error = Error::Success;
  4339. auto ret = cli_.send(req, *res, error);
  4340. ASSERT_TRUE(ret);
  4341. EXPECT_EQ(StatusCode::OK_200, res->status);
  4342. }
  4343. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4344. auto res = cli_.Get("/remote_addr");
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::OK_200, res->status);
  4347. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4348. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4349. }
  4350. TEST_F(ServerTest, GetMethodLocalAddr) {
  4351. auto res = cli_.Get("/local_addr");
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::OK_200, res->status);
  4354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4355. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4356. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4357. }
  4358. TEST_F(ServerTest, HTTPResponseSplitting) {
  4359. auto res = cli_.Get("/http_response_splitting");
  4360. ASSERT_TRUE(res);
  4361. EXPECT_EQ(StatusCode::OK_200, res->status);
  4362. }
  4363. TEST_F(ServerTest, SlowRequest) {
  4364. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4366. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4367. }
  4368. #if 0
  4369. TEST_F(ServerTest, SlowPost) {
  4370. char buffer[64 * 1024];
  4371. memset(buffer, 0x42, sizeof(buffer));
  4372. auto res = cli_.Post(
  4373. "/slowpost", 64 * 1024 * 1024,
  4374. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4375. auto ret = sink.write(buffer, sizeof(buffer));
  4376. EXPECT_TRUE(ret);
  4377. return true;
  4378. },
  4379. "text/plain");
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(StatusCode::OK_200, res->status);
  4382. }
  4383. TEST_F(ServerTest, SlowPostFail) {
  4384. char buffer[64 * 1024];
  4385. memset(buffer, 0x42, sizeof(buffer));
  4386. cli_.set_write_timeout(std::chrono::seconds(0));
  4387. auto res = cli_.Post(
  4388. "/slowpost", 64 * 1024 * 1024,
  4389. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4390. sink.write(buffer, sizeof(buffer));
  4391. return true;
  4392. },
  4393. "text/plain");
  4394. ASSERT_TRUE(!res);
  4395. EXPECT_EQ(Error::Write, res.error());
  4396. }
  4397. #endif
  4398. TEST_F(ServerTest, Put) {
  4399. auto res = cli_.Put("/put", "PUT", "text/plain");
  4400. ASSERT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. EXPECT_EQ("PUT", res->body);
  4403. }
  4404. TEST_F(ServerTest, PutWithContentProvider) {
  4405. auto res = cli_.Put(
  4406. "/put", 3,
  4407. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4408. sink.os << "PUT";
  4409. return true;
  4410. },
  4411. "text/plain");
  4412. ASSERT_TRUE(res);
  4413. EXPECT_EQ(StatusCode::OK_200, res->status);
  4414. EXPECT_EQ("PUT", res->body);
  4415. }
  4416. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4417. auto res = cli_.Post(
  4418. "/post", 42,
  4419. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4420. return false;
  4421. },
  4422. "text/plain");
  4423. ASSERT_TRUE(!res);
  4424. EXPECT_EQ(Error::Canceled, res.error());
  4425. }
  4426. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4427. auto res = cli_.Put(
  4428. "/put",
  4429. [](size_t /*offset*/, DataSink &sink) {
  4430. sink.os << "PUT";
  4431. sink.done();
  4432. return true;
  4433. },
  4434. "text/plain");
  4435. ASSERT_TRUE(res);
  4436. EXPECT_EQ(StatusCode::OK_200, res->status);
  4437. EXPECT_EQ("PUT", res->body);
  4438. }
  4439. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4440. auto res = cli_.Post(
  4441. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4442. "text/plain");
  4443. ASSERT_TRUE(!res);
  4444. EXPECT_EQ(Error::Canceled, res.error());
  4445. }
  4446. TEST_F(ServerTest, PostLoopBack) {
  4447. std::string body;
  4448. auto res = cli_.Post(
  4449. "/post-loopback", 9,
  4450. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4451. EXPECT_EQ(9u, length);
  4452. sink.write("123", 3);
  4453. sink.write("456", 3);
  4454. sink.write("789", 3);
  4455. return true;
  4456. },
  4457. "text/plain",
  4458. [&body](const char *data, size_t data_length) {
  4459. body.append(data, data_length);
  4460. return true;
  4461. });
  4462. ASSERT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::OK_200, res->status);
  4464. EXPECT_EQ("123456789", body);
  4465. }
  4466. TEST_F(ServerTest, PutLoopBack) {
  4467. std::string body;
  4468. auto res = cli_.Put(
  4469. "/put-loopback", 9,
  4470. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4471. EXPECT_EQ(9u, length);
  4472. sink.write("123", 3);
  4473. sink.write("456", 3);
  4474. sink.write("789", 3);
  4475. return true;
  4476. },
  4477. "text/plain",
  4478. [&body](const char *data, size_t data_length) {
  4479. body.append(data, data_length);
  4480. return true;
  4481. });
  4482. ASSERT_TRUE(res);
  4483. EXPECT_EQ(StatusCode::OK_200, res->status);
  4484. EXPECT_EQ("123456789", body);
  4485. }
  4486. TEST_F(ServerTest, PatchLoopBack) {
  4487. std::string body;
  4488. auto res = cli_.Patch(
  4489. "/patch-loopback", 9,
  4490. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4491. EXPECT_EQ(9u, length);
  4492. sink.write("123", 3);
  4493. sink.write("456", 3);
  4494. sink.write("789", 3);
  4495. return true;
  4496. },
  4497. "text/plain",
  4498. [&body](const char *data, size_t data_length) {
  4499. body.append(data, data_length);
  4500. return true;
  4501. });
  4502. ASSERT_TRUE(res);
  4503. EXPECT_EQ(StatusCode::OK_200, res->status);
  4504. EXPECT_EQ("123456789", body);
  4505. }
  4506. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4507. std::string body;
  4508. auto res = cli_.Post(
  4509. "/post-loopback",
  4510. [](size_t /*offset*/, DataSink &sink) {
  4511. sink.write("123", 3);
  4512. sink.write("456", 3);
  4513. sink.write("789", 3);
  4514. sink.done();
  4515. return true;
  4516. },
  4517. "text/plain",
  4518. [&body](const char *data, size_t data_length) {
  4519. body.append(data, data_length);
  4520. return true;
  4521. });
  4522. ASSERT_TRUE(res);
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("123456789", body);
  4525. }
  4526. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4527. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4528. cli_.set_compress(true);
  4529. auto res = cli_.Put(
  4530. "/put", 3,
  4531. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4532. sink.os << "PUT";
  4533. return true;
  4534. },
  4535. "text/plain");
  4536. ASSERT_TRUE(res);
  4537. EXPECT_EQ(StatusCode::OK_200, res->status);
  4538. EXPECT_EQ("PUT", res->body);
  4539. }
  4540. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4541. cli_.set_compress(true);
  4542. auto res = cli_.Post(
  4543. "/post", 42,
  4544. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4545. return false;
  4546. },
  4547. "text/plain");
  4548. ASSERT_TRUE(!res);
  4549. EXPECT_EQ(Error::Canceled, res.error());
  4550. }
  4551. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4552. cli_.set_compress(true);
  4553. auto res = cli_.Put(
  4554. "/put",
  4555. [](size_t /*offset*/, DataSink &sink) {
  4556. sink.os << "PUT";
  4557. sink.done();
  4558. return true;
  4559. },
  4560. "text/plain");
  4561. ASSERT_TRUE(res);
  4562. EXPECT_EQ(StatusCode::OK_200, res->status);
  4563. EXPECT_EQ("PUT", res->body);
  4564. }
  4565. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4566. cli_.set_compress(true);
  4567. auto res = cli_.Post(
  4568. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4569. "text/plain");
  4570. ASSERT_TRUE(!res);
  4571. EXPECT_EQ(Error::Canceled, res.error());
  4572. }
  4573. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4574. cli_.set_compress(true);
  4575. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4576. ASSERT_TRUE(res);
  4577. EXPECT_EQ(StatusCode::OK_200, res->status);
  4578. EXPECT_EQ(LARGE_DATA, res->body);
  4579. }
  4580. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4582. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4583. Client cli(s.c_str());
  4584. cli.enable_server_certificate_verification(false);
  4585. #else
  4586. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4587. Client cli(s.c_str());
  4588. #endif
  4589. cli.set_compress(true);
  4590. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4591. ASSERT_TRUE(res);
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ(LARGE_DATA, res->body);
  4594. // The compressed size should be less than a 10th of the original. May vary
  4595. // depending on the zlib library.
  4596. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4597. static_cast<uint64_t>(10 * 1024 * 1024));
  4598. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4599. }
  4600. TEST_F(ServerTest, PutContentWithDeflate) {
  4601. cli_.set_compress(false);
  4602. Headers headers;
  4603. headers.emplace("Content-Encoding", "deflate");
  4604. // PUT in deflate format:
  4605. auto res = cli_.Put("/put", headers,
  4606. "\170\234\013\010\015\001\0\001\361\0\372", "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, GetStreamedChunkedWithGzip) {
  4612. Headers headers;
  4613. headers.emplace("Accept-Encoding", "gzip, deflate");
  4614. auto res = cli_.Get("/streamed-chunked", headers);
  4615. ASSERT_TRUE(res);
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. EXPECT_EQ(std::string("123456789"), res->body);
  4618. }
  4619. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4620. Headers headers;
  4621. headers.emplace("Accept-Encoding", "gzip, deflate");
  4622. auto res = cli_.Get("/streamed-chunked2", headers);
  4623. ASSERT_TRUE(res);
  4624. EXPECT_EQ(StatusCode::OK_200, res->status);
  4625. EXPECT_EQ(std::string("123456789"), res->body);
  4626. }
  4627. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4628. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4629. ASSERT_TRUE(res);
  4630. EXPECT_EQ(StatusCode::OK_200, res->status);
  4631. }
  4632. TEST(GzipDecompressor, ChunkedDecompression) {
  4633. std::string data;
  4634. for (size_t i = 0; i < 32 * 1024; ++i) {
  4635. data.push_back(static_cast<char>('a' + i % 26));
  4636. }
  4637. std::string compressed_data;
  4638. {
  4639. httplib::detail::gzip_compressor compressor;
  4640. bool result = compressor.compress(
  4641. data.data(), data.size(),
  4642. /*last=*/true,
  4643. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4644. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4645. compressed_data_size);
  4646. return true;
  4647. });
  4648. ASSERT_TRUE(result);
  4649. }
  4650. std::string decompressed_data;
  4651. {
  4652. httplib::detail::gzip_decompressor decompressor;
  4653. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4654. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4655. size_t chunk_size = 130;
  4656. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4657. chunk_begin += chunk_size) {
  4658. size_t current_chunk_size =
  4659. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4660. bool result = decompressor.decompress(
  4661. compressed_data.data() + chunk_begin, current_chunk_size,
  4662. [&](const char *decompressed_data_chunk,
  4663. size_t decompressed_data_chunk_size) {
  4664. decompressed_data.insert(decompressed_data.size(),
  4665. decompressed_data_chunk,
  4666. decompressed_data_chunk_size);
  4667. return true;
  4668. });
  4669. ASSERT_TRUE(result);
  4670. }
  4671. }
  4672. ASSERT_EQ(data, decompressed_data);
  4673. }
  4674. TEST(GzipDecompressor, DeflateDecompression) {
  4675. std::string original_text = "Raw deflate without gzip";
  4676. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4677. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4678. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4679. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4680. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4681. std::string decompressed_data;
  4682. {
  4683. httplib::detail::gzip_decompressor decompressor;
  4684. bool result = decompressor.decompress(
  4685. compressed_data.data(), compressed_data.size(),
  4686. [&](const char *decompressed_data_chunk,
  4687. size_t decompressed_data_chunk_size) {
  4688. decompressed_data.insert(decompressed_data.size(),
  4689. decompressed_data_chunk,
  4690. decompressed_data_chunk_size);
  4691. return true;
  4692. });
  4693. ASSERT_TRUE(result);
  4694. }
  4695. ASSERT_EQ(original_text, decompressed_data);
  4696. }
  4697. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4698. std::string original_text = "Raw deflate without gzip";
  4699. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4700. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4701. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4702. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4703. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4704. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4705. std::string decompressed_data;
  4706. {
  4707. httplib::detail::gzip_decompressor decompressor;
  4708. bool result = decompressor.decompress(
  4709. compressed_data.data(), compressed_data.size(),
  4710. [&](const char *decompressed_data_chunk,
  4711. size_t decompressed_data_chunk_size) {
  4712. decompressed_data.insert(decompressed_data.size(),
  4713. decompressed_data_chunk,
  4714. decompressed_data_chunk_size);
  4715. return true;
  4716. });
  4717. ASSERT_TRUE(result);
  4718. }
  4719. ASSERT_EQ(original_text, decompressed_data);
  4720. }
  4721. #ifdef _WIN32
  4722. TEST(GzipDecompressor, LargeRandomData) {
  4723. // prepare large random data that is difficult to be compressed and is
  4724. // expected to have large size even when compressed
  4725. std::random_device seed_gen;
  4726. std::mt19937 random(seed_gen());
  4727. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4728. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4729. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4730. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4731. // compress data over 4GiB
  4732. std::string compressed_data;
  4733. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4734. httplib::detail::gzip_compressor compressor;
  4735. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4736. data.size() * sizeof(std::uint32_t), true,
  4737. [&](const char *data, size_t size) {
  4738. compressed_data.insert(
  4739. compressed_data.size(), data, size);
  4740. return true;
  4741. });
  4742. ASSERT_TRUE(result);
  4743. // FIXME: compressed data size is expected to be greater than 4GiB,
  4744. // but there is no guarantee
  4745. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4746. // decompress data over 4GiB
  4747. std::string decompressed_data;
  4748. decompressed_data.reserve(data_size);
  4749. httplib::detail::gzip_decompressor decompressor;
  4750. result = decompressor.decompress(
  4751. compressed_data.data(), compressed_data.size(),
  4752. [&](const char *data, size_t size) {
  4753. decompressed_data.insert(decompressed_data.size(), data, size);
  4754. return true;
  4755. });
  4756. ASSERT_TRUE(result);
  4757. // compare
  4758. ASSERT_EQ(data_size, decompressed_data.size());
  4759. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4760. 0);
  4761. }
  4762. #endif
  4763. #endif
  4764. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4765. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4766. Headers headers;
  4767. headers.emplace("Accept-Encoding", "br");
  4768. auto res = cli_.Get("/streamed-chunked", headers);
  4769. ASSERT_TRUE(res);
  4770. EXPECT_EQ(StatusCode::OK_200, res->status);
  4771. EXPECT_EQ(std::string("123456789"), res->body);
  4772. }
  4773. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4774. Headers headers;
  4775. headers.emplace("Accept-Encoding", "br");
  4776. auto res = cli_.Get("/streamed-chunked2", headers);
  4777. ASSERT_TRUE(res);
  4778. EXPECT_EQ(StatusCode::OK_200, res->status);
  4779. EXPECT_EQ(std::string("123456789"), res->body);
  4780. }
  4781. #endif
  4782. TEST_F(ServerTest, Patch) {
  4783. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ("PATCH", res->body);
  4787. }
  4788. TEST_F(ServerTest, Delete) {
  4789. auto res = cli_.Delete("/delete");
  4790. ASSERT_TRUE(res);
  4791. EXPECT_EQ(StatusCode::OK_200, res->status);
  4792. EXPECT_EQ("DELETE", res->body);
  4793. }
  4794. TEST_F(ServerTest, DeleteContentReceiver) {
  4795. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4796. ASSERT_TRUE(res);
  4797. EXPECT_EQ(StatusCode::OK_200, res->status);
  4798. EXPECT_EQ("content", res->body);
  4799. }
  4800. TEST_F(ServerTest, Options) {
  4801. auto res = cli_.Options("*");
  4802. ASSERT_TRUE(res);
  4803. EXPECT_EQ(StatusCode::OK_200, res->status);
  4804. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4805. EXPECT_TRUE(res->body.empty());
  4806. }
  4807. TEST_F(ServerTest, URL) {
  4808. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4809. ASSERT_TRUE(res);
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. }
  4812. TEST_F(ServerTest, ArrayParam) {
  4813. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4814. ASSERT_TRUE(res);
  4815. EXPECT_EQ(StatusCode::OK_200, res->status);
  4816. }
  4817. TEST_F(ServerTest, NoMultipleHeaders) {
  4818. Headers headers = {{"Content-Length", "5"}};
  4819. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4820. "text/plain");
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, PostContentReceiver) {
  4825. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4826. ASSERT_TRUE(res);
  4827. ASSERT_EQ(StatusCode::OK_200, res->status);
  4828. ASSERT_EQ("content", res->body);
  4829. }
  4830. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4831. UploadFormDataItems items = {
  4832. {"text1", "text default", "", ""},
  4833. {"text2", "aωb", "", ""},
  4834. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4835. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4836. {"file3", "", "", "application/octet-stream"},
  4837. };
  4838. auto res = cli_.Post("/content_receiver", items);
  4839. ASSERT_TRUE(res);
  4840. EXPECT_EQ(StatusCode::OK_200, res->status);
  4841. }
  4842. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4843. UploadFormDataItems items = {
  4844. {"text1", "text default", "", ""},
  4845. {"text2", "aωb", "", ""},
  4846. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4847. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4848. {"file3", "", "", "application/octet-stream"},
  4849. };
  4850. auto boundary = std::string("+++++");
  4851. std::string body;
  4852. for (const auto &item : items) {
  4853. body += "--" + boundary + "\r\n";
  4854. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4855. if (!item.filename.empty()) {
  4856. body += "; filename=\"" + item.filename + "\"";
  4857. }
  4858. body += "\r\n";
  4859. if (!item.content_type.empty()) {
  4860. body += "Content-Type: " + item.content_type + "\r\n";
  4861. }
  4862. body += "\r\n";
  4863. body += item.content + "\r\n";
  4864. }
  4865. body += "--" + boundary + "--\r\n";
  4866. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4867. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4868. ASSERT_TRUE(res);
  4869. EXPECT_EQ(StatusCode::OK_200, res->status);
  4870. }
  4871. TEST_F(ServerTest, PostContentReceiverGzip) {
  4872. cli_.set_compress(true);
  4873. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4874. ASSERT_TRUE(res);
  4875. ASSERT_EQ(StatusCode::OK_200, res->status);
  4876. ASSERT_EQ("content", res->body);
  4877. }
  4878. TEST_F(ServerTest, PutContentReceiver) {
  4879. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4880. ASSERT_TRUE(res);
  4881. ASSERT_EQ(StatusCode::OK_200, res->status);
  4882. ASSERT_EQ("content", res->body);
  4883. }
  4884. TEST_F(ServerTest, PatchContentReceiver) {
  4885. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4886. ASSERT_TRUE(res);
  4887. ASSERT_EQ(StatusCode::OK_200, res->status);
  4888. ASSERT_EQ("content", res->body);
  4889. }
  4890. template <typename ClientType>
  4891. void TestWithHeadersAndContentReceiver(
  4892. ClientType &cli,
  4893. std::function<Result(ClientType &, const std::string &, const Headers &,
  4894. const std::string &, const std::string &,
  4895. ContentReceiver, DownloadProgress)>
  4896. request_func) {
  4897. Headers headers;
  4898. headers.emplace("X-Custom-Header", "test-value");
  4899. std::string received_body;
  4900. auto res = request_func(
  4901. cli, "/content_receiver", headers, "content", "application/json",
  4902. [&](const char *data, size_t data_length) {
  4903. received_body.append(data, data_length);
  4904. return true;
  4905. },
  4906. nullptr);
  4907. ASSERT_TRUE(res);
  4908. EXPECT_EQ(StatusCode::OK_200, res->status);
  4909. EXPECT_EQ("content", received_body);
  4910. }
  4911. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4912. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4913. using ClientT = SSLClient;
  4914. #else
  4915. using ClientT = Client;
  4916. #endif
  4917. TestWithHeadersAndContentReceiver<ClientT>(
  4918. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4919. const std::string &body, const std::string &content_type,
  4920. ContentReceiver receiver, DownloadProgress progress) {
  4921. return cli.Post(path, headers, body, content_type, receiver, progress);
  4922. });
  4923. }
  4924. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4925. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4926. using ClientT = SSLClient;
  4927. #else
  4928. using ClientT = Client;
  4929. #endif
  4930. TestWithHeadersAndContentReceiver<ClientT>(
  4931. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4932. const std::string &body, const std::string &content_type,
  4933. ContentReceiver receiver, DownloadProgress progress) {
  4934. return cli.Put(path, headers, body, content_type, receiver, progress);
  4935. });
  4936. }
  4937. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4938. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4939. using ClientT = SSLClient;
  4940. #else
  4941. using ClientT = Client;
  4942. #endif
  4943. TestWithHeadersAndContentReceiver<ClientT>(
  4944. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4945. const std::string &body, const std::string &content_type,
  4946. ContentReceiver receiver, DownloadProgress progress) {
  4947. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4948. });
  4949. }
  4950. template <typename ClientType>
  4951. void TestWithHeadersAndContentReceiverWithProgress(
  4952. ClientType &cli,
  4953. std::function<Result(ClientType &, const std::string &, const Headers &,
  4954. const std::string &, const std::string &,
  4955. ContentReceiver, DownloadProgress)>
  4956. request_func) {
  4957. Headers headers;
  4958. headers.emplace("X-Test-Header", "progress-test");
  4959. std::string received_body;
  4960. auto progress_called = false;
  4961. auto res = request_func(
  4962. cli, "/content_receiver", headers, "content", "text/plain",
  4963. [&](const char *data, size_t data_length) {
  4964. received_body.append(data, data_length);
  4965. return true;
  4966. },
  4967. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4968. progress_called = true;
  4969. return true;
  4970. });
  4971. ASSERT_TRUE(res);
  4972. EXPECT_EQ(StatusCode::OK_200, res->status);
  4973. EXPECT_EQ("content", received_body);
  4974. EXPECT_TRUE(progress_called);
  4975. }
  4976. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4977. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4978. using ClientT = SSLClient;
  4979. #else
  4980. using ClientT = Client;
  4981. #endif
  4982. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4983. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4984. const std::string &body, const std::string &content_type,
  4985. ContentReceiver receiver, DownloadProgress progress) {
  4986. return cli.Post(path, headers, body, content_type, receiver, progress);
  4987. });
  4988. }
  4989. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4991. using ClientT = SSLClient;
  4992. #else
  4993. using ClientT = Client;
  4994. #endif
  4995. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4996. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4997. const std::string &body, const std::string &content_type,
  4998. ContentReceiver receiver, DownloadProgress progress) {
  4999. return cli.Put(path, headers, body, content_type, receiver, progress);
  5000. });
  5001. }
  5002. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5003. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5004. using ClientT = SSLClient;
  5005. #else
  5006. using ClientT = Client;
  5007. #endif
  5008. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5009. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5010. const std::string &body, const std::string &content_type,
  5011. ContentReceiver receiver, DownloadProgress progress) {
  5012. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5013. });
  5014. }
  5015. template <typename ClientType>
  5016. void TestWithHeadersAndContentReceiverError(
  5017. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5018. const Headers &, const std::string &,
  5019. const std::string &, ContentReceiver)>
  5020. request_func) {
  5021. Headers headers;
  5022. headers.emplace("X-Error-Test", "true");
  5023. std::string received_body;
  5024. auto receiver_failed = false;
  5025. auto res =
  5026. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5027. [&](const char *data, size_t data_length) {
  5028. received_body.append(data, data_length);
  5029. receiver_failed = true;
  5030. return false;
  5031. });
  5032. ASSERT_FALSE(res);
  5033. EXPECT_TRUE(receiver_failed);
  5034. }
  5035. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5036. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5037. using ClientT = SSLClient;
  5038. #else
  5039. using ClientT = Client;
  5040. #endif
  5041. TestWithHeadersAndContentReceiverError<ClientT>(
  5042. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5043. const std::string &body, const std::string &content_type,
  5044. ContentReceiver receiver) {
  5045. return cli.Post(path, headers, body, content_type, receiver);
  5046. });
  5047. }
  5048. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5050. using ClientT = SSLClient;
  5051. #else
  5052. using ClientT = Client;
  5053. #endif
  5054. TestWithHeadersAndContentReceiverError<ClientT>(
  5055. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5056. const std::string &body, const std::string &content_type,
  5057. ContentReceiver receiver) {
  5058. return cli.Put(path, headers, body, content_type, receiver);
  5059. });
  5060. }
  5061. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5062. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5063. using ClientT = SSLClient;
  5064. #else
  5065. using ClientT = Client;
  5066. #endif
  5067. TestWithHeadersAndContentReceiverError<ClientT>(
  5068. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5069. const std::string &body, const std::string &content_type,
  5070. ContentReceiver receiver) {
  5071. return cli.Patch(path, headers, body, content_type, receiver);
  5072. });
  5073. }
  5074. TEST_F(ServerTest, PostQueryStringAndBody) {
  5075. auto res =
  5076. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5077. ASSERT_TRUE(res);
  5078. ASSERT_EQ(StatusCode::OK_200, res->status);
  5079. }
  5080. TEST_F(ServerTest, HTTP2Magic) {
  5081. Request req;
  5082. req.method = "PRI";
  5083. req.path = "*";
  5084. req.body = "SM";
  5085. auto res = std::make_shared<Response>();
  5086. auto error = Error::Success;
  5087. auto ret = cli_.send(req, *res, error);
  5088. ASSERT_TRUE(ret);
  5089. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5090. }
  5091. TEST_F(ServerTest, KeepAlive) {
  5092. auto res = cli_.Get("/hi");
  5093. ASSERT_TRUE(res);
  5094. EXPECT_EQ(StatusCode::OK_200, res->status);
  5095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5096. EXPECT_EQ("Hello World!", res->body);
  5097. res = cli_.Get("/hi");
  5098. ASSERT_TRUE(res);
  5099. EXPECT_EQ(StatusCode::OK_200, res->status);
  5100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5101. EXPECT_EQ("Hello World!", res->body);
  5102. res = cli_.Get("/hi");
  5103. ASSERT_TRUE(res);
  5104. EXPECT_EQ(StatusCode::OK_200, res->status);
  5105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5106. EXPECT_EQ("Hello World!", res->body);
  5107. res = cli_.Get("/not-exist");
  5108. ASSERT_TRUE(res);
  5109. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5110. res = cli_.Post("/empty", "", "text/plain");
  5111. ASSERT_TRUE(res);
  5112. EXPECT_EQ(StatusCode::OK_200, res->status);
  5113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5114. EXPECT_EQ("empty", res->body);
  5115. EXPECT_EQ("close", res->get_header_value("Connection"));
  5116. res = cli_.Post(
  5117. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5118. "text/plain");
  5119. ASSERT_TRUE(res);
  5120. EXPECT_EQ(StatusCode::OK_200, res->status);
  5121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5122. EXPECT_EQ("empty", res->body);
  5123. cli_.set_keep_alive(false);
  5124. res = cli_.Get("/last-request");
  5125. ASSERT_TRUE(res);
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. EXPECT_EQ("close", res->get_header_value("Connection"));
  5128. }
  5129. TEST_F(ServerTest, TooManyRedirect) {
  5130. cli_.set_follow_location(true);
  5131. auto res = cli_.Get("/redirect/0");
  5132. ASSERT_TRUE(!res);
  5133. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5134. }
  5135. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5136. Request req;
  5137. req.method = "FOOBAR";
  5138. req.path = "/hi";
  5139. cli_.set_keep_alive(true);
  5140. auto res = cli_.send(req);
  5141. ASSERT_TRUE(res);
  5142. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5143. EXPECT_EQ("close", res->get_header_value("Connection"));
  5144. EXPECT_FALSE(cli_.is_socket_open());
  5145. }
  5146. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5147. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5148. TEST_F(ServerTest, Gzip) {
  5149. Headers headers;
  5150. headers.emplace("Accept-Encoding", "gzip, deflate");
  5151. auto res = cli_.Get("/compress", headers);
  5152. ASSERT_TRUE(res);
  5153. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5155. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5156. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5157. "7890123456789012345678901234567890",
  5158. res->body);
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. }
  5161. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5162. Headers headers;
  5163. headers.emplace("Accept-Encoding", "");
  5164. auto res = cli_.Get("/compress", headers);
  5165. ASSERT_TRUE(res);
  5166. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5168. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5169. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5170. "7890123456789012345678901234567890",
  5171. res->body);
  5172. EXPECT_EQ(StatusCode::OK_200, res->status);
  5173. }
  5174. TEST_F(ServerTest, GzipWithContentReceiver) {
  5175. Headers headers;
  5176. headers.emplace("Accept-Encoding", "gzip, deflate");
  5177. std::string body;
  5178. auto res = cli_.Get("/compress", headers,
  5179. [&](const char *data, uint64_t data_length) {
  5180. EXPECT_EQ(100U, data_length);
  5181. body.append(data, data_length);
  5182. return true;
  5183. });
  5184. ASSERT_TRUE(res);
  5185. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5186. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5187. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5189. "7890123456789012345678901234567890",
  5190. body);
  5191. EXPECT_EQ(StatusCode::OK_200, res->status);
  5192. }
  5193. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5194. Headers headers;
  5195. headers.emplace("Accept-Encoding", "gzip, deflate");
  5196. cli_.set_decompress(false);
  5197. auto res = cli_.Get("/compress", headers);
  5198. ASSERT_TRUE(res);
  5199. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5200. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5201. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5202. EXPECT_EQ(33U, res->body.size());
  5203. EXPECT_EQ(StatusCode::OK_200, res->status);
  5204. }
  5205. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5206. Headers headers;
  5207. headers.emplace("Accept-Encoding", "");
  5208. std::string body;
  5209. auto res = cli_.Get("/compress", headers,
  5210. [&](const char *data, uint64_t data_length) {
  5211. EXPECT_EQ(100U, data_length);
  5212. body.append(data, data_length);
  5213. return true;
  5214. });
  5215. ASSERT_TRUE(res);
  5216. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5217. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5218. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5219. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5220. "7890123456789012345678901234567890",
  5221. body);
  5222. EXPECT_EQ(StatusCode::OK_200, res->status);
  5223. }
  5224. TEST_F(ServerTest, NoGzip) {
  5225. Headers headers;
  5226. headers.emplace("Accept-Encoding", "gzip, deflate");
  5227. auto res = cli_.Get("/nocompress", headers);
  5228. ASSERT_TRUE(res);
  5229. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5230. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5231. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5232. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5233. "7890123456789012345678901234567890",
  5234. res->body);
  5235. EXPECT_EQ(StatusCode::OK_200, res->status);
  5236. }
  5237. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5238. Headers headers;
  5239. headers.emplace("Accept-Encoding", "gzip, deflate");
  5240. std::string body;
  5241. auto res = cli_.Get("/nocompress", headers,
  5242. [&](const char *data, uint64_t data_length) {
  5243. EXPECT_EQ(100U, data_length);
  5244. body.append(data, data_length);
  5245. return true;
  5246. });
  5247. ASSERT_TRUE(res);
  5248. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5249. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5250. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5251. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5252. "7890123456789012345678901234567890",
  5253. body);
  5254. EXPECT_EQ(StatusCode::OK_200, res->status);
  5255. }
  5256. TEST_F(ServerTest, MultipartFormDataGzip) {
  5257. UploadFormDataItems items = {
  5258. {"key1", "test", "", ""},
  5259. {"key2", "--abcdefg123", "", ""},
  5260. };
  5261. cli_.set_compress(true);
  5262. auto res = cli_.Post("/compress-multipart", items);
  5263. ASSERT_TRUE(res);
  5264. EXPECT_EQ(StatusCode::OK_200, res->status);
  5265. }
  5266. #endif
  5267. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5268. TEST_F(ServerTest, Brotli) {
  5269. Headers headers;
  5270. headers.emplace("Accept-Encoding", "br");
  5271. auto res = cli_.Get("/compress", headers);
  5272. ASSERT_TRUE(res);
  5273. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5274. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5275. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5276. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5277. "7890123456789012345678901234567890",
  5278. res->body);
  5279. EXPECT_EQ(StatusCode::OK_200, res->status);
  5280. }
  5281. #endif
  5282. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5283. TEST_F(ServerTest, Zstd) {
  5284. Headers headers;
  5285. headers.emplace("Accept-Encoding", "zstd");
  5286. auto res = cli_.Get("/compress", headers);
  5287. ASSERT_TRUE(res);
  5288. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5290. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5291. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5292. "7890123456789012345678901234567890",
  5293. res->body);
  5294. EXPECT_EQ(StatusCode::OK_200, res->status);
  5295. }
  5296. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5297. Headers headers;
  5298. headers.emplace("Accept-Encoding", "");
  5299. auto res = cli_.Get("/compress", headers);
  5300. ASSERT_TRUE(res);
  5301. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5303. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5304. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5305. "7890123456789012345678901234567890",
  5306. res->body);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. }
  5309. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5310. Headers headers;
  5311. headers.emplace("Accept-Encoding", "zstd");
  5312. std::string body;
  5313. auto res = cli_.Get("/compress", headers,
  5314. [&](const char *data, uint64_t data_length) {
  5315. EXPECT_EQ(100U, data_length);
  5316. body.append(data, data_length);
  5317. return true;
  5318. });
  5319. ASSERT_TRUE(res);
  5320. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5321. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5322. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5323. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5324. "7890123456789012345678901234567890",
  5325. body);
  5326. EXPECT_EQ(StatusCode::OK_200, res->status);
  5327. }
  5328. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5329. Headers headers;
  5330. headers.emplace("Accept-Encoding", "zstd");
  5331. cli_.set_decompress(false);
  5332. auto res = cli_.Get("/compress", headers);
  5333. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5334. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5335. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5336. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5337. ASSERT_TRUE(res);
  5338. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5339. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5340. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. ASSERT_EQ(26U, res->body.size());
  5343. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5344. 0);
  5345. }
  5346. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5347. Headers headers;
  5348. headers.emplace("Accept-Encoding", "");
  5349. std::string body;
  5350. auto res = cli_.Get("/compress", headers,
  5351. [&](const char *data, uint64_t data_length) {
  5352. EXPECT_EQ(100U, data_length);
  5353. body.append(data, data_length);
  5354. return true;
  5355. });
  5356. ASSERT_TRUE(res);
  5357. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5358. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5359. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5360. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5361. "7890123456789012345678901234567890",
  5362. body);
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. }
  5365. TEST_F(ServerTest, NoZstd) {
  5366. Headers headers;
  5367. headers.emplace("Accept-Encoding", "zstd");
  5368. auto res = cli_.Get("/nocompress", headers);
  5369. ASSERT_TRUE(res);
  5370. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5371. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5372. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5374. "7890123456789012345678901234567890",
  5375. res->body);
  5376. EXPECT_EQ(StatusCode::OK_200, res->status);
  5377. }
  5378. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5379. Headers headers;
  5380. headers.emplace("Accept-Encoding", "zstd");
  5381. std::string body;
  5382. auto res = cli_.Get("/nocompress", headers,
  5383. [&](const char *data, uint64_t data_length) {
  5384. EXPECT_EQ(100U, data_length);
  5385. body.append(data, data_length);
  5386. return true;
  5387. });
  5388. ASSERT_TRUE(res);
  5389. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5390. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5391. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5392. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5393. "7890123456789012345678901234567890",
  5394. body);
  5395. EXPECT_EQ(StatusCode::OK_200, res->status);
  5396. }
  5397. // TODO: How to enable zstd ??
  5398. TEST_F(ServerTest, MultipartFormDataZstd) {
  5399. UploadFormDataItems items = {
  5400. {"key1", "test", "", ""},
  5401. {"key2", "--abcdefg123", "", ""},
  5402. };
  5403. Headers headers;
  5404. headers.emplace("Accept-Encoding", "zstd");
  5405. cli_.set_compress(true);
  5406. auto res = cli_.Post("/compress-multipart", headers, items);
  5407. ASSERT_TRUE(res);
  5408. EXPECT_EQ(StatusCode::OK_200, res->status);
  5409. }
  5410. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5411. Headers headers;
  5412. headers.emplace("Accept-Encoding", "zstd");
  5413. cli_.set_compress(true);
  5414. auto res = cli_.Put(
  5415. "/put", headers, 3,
  5416. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5417. sink.os << "PUT";
  5418. return true;
  5419. },
  5420. "text/plain");
  5421. ASSERT_TRUE(res);
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. EXPECT_EQ("PUT", res->body);
  5424. }
  5425. // Pre-compression logging tests
  5426. TEST_F(ServerTest, PreCompressionLogging) {
  5427. // Test data for compression (matches the actual /compress endpoint content)
  5428. const std::string test_content =
  5429. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5430. "3456789012345678901234567890";
  5431. // Variables to capture logging data
  5432. std::string pre_compression_body;
  5433. std::string pre_compression_content_type;
  5434. std::string pre_compression_content_encoding;
  5435. std::string post_compression_body;
  5436. std::string post_compression_content_type;
  5437. std::string post_compression_content_encoding;
  5438. // Set up pre-compression logger
  5439. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5440. const Response &res) {
  5441. pre_compression_body = res.body;
  5442. pre_compression_content_type = res.get_header_value("Content-Type");
  5443. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5444. });
  5445. // Set up post-compression logger
  5446. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5447. post_compression_body = res.body;
  5448. post_compression_content_type = res.get_header_value("Content-Type");
  5449. post_compression_content_encoding =
  5450. res.get_header_value("Content-Encoding");
  5451. });
  5452. // Test with gzip compression
  5453. Headers headers;
  5454. headers.emplace("Accept-Encoding", "gzip");
  5455. auto res = cli_.Get("/compress", headers);
  5456. // Verify response was compressed
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ(StatusCode::OK_200, res->status);
  5459. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5460. // Verify pre-compression logger captured uncompressed content
  5461. EXPECT_EQ(test_content, pre_compression_body);
  5462. EXPECT_EQ("text/plain", pre_compression_content_type);
  5463. EXPECT_TRUE(pre_compression_content_encoding
  5464. .empty()); // No encoding header before compression
  5465. // Verify post-compression logger captured compressed content
  5466. EXPECT_NE(test_content,
  5467. post_compression_body); // Should be different after compression
  5468. EXPECT_EQ("text/plain", post_compression_content_type);
  5469. EXPECT_EQ("gzip", post_compression_content_encoding);
  5470. // Verify compressed content is smaller
  5471. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5472. }
  5473. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5474. const std::string test_content =
  5475. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5476. "3456789012345678901234567890";
  5477. std::string pre_compression_body;
  5478. std::string post_compression_body;
  5479. svr_.set_pre_compression_logger(
  5480. [&](const Request & /*req*/, const Response &res) {
  5481. pre_compression_body = res.body;
  5482. });
  5483. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5484. post_compression_body = res.body;
  5485. });
  5486. Headers headers;
  5487. headers.emplace("Accept-Encoding", "br");
  5488. auto res = cli_.Get("/compress", headers);
  5489. ASSERT_TRUE(res);
  5490. EXPECT_EQ(StatusCode::OK_200, res->status);
  5491. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5492. // Verify pre-compression content is uncompressed
  5493. EXPECT_EQ(test_content, pre_compression_body);
  5494. // Verify post-compression content is compressed
  5495. EXPECT_NE(test_content, post_compression_body);
  5496. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5497. }
  5498. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5499. const std::string test_content =
  5500. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5501. "3456789012345678901234567890";
  5502. std::string pre_compression_body;
  5503. std::string post_compression_body;
  5504. svr_.set_pre_compression_logger(
  5505. [&](const Request & /*req*/, const Response &res) {
  5506. pre_compression_body = res.body;
  5507. });
  5508. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5509. post_compression_body = res.body;
  5510. });
  5511. // Request without compression (use /nocompress endpoint)
  5512. Headers headers;
  5513. auto res = cli_.Get("/nocompress", headers);
  5514. ASSERT_TRUE(res);
  5515. EXPECT_EQ(StatusCode::OK_200, res->status);
  5516. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5517. // Pre-compression logger should not be called when no compression is applied
  5518. EXPECT_TRUE(
  5519. pre_compression_body.empty()); // Pre-compression logger not called
  5520. EXPECT_EQ(
  5521. test_content,
  5522. post_compression_body); // Post-compression logger captures final content
  5523. }
  5524. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5525. const std::string test_content =
  5526. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5527. "3456789012345678901234567890";
  5528. std::string pre_compression_body;
  5529. bool pre_logger_called = false;
  5530. // Set only pre-compression logger
  5531. svr_.set_pre_compression_logger(
  5532. [&](const Request & /*req*/, const Response &res) {
  5533. pre_compression_body = res.body;
  5534. pre_logger_called = true;
  5535. });
  5536. Headers headers;
  5537. headers.emplace("Accept-Encoding", "gzip");
  5538. auto res = cli_.Get("/compress", headers);
  5539. ASSERT_TRUE(res);
  5540. EXPECT_EQ(StatusCode::OK_200, res->status);
  5541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5542. // Verify pre-compression logger was called
  5543. EXPECT_TRUE(pre_logger_called);
  5544. EXPECT_EQ(test_content, pre_compression_body);
  5545. }
  5546. TEST(ZstdDecompressor, ChunkedDecompression) {
  5547. std::string data;
  5548. for (size_t i = 0; i < 32 * 1024; ++i) {
  5549. data.push_back(static_cast<char>('a' + i % 26));
  5550. }
  5551. std::string compressed_data;
  5552. {
  5553. httplib::detail::zstd_compressor compressor;
  5554. bool result = compressor.compress(
  5555. data.data(), data.size(),
  5556. /*last=*/true,
  5557. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5558. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5559. compressed_data_size);
  5560. return true;
  5561. });
  5562. ASSERT_TRUE(result);
  5563. }
  5564. std::string decompressed_data;
  5565. {
  5566. httplib::detail::zstd_decompressor decompressor;
  5567. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5568. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5569. size_t chunk_size = 130;
  5570. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5571. chunk_begin += chunk_size) {
  5572. size_t current_chunk_size =
  5573. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5574. bool result = decompressor.decompress(
  5575. compressed_data.data() + chunk_begin, current_chunk_size,
  5576. [&](const char *decompressed_data_chunk,
  5577. size_t decompressed_data_chunk_size) {
  5578. decompressed_data.insert(decompressed_data.size(),
  5579. decompressed_data_chunk,
  5580. decompressed_data_chunk_size);
  5581. return true;
  5582. });
  5583. ASSERT_TRUE(result);
  5584. }
  5585. }
  5586. ASSERT_EQ(data, decompressed_data);
  5587. }
  5588. TEST(ZstdDecompressor, Decompress) {
  5589. std::string original_text = "Compressed with ZSTD";
  5590. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5591. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5592. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5593. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5594. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5595. std::string decompressed_data;
  5596. {
  5597. httplib::detail::zstd_decompressor decompressor;
  5598. bool result = decompressor.decompress(
  5599. compressed_data.data(), compressed_data.size(),
  5600. [&](const char *decompressed_data_chunk,
  5601. size_t decompressed_data_chunk_size) {
  5602. decompressed_data.insert(decompressed_data.size(),
  5603. decompressed_data_chunk,
  5604. decompressed_data_chunk_size);
  5605. return true;
  5606. });
  5607. ASSERT_TRUE(result);
  5608. }
  5609. ASSERT_EQ(original_text, decompressed_data);
  5610. }
  5611. #endif
  5612. // Sends a raw request to a server listening at HOST:PORT.
  5613. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5614. std::string *resp = nullptr) {
  5615. auto error = Error::Success;
  5616. auto client_sock = detail::create_client_socket(
  5617. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5618. /*connection_timeout_sec=*/5, 0,
  5619. /*read_timeout_sec=*/5, 0,
  5620. /*write_timeout_sec=*/5, 0, std::string(), error);
  5621. if (client_sock == INVALID_SOCKET) { return false; }
  5622. auto ret = detail::process_client_socket(
  5623. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5624. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5625. if (req.size() !=
  5626. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5627. return false;
  5628. }
  5629. char buf[512];
  5630. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5631. while (line_reader.getline()) {
  5632. if (resp) { *resp += line_reader.ptr(); }
  5633. }
  5634. return true;
  5635. });
  5636. detail::close_socket(client_sock);
  5637. return ret;
  5638. }
  5639. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5640. Server svr;
  5641. std::string header_value;
  5642. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5643. header_value = req.get_header_value("foo");
  5644. res.set_content("ok", "text/plain");
  5645. });
  5646. thread t = thread([&] { svr.listen(HOST, PORT); });
  5647. auto se = detail::scope_exit([&] {
  5648. svr.stop();
  5649. t.join();
  5650. ASSERT_FALSE(svr.is_running());
  5651. });
  5652. svr.wait_until_ready();
  5653. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5654. // like characters are not treated the same - use vertical tab and escape.
  5655. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5656. "foo: \t \v bar \x1B\t \r\n"
  5657. "Connection: close\r\n"
  5658. "\r\n";
  5659. std::string res;
  5660. ASSERT_TRUE(send_request(5, req, &res));
  5661. EXPECT_EQ(header_value, "");
  5662. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5663. }
  5664. // Sends a raw request and verifies that there isn't a crash or exception.
  5665. static void test_raw_request(const std::string &req,
  5666. std::string *out = nullptr) {
  5667. Server svr;
  5668. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5669. res.set_content("ok", "text/plain");
  5670. });
  5671. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5672. res.set_content("ok", "text/plain");
  5673. });
  5674. svr.Get("/header_field_value_check",
  5675. [&](const Request & /*req*/, Response &res) {
  5676. res.set_content("ok", "text/plain");
  5677. });
  5678. // Server read timeout must be longer than the client read timeout for the
  5679. // bug to reproduce, probably to force the server to process a request
  5680. // without a trailing blank line.
  5681. const time_t client_read_timeout_sec = 1;
  5682. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5683. bool listen_thread_ok = false;
  5684. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5685. auto se = detail::scope_exit([&] {
  5686. svr.stop();
  5687. t.join();
  5688. ASSERT_FALSE(svr.is_running());
  5689. EXPECT_TRUE(listen_thread_ok);
  5690. });
  5691. svr.wait_until_ready();
  5692. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5693. }
  5694. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5695. // A certain header line causes an exception if the header property is parsed
  5696. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5697. test_raw_request(
  5698. "GET /hi HTTP/1.1\r\n"
  5699. " : "
  5700. " "
  5701. " ");
  5702. }
  5703. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5704. // A certain header line causes an exception if the header property *name* is
  5705. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5706. // greedy matcher and requires backtracking when there are a lot of ":"
  5707. // characters.
  5708. // This occurs with libc++ but not libstdc++.
  5709. test_raw_request(
  5710. "GET /hi HTTP/1.1\r\n"
  5711. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5712. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5713. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5714. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5715. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5716. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5717. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5718. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5719. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5720. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5721. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5722. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5723. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5724. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5725. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5726. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5727. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5728. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5729. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5730. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5731. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5732. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5733. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5734. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5735. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5736. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5737. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5738. "&&&%%%");
  5739. }
  5740. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5741. // Make sure this doesn't crash the server.
  5742. // In a previous version of the header line regex, the "\r" rendered the line
  5743. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5744. // a new position where the leading white space ended and the field value
  5745. // began.
  5746. // The crash occurs with libc++ but not libstdc++.
  5747. test_raw_request("GET /hi HTTP/1.1\r\n"
  5748. "a:" +
  5749. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5750. "\r\n"
  5751. "\r\n");
  5752. }
  5753. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5754. std::string out;
  5755. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5756. "Content-Type: text/plain\r\n"
  5757. "Transfer-Encoding: chunked\r\n"
  5758. "\r\n"
  5759. "nothex\r\n",
  5760. &out);
  5761. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5762. }
  5763. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5764. std::string out;
  5765. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5766. "Content-Type: text/plain\r\n"
  5767. "Transfer-Encoding: chunked\r\n"
  5768. "\r\n"
  5769. "3\r\n"
  5770. "xyz\r\n"
  5771. "NaN\r\n",
  5772. &out);
  5773. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5774. }
  5775. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5776. std::string out;
  5777. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5778. "Content-Type: text/plain\r\n"
  5779. "Transfer-Encoding: chunked\r\n"
  5780. "\r\n"
  5781. // Length is too large for 64 bits.
  5782. "1ffffffffffffffff\r\n"
  5783. "xyz\r\n",
  5784. &out);
  5785. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5786. }
  5787. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5788. test_raw_request("GET /hi HTTP/1.1\r\n"
  5789. "Content-Type: text/plain\r\n\r");
  5790. }
  5791. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5792. std::string out;
  5793. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5795. }
  5796. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5797. std::string out;
  5798. std::string request(
  5799. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5800. test_raw_request(request, &out);
  5801. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5802. }
  5803. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5804. std::string out;
  5805. std::string request(
  5806. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5807. test_raw_request(request, &out);
  5808. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5809. }
  5810. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5811. std::string out;
  5812. std::string request(
  5813. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5814. test_raw_request(request, &out);
  5815. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5816. }
  5817. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5818. std::string out;
  5819. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5820. "Test: \r\n\r\n",
  5821. &out);
  5822. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5823. }
  5824. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5825. Server svr;
  5826. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5827. res.set_header("Cache-Control", "no-cache");
  5828. res.set_chunked_content_provider(
  5829. "text/event-stream", [](size_t offset, DataSink &sink) {
  5830. std::string s = "data:";
  5831. s += std::to_string(offset);
  5832. s += "\n\n";
  5833. auto ret = sink.write(s.data(), s.size());
  5834. EXPECT_TRUE(ret);
  5835. std::this_thread::sleep_for(std::chrono::seconds(1));
  5836. return true;
  5837. });
  5838. });
  5839. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5840. svr.wait_until_ready();
  5841. Client client(HOST, PORT);
  5842. const Headers headers = {{"Accept", "text/event-stream"}};
  5843. auto get_thread = std::thread([&client, &headers]() {
  5844. auto res = client.Get(
  5845. "/events", headers,
  5846. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5847. });
  5848. auto se = detail::scope_exit([&] {
  5849. svr.stop();
  5850. get_thread.join();
  5851. listen_thread.join();
  5852. ASSERT_FALSE(svr.is_running());
  5853. });
  5854. // Give GET time to get a few messages.
  5855. std::this_thread::sleep_for(std::chrono::seconds(2));
  5856. }
  5857. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5858. httplib::Server svr;
  5859. svr.Post("/hi",
  5860. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5861. res.status = StatusCode::OK_200;
  5862. });
  5863. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5864. svr.wait_until_ready();
  5865. Client cli(HOST, PORT);
  5866. auto res = cli.Post("/hi", "data", "text/plain");
  5867. ASSERT_TRUE(res);
  5868. EXPECT_EQ(StatusCode::OK_200, res->status);
  5869. svr.stop();
  5870. thread.join();
  5871. ASSERT_FALSE(svr.is_running());
  5872. res = cli.Post("/hi", "data", "text/plain");
  5873. ASSERT_FALSE(res);
  5874. }
  5875. TEST(ServerStopTest, ListenFailure) {
  5876. Server svr;
  5877. auto t = thread([&]() {
  5878. auto ret = svr.listen("????", PORT);
  5879. EXPECT_FALSE(ret);
  5880. });
  5881. svr.wait_until_ready();
  5882. svr.stop();
  5883. t.join();
  5884. }
  5885. TEST(ServerStopTest, Decommision) {
  5886. Server svr;
  5887. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5888. for (int i = 0; i < 4; i++) {
  5889. auto is_even = !(i % 2);
  5890. std::thread t{[&] {
  5891. try {
  5892. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5893. if (is_even) {
  5894. throw std::runtime_error("Some thing that happens to go wrong.");
  5895. }
  5896. svr.listen(HOST, PORT);
  5897. } catch (...) { svr.decommission(); }
  5898. }};
  5899. svr.wait_until_ready();
  5900. // Server is up
  5901. {
  5902. Client cli(HOST, PORT);
  5903. auto res = cli.Get("/hi");
  5904. if (is_even) {
  5905. EXPECT_FALSE(res);
  5906. } else {
  5907. EXPECT_TRUE(res);
  5908. EXPECT_EQ("hi...", res->body);
  5909. }
  5910. }
  5911. svr.stop();
  5912. t.join();
  5913. // Server is down...
  5914. {
  5915. Client cli(HOST, PORT);
  5916. auto res = cli.Get("/hi");
  5917. EXPECT_FALSE(res);
  5918. }
  5919. }
  5920. }
  5921. // Helper function for string body upload progress tests
  5922. template <typename SetupHandler, typename ClientCall>
  5923. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5924. ClientCall &&client_call,
  5925. const string &body) {
  5926. Server svr;
  5927. setup_handler(svr);
  5928. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5929. auto se = detail::scope_exit([&] {
  5930. svr.stop();
  5931. t.join();
  5932. });
  5933. svr.wait_until_ready();
  5934. Client cli(HOST, PORT);
  5935. vector<uint64_t> progress_values;
  5936. bool progress_called = false;
  5937. auto res =
  5938. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5939. progress_values.push_back(current);
  5940. progress_called = true;
  5941. return true;
  5942. });
  5943. ASSERT_TRUE(res);
  5944. EXPECT_EQ(200, res->status);
  5945. EXPECT_TRUE(progress_called);
  5946. }
  5947. TEST(UploadProgressTest, PostStringBodyBasic) {
  5948. TestStringBodyUploadProgress(
  5949. [](Server &svr) {
  5950. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5951. res.set_content("received", "text/plain");
  5952. });
  5953. },
  5954. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5955. return cli.Post("/test", body, "text/plain", progress_callback);
  5956. },
  5957. "test data for upload progress");
  5958. }
  5959. TEST(UploadProgressTest, PutStringBodyBasic) {
  5960. TestStringBodyUploadProgress(
  5961. [](Server &svr) {
  5962. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5963. res.set_content("put received", "text/plain");
  5964. });
  5965. },
  5966. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5967. return cli.Put("/test", body, "text/plain", progress_callback);
  5968. },
  5969. "put test data for upload progress");
  5970. }
  5971. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5972. TestStringBodyUploadProgress(
  5973. [](Server &svr) {
  5974. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5975. res.set_content("patch received", "text/plain");
  5976. });
  5977. },
  5978. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5979. return cli.Patch("/test", body, "text/plain", progress_callback);
  5980. },
  5981. "patch test data for upload progress");
  5982. }
  5983. // Helper function for content provider upload progress tests
  5984. template <typename SetupHandler, typename ClientCall>
  5985. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  5986. ClientCall &&client_call) {
  5987. Server svr;
  5988. setup_handler(svr);
  5989. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5990. auto se = detail::scope_exit([&] {
  5991. svr.stop();
  5992. t.join();
  5993. });
  5994. svr.wait_until_ready();
  5995. Client cli(HOST, PORT);
  5996. vector<uint64_t> progress_values;
  5997. auto res =
  5998. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5999. progress_values.push_back(current);
  6000. return true;
  6001. });
  6002. ASSERT_TRUE(res);
  6003. EXPECT_EQ(200, res->status);
  6004. EXPECT_FALSE(progress_values.empty());
  6005. }
  6006. TEST(UploadProgressTest, PostContentProviderProgress) {
  6007. TestContentProviderUploadProgress(
  6008. [](Server &svr) {
  6009. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6010. res.set_content("provider received", "text/plain");
  6011. });
  6012. },
  6013. [](Client &cli, UploadProgress progress_callback) {
  6014. return cli.Post(
  6015. "/test", 10,
  6016. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6017. sink.os << "test data";
  6018. return true;
  6019. },
  6020. "text/plain", progress_callback);
  6021. });
  6022. }
  6023. // Helper function for multipart upload progress tests
  6024. template <typename SetupHandler, typename ClientCall>
  6025. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6026. ClientCall &&client_call,
  6027. const string &endpoint) {
  6028. Server svr;
  6029. setup_handler(svr);
  6030. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6031. auto se = detail::scope_exit([&] {
  6032. svr.stop();
  6033. t.join();
  6034. });
  6035. svr.wait_until_ready();
  6036. Client cli(HOST, PORT);
  6037. vector<uint64_t> progress_values;
  6038. UploadFormDataItems items = {
  6039. {"field1", "value1", "", ""},
  6040. {"field2", "longer value for progress tracking test", "", ""},
  6041. {"file1", "file content data for upload progress", "test.txt",
  6042. "text/plain"}};
  6043. auto res = client_call(cli, endpoint, items,
  6044. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6045. progress_values.push_back(current);
  6046. return true;
  6047. });
  6048. ASSERT_TRUE(res);
  6049. EXPECT_EQ(200, res->status);
  6050. EXPECT_FALSE(progress_values.empty());
  6051. }
  6052. TEST(UploadProgressTest, PostMultipartProgress) {
  6053. TestMultipartUploadProgress(
  6054. [](Server &svr) {
  6055. svr.Post("/multipart", [](const Request &req, Response &res) {
  6056. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6057. res.set_content("multipart received", "text/plain");
  6058. });
  6059. },
  6060. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6061. UploadProgress progress_callback) {
  6062. return cli.Post(endpoint, items, progress_callback);
  6063. },
  6064. "/multipart");
  6065. }
  6066. // Helper function for basic download progress tests
  6067. template <typename SetupHandler, typename ClientCall>
  6068. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6069. ClientCall &&client_call, const string &endpoint,
  6070. size_t expected_content_size) {
  6071. Server svr;
  6072. setup_handler(svr);
  6073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6074. auto se = detail::scope_exit([&] {
  6075. svr.stop();
  6076. t.join();
  6077. });
  6078. svr.wait_until_ready();
  6079. Client cli(HOST, PORT);
  6080. vector<uint64_t> progress_values;
  6081. auto res = client_call(cli, endpoint,
  6082. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6083. progress_values.push_back(current);
  6084. return true;
  6085. });
  6086. ASSERT_TRUE(res);
  6087. EXPECT_EQ(200, res->status);
  6088. EXPECT_FALSE(progress_values.empty());
  6089. EXPECT_EQ(expected_content_size, res->body.size());
  6090. }
  6091. TEST(DownloadProgressTest, GetBasic) {
  6092. TestBasicDownloadProgress(
  6093. [](Server &svr) {
  6094. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6095. string content(1000, 'D');
  6096. res.set_content(content, "text/plain");
  6097. });
  6098. },
  6099. [](Client &cli, const string &endpoint,
  6100. DownloadProgress progress_callback) {
  6101. return cli.Get(endpoint, progress_callback);
  6102. },
  6103. "/download", 1000u);
  6104. }
  6105. // Helper function for content receiver download progress tests
  6106. template <typename SetupHandler, typename ClientCall>
  6107. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6108. ClientCall &&client_call,
  6109. const string &endpoint,
  6110. size_t expected_content_size) {
  6111. Server svr;
  6112. setup_handler(svr);
  6113. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6114. auto se = detail::scope_exit([&] {
  6115. svr.stop();
  6116. t.join();
  6117. });
  6118. svr.wait_until_ready();
  6119. Client cli(HOST, PORT);
  6120. vector<uint64_t> progress_values;
  6121. string received_body;
  6122. auto res = client_call(
  6123. cli, endpoint,
  6124. [&](const char *data, size_t data_length) -> bool {
  6125. received_body.append(data, data_length);
  6126. return true;
  6127. },
  6128. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6129. progress_values.push_back(current);
  6130. return true;
  6131. });
  6132. ASSERT_TRUE(res);
  6133. EXPECT_EQ(200, res->status);
  6134. EXPECT_FALSE(progress_values.empty());
  6135. EXPECT_EQ(expected_content_size, received_body.size());
  6136. EXPECT_TRUE(res->body.empty());
  6137. }
  6138. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6139. TestContentReceiverDownloadProgress(
  6140. [](Server &svr) {
  6141. svr.Get("/download-receiver",
  6142. [](const Request & /*req*/, Response &res) {
  6143. string content(2000, 'R');
  6144. res.set_content(content, "text/plain");
  6145. });
  6146. },
  6147. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6148. DownloadProgress progress_callback) {
  6149. return cli.Get(endpoint, content_receiver, progress_callback);
  6150. },
  6151. "/download-receiver", 2000u);
  6152. }
  6153. TEST(StreamingTest, NoContentLengthStreaming) {
  6154. Server svr;
  6155. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6156. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6157. if (offset < 6) {
  6158. sink.os << (offset < 3 ? "a" : "b");
  6159. } else {
  6160. sink.done();
  6161. }
  6162. return true;
  6163. });
  6164. });
  6165. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6166. auto listen_se = detail::scope_exit([&] {
  6167. svr.stop();
  6168. listen_thread.join();
  6169. ASSERT_FALSE(svr.is_running());
  6170. });
  6171. svr.wait_until_ready();
  6172. Client client(HOST, PORT);
  6173. auto get_thread = std::thread([&client]() {
  6174. std::string s;
  6175. auto res =
  6176. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6177. s += std::string(data, len);
  6178. return true;
  6179. });
  6180. ASSERT_TRUE(res);
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. EXPECT_EQ("aaabbb", s);
  6183. });
  6184. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6185. // Give GET time to get a few messages.
  6186. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6187. }
  6188. TEST(MountTest, Unmount) {
  6189. Server svr;
  6190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6191. auto se = detail::scope_exit([&] {
  6192. svr.stop();
  6193. listen_thread.join();
  6194. ASSERT_FALSE(svr.is_running());
  6195. });
  6196. svr.wait_until_ready();
  6197. Client cli("localhost", PORT);
  6198. svr.set_mount_point("/mount2", "./www2");
  6199. auto res = cli.Get("/");
  6200. ASSERT_TRUE(res);
  6201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6202. res = cli.Get("/mount2/dir/test.html");
  6203. ASSERT_TRUE(res);
  6204. EXPECT_EQ(StatusCode::OK_200, res->status);
  6205. svr.set_mount_point("/", "./www");
  6206. res = cli.Get("/dir/");
  6207. ASSERT_TRUE(res);
  6208. EXPECT_EQ(StatusCode::OK_200, res->status);
  6209. svr.remove_mount_point("/");
  6210. res = cli.Get("/dir/");
  6211. ASSERT_TRUE(res);
  6212. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6213. svr.remove_mount_point("/mount2");
  6214. res = cli.Get("/mount2/dir/test.html");
  6215. ASSERT_TRUE(res);
  6216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6217. }
  6218. TEST(MountTest, Redicect) {
  6219. Server svr;
  6220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6221. auto se = detail::scope_exit([&] {
  6222. svr.stop();
  6223. listen_thread.join();
  6224. ASSERT_FALSE(svr.is_running());
  6225. });
  6226. svr.set_mount_point("/", "./www");
  6227. svr.wait_until_ready();
  6228. Client cli("localhost", PORT);
  6229. auto res = cli.Get("/dir/");
  6230. ASSERT_TRUE(res);
  6231. EXPECT_EQ(StatusCode::OK_200, res->status);
  6232. res = cli.Get("/dir");
  6233. ASSERT_TRUE(res);
  6234. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6235. res = cli.Get("/file");
  6236. ASSERT_TRUE(res);
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. res = cli.Get("/file/");
  6239. ASSERT_TRUE(res);
  6240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6241. cli.set_follow_location(true);
  6242. res = cli.Get("/dir");
  6243. ASSERT_TRUE(res);
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. }
  6246. TEST(MountTest, MultibytesPathName) {
  6247. Server svr;
  6248. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6249. auto se = detail::scope_exit([&] {
  6250. svr.stop();
  6251. listen_thread.join();
  6252. ASSERT_FALSE(svr.is_running());
  6253. });
  6254. svr.set_mount_point("/", "./www");
  6255. svr.wait_until_ready();
  6256. Client cli("localhost", PORT);
  6257. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6258. ASSERT_TRUE(res);
  6259. EXPECT_EQ(StatusCode::OK_200, res->status);
  6260. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6261. }
  6262. TEST(KeepAliveTest, ReadTimeout) {
  6263. Server svr;
  6264. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6265. std::this_thread::sleep_for(std::chrono::seconds(2));
  6266. res.set_content("a", "text/plain");
  6267. });
  6268. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6269. res.set_content("b", "text/plain");
  6270. });
  6271. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6272. auto se = detail::scope_exit([&] {
  6273. svr.stop();
  6274. listen_thread.join();
  6275. ASSERT_FALSE(svr.is_running());
  6276. });
  6277. svr.wait_until_ready();
  6278. Client cli("localhost", PORT);
  6279. cli.set_keep_alive(true);
  6280. cli.set_read_timeout(std::chrono::seconds(1));
  6281. auto resa = cli.Get("/a");
  6282. ASSERT_FALSE(resa);
  6283. EXPECT_EQ(Error::Read, resa.error());
  6284. auto resb = cli.Get("/b");
  6285. ASSERT_TRUE(resb);
  6286. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6287. EXPECT_EQ("b", resb->body);
  6288. }
  6289. TEST(KeepAliveTest, MaxCount) {
  6290. size_t keep_alive_max_count = 3;
  6291. Server svr;
  6292. svr.set_keep_alive_max_count(keep_alive_max_count);
  6293. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6294. res.set_content("Hello World!", "text/plain");
  6295. });
  6296. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6297. auto se = detail::scope_exit([&] {
  6298. svr.stop();
  6299. listen_thread.join();
  6300. ASSERT_FALSE(svr.is_running());
  6301. });
  6302. svr.wait_until_ready();
  6303. Client cli(HOST, PORT);
  6304. cli.set_keep_alive(true);
  6305. for (size_t i = 0; i < 5; i++) {
  6306. auto result = cli.Get("/hi");
  6307. ASSERT_TRUE(result);
  6308. EXPECT_EQ(StatusCode::OK_200, result->status);
  6309. if (i == keep_alive_max_count - 1) {
  6310. EXPECT_EQ("close", result->get_header_value("Connection"));
  6311. } else {
  6312. EXPECT_FALSE(result->has_header("Connection"));
  6313. }
  6314. }
  6315. }
  6316. TEST(KeepAliveTest, Issue1041) {
  6317. Server svr;
  6318. svr.set_keep_alive_timeout(3);
  6319. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6320. res.set_content("Hello World!", "text/plain");
  6321. });
  6322. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6323. auto se = detail::scope_exit([&] {
  6324. svr.stop();
  6325. listen_thread.join();
  6326. ASSERT_FALSE(svr.is_running());
  6327. });
  6328. svr.wait_until_ready();
  6329. Client cli(HOST, PORT);
  6330. cli.set_keep_alive(true);
  6331. auto result = cli.Get("/hi");
  6332. ASSERT_TRUE(result);
  6333. EXPECT_EQ(StatusCode::OK_200, result->status);
  6334. std::this_thread::sleep_for(std::chrono::seconds(5));
  6335. result = cli.Get("/hi");
  6336. ASSERT_TRUE(result);
  6337. EXPECT_EQ(StatusCode::OK_200, result->status);
  6338. }
  6339. TEST(KeepAliveTest, Issue1959) {
  6340. Server svr;
  6341. svr.set_keep_alive_timeout(5);
  6342. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6343. res.set_content("a", "text/plain");
  6344. });
  6345. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6346. auto se = detail::scope_exit([&] {
  6347. if (!svr.is_running()) return;
  6348. svr.stop();
  6349. listen_thread.join();
  6350. ASSERT_FALSE(svr.is_running());
  6351. });
  6352. svr.wait_until_ready();
  6353. Client cli("localhost", PORT);
  6354. cli.set_keep_alive(true);
  6355. using namespace std::chrono;
  6356. auto start = steady_clock::now();
  6357. cli.Get("/a");
  6358. svr.stop();
  6359. listen_thread.join();
  6360. auto end = steady_clock::now();
  6361. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6362. EXPECT_LT(elapsed, 5000);
  6363. }
  6364. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6365. TEST(KeepAliveTest, SSLClientReconnection) {
  6366. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6367. ASSERT_TRUE(svr.is_valid());
  6368. svr.set_keep_alive_timeout(1);
  6369. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6370. res.set_content("Hello World!", "text/plain");
  6371. });
  6372. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6373. auto se = detail::scope_exit([&] {
  6374. svr.stop();
  6375. listen_thread.join();
  6376. ASSERT_FALSE(svr.is_running());
  6377. });
  6378. svr.wait_until_ready();
  6379. SSLClient cli(HOST, PORT);
  6380. cli.enable_server_certificate_verification(false);
  6381. cli.set_keep_alive(true);
  6382. auto result = cli.Get("/hi");
  6383. ASSERT_TRUE(result);
  6384. EXPECT_EQ(StatusCode::OK_200, result->status);
  6385. result = cli.Get("/hi");
  6386. ASSERT_TRUE(result);
  6387. EXPECT_EQ(StatusCode::OK_200, result->status);
  6388. std::this_thread::sleep_for(std::chrono::seconds(2));
  6389. // Recoonect
  6390. result = cli.Get("/hi");
  6391. ASSERT_TRUE(result);
  6392. EXPECT_EQ(StatusCode::OK_200, result->status);
  6393. result = cli.Get("/hi");
  6394. ASSERT_TRUE(result);
  6395. EXPECT_EQ(StatusCode::OK_200, result->status);
  6396. }
  6397. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6399. ASSERT_TRUE(svr.is_valid());
  6400. svr.set_keep_alive_timeout(1);
  6401. std::string content = "reconnect";
  6402. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6403. res.set_content("Hello World!", "text/plain");
  6404. });
  6405. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6406. auto se = detail::scope_exit([&] {
  6407. svr.stop();
  6408. listen_thread.join();
  6409. ASSERT_FALSE(svr.is_running());
  6410. });
  6411. svr.wait_until_ready();
  6412. SSLClient cli(HOST, PORT);
  6413. cli.enable_server_certificate_verification(false);
  6414. cli.set_keep_alive(true);
  6415. auto result = cli.Post(
  6416. "/hi", content.size(),
  6417. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6418. sink.write(content.c_str(), content.size());
  6419. return true;
  6420. },
  6421. "text/plain");
  6422. ASSERT_TRUE(result);
  6423. EXPECT_EQ(200, result->status);
  6424. std::this_thread::sleep_for(std::chrono::seconds(2));
  6425. // Recoonect
  6426. result = cli.Post(
  6427. "/hi", content.size(),
  6428. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6429. sink.write(content.c_str(), content.size());
  6430. return true;
  6431. },
  6432. "text/plain");
  6433. ASSERT_TRUE(result);
  6434. EXPECT_EQ(200, result->status);
  6435. result = cli.Post(
  6436. "/hi", content.size(),
  6437. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6438. sink.write(content.c_str(), content.size());
  6439. return true;
  6440. },
  6441. "text/plain");
  6442. ASSERT_TRUE(result);
  6443. EXPECT_EQ(200, result->status);
  6444. }
  6445. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6446. {
  6447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6448. ASSERT_TRUE(svr.is_valid());
  6449. svr.Get("/sni", [&](const Request &req, Response &res) {
  6450. std::string expected;
  6451. if (req.ssl) {
  6452. if (const char *sni =
  6453. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6454. expected = sni;
  6455. }
  6456. }
  6457. EXPECT_EQ(expected, req.get_param_value("expected"));
  6458. res.set_content("ok", "text/plain");
  6459. });
  6460. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6461. auto se = detail::scope_exit([&] {
  6462. svr.stop();
  6463. listen_thread.join();
  6464. ASSERT_FALSE(svr.is_running());
  6465. });
  6466. svr.wait_until_ready();
  6467. {
  6468. SSLClient cli("localhost", PORT);
  6469. cli.enable_server_certificate_verification(false);
  6470. auto res = cli.Get("/sni?expected=localhost");
  6471. ASSERT_TRUE(res);
  6472. }
  6473. {
  6474. SSLClient cli("::1", PORT);
  6475. cli.enable_server_certificate_verification(false);
  6476. auto res = cli.Get("/sni?expected=");
  6477. // NOTE: This may fail if the server is listening on IPv4 only
  6478. // (e.g., when localhost resolves to 127.0.0.1 only)
  6479. if (res) {
  6480. EXPECT_EQ(StatusCode::OK_200, res->status);
  6481. } else {
  6482. EXPECT_EQ(Error::Connection, res.error());
  6483. }
  6484. }
  6485. }
  6486. }
  6487. #endif
  6488. TEST(ClientProblemDetectionTest, ContentProvider) {
  6489. Server svr;
  6490. size_t content_length = 1024 * 1024;
  6491. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6492. res.set_content_provider(
  6493. content_length, "text/plain",
  6494. [&](size_t offset, size_t length, DataSink &sink) {
  6495. auto out_len = std::min(length, static_cast<size_t>(1024));
  6496. std::string out(out_len, '@');
  6497. sink.write(out.data(), out_len);
  6498. return offset < 4096;
  6499. },
  6500. [](bool success) { ASSERT_FALSE(success); });
  6501. });
  6502. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6503. res.set_content_provider(
  6504. 0, "text/plain",
  6505. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6506. EXPECT_TRUE(false);
  6507. return true;
  6508. },
  6509. [](bool success) { ASSERT_FALSE(success); });
  6510. });
  6511. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6512. auto se = detail::scope_exit([&] {
  6513. svr.stop();
  6514. listen_thread.join();
  6515. ASSERT_FALSE(svr.is_running());
  6516. });
  6517. svr.wait_until_ready();
  6518. Client cli("localhost", PORT);
  6519. {
  6520. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6521. size_t /*data_length*/) { return false; });
  6522. ASSERT_FALSE(res);
  6523. }
  6524. {
  6525. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6526. size_t /*data_length*/) { return false; });
  6527. ASSERT_TRUE(res);
  6528. }
  6529. }
  6530. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6531. Server svr;
  6532. svr.set_error_handler([](Request const &, Response &res) -> void {
  6533. res.set_chunked_content_provider(
  6534. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6535. sink.os << "hello";
  6536. sink.os << "world";
  6537. sink.done();
  6538. return true;
  6539. });
  6540. });
  6541. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6542. auto se = detail::scope_exit([&] {
  6543. svr.stop();
  6544. listen_thread.join();
  6545. ASSERT_FALSE(svr.is_running());
  6546. });
  6547. svr.wait_until_ready();
  6548. Client cli("localhost", PORT);
  6549. auto res = cli.Get("/");
  6550. ASSERT_TRUE(res);
  6551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6552. EXPECT_EQ("helloworld", res->body);
  6553. }
  6554. TEST(LongPollingTest, ClientCloseDetection) {
  6555. Server svr;
  6556. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6557. res.set_chunked_content_provider(
  6558. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6559. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6560. sink.os << "hello";
  6561. auto count = 10;
  6562. while (count > 0 && sink.is_writable()) {
  6563. this_thread::sleep_for(chrono::milliseconds(10));
  6564. count--;
  6565. }
  6566. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6567. return true;
  6568. });
  6569. });
  6570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6571. auto se = detail::scope_exit([&] {
  6572. svr.stop();
  6573. listen_thread.join();
  6574. ASSERT_FALSE(svr.is_running());
  6575. });
  6576. svr.wait_until_ready();
  6577. Client cli("localhost", PORT);
  6578. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6579. EXPECT_EQ("hello", string(data, data_length));
  6580. return false; // close the socket immediately.
  6581. });
  6582. ASSERT_FALSE(res);
  6583. }
  6584. TEST(GetWithParametersTest, GetWithParameters) {
  6585. Server svr;
  6586. svr.Get("/", [&](const Request &req, Response &) {
  6587. EXPECT_EQ("world", req.get_param_value("hello"));
  6588. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6589. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6590. });
  6591. svr.Get("/params", [&](const Request &req, Response &) {
  6592. EXPECT_EQ("world", req.get_param_value("hello"));
  6593. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6594. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6595. });
  6596. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6597. EXPECT_EQ("resource-id", req.matches[1]);
  6598. EXPECT_EQ("foo", req.get_param_value("param1"));
  6599. EXPECT_EQ("bar", req.get_param_value("param2"));
  6600. });
  6601. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6602. EXPECT_EQ("user-id", req.path_params.at("id"));
  6603. EXPECT_EQ("foo", req.get_param_value("param1"));
  6604. EXPECT_EQ("bar", req.get_param_value("param2"));
  6605. });
  6606. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6607. auto se = detail::scope_exit([&] {
  6608. svr.stop();
  6609. listen_thread.join();
  6610. ASSERT_FALSE(svr.is_running());
  6611. });
  6612. svr.wait_until_ready();
  6613. {
  6614. Client cli(HOST, PORT);
  6615. Params params;
  6616. params.emplace("hello", "world");
  6617. params.emplace("hello2", "world2");
  6618. params.emplace("hello3", "world3");
  6619. auto res = cli.Get("/", params, Headers{});
  6620. ASSERT_TRUE(res);
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. }
  6623. {
  6624. Client cli(HOST, PORT);
  6625. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6626. ASSERT_TRUE(res);
  6627. EXPECT_EQ(StatusCode::OK_200, res->status);
  6628. }
  6629. {
  6630. Client cli(HOST, PORT);
  6631. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6632. ASSERT_TRUE(res);
  6633. EXPECT_EQ(StatusCode::OK_200, res->status);
  6634. }
  6635. {
  6636. Client cli(HOST, PORT);
  6637. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6638. ASSERT_TRUE(res);
  6639. EXPECT_EQ(StatusCode::OK_200, res->status);
  6640. }
  6641. }
  6642. TEST(GetWithParametersTest, GetWithParameters2) {
  6643. Server svr;
  6644. svr.Get("/", [&](const Request &req, Response &res) {
  6645. auto text = req.get_param_value("hello");
  6646. res.set_content(text, "text/plain");
  6647. });
  6648. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6649. auto se = detail::scope_exit([&] {
  6650. svr.stop();
  6651. listen_thread.join();
  6652. ASSERT_FALSE(svr.is_running());
  6653. });
  6654. svr.wait_until_ready();
  6655. Client cli("localhost", PORT);
  6656. Params params;
  6657. params.emplace("hello", "world");
  6658. std::string body;
  6659. auto res = cli.Get("/", params, Headers{},
  6660. [&](const char *data, size_t data_length) {
  6661. body.append(data, data_length);
  6662. return true;
  6663. });
  6664. ASSERT_TRUE(res);
  6665. EXPECT_EQ(StatusCode::OK_200, res->status);
  6666. EXPECT_EQ("world", body);
  6667. }
  6668. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6669. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6670. auto host = "httpcan.org";
  6671. auto path = std::string{"/range/32"};
  6672. #else
  6673. auto host = "nghttp2.org";
  6674. auto path = std::string{"/httpbin/range/32"};
  6675. #endif
  6676. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6677. SSLClient cli(host);
  6678. #else
  6679. Client cli(host);
  6680. #endif
  6681. cli.set_default_headers({make_range_header({{1, 10}})});
  6682. cli.set_connection_timeout(5);
  6683. {
  6684. auto res = cli.Get(path);
  6685. ASSERT_TRUE(res);
  6686. EXPECT_EQ("bcdefghijk", res->body);
  6687. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6688. }
  6689. {
  6690. auto res = cli.Get(path);
  6691. ASSERT_TRUE(res);
  6692. EXPECT_EQ("bcdefghijk", res->body);
  6693. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6694. }
  6695. }
  6696. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6697. Server svr;
  6698. svr.set_default_headers({{"Hello", "World"}});
  6699. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6700. res.set_content("ok", "text/plain");
  6701. });
  6702. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6703. auto se = detail::scope_exit([&] {
  6704. svr.stop();
  6705. listen_thread.join();
  6706. ASSERT_FALSE(svr.is_running());
  6707. });
  6708. svr.wait_until_ready();
  6709. Client cli("localhost", PORT);
  6710. auto res = cli.Get("/");
  6711. ASSERT_TRUE(res);
  6712. EXPECT_EQ(StatusCode::OK_200, res->status);
  6713. EXPECT_EQ("ok", res->body);
  6714. EXPECT_EQ("World", res->get_header_value("Hello"));
  6715. }
  6716. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6717. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6718. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6719. ASSERT_TRUE(svr.is_valid());
  6720. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6721. std::this_thread::sleep_for(std::chrono::seconds(2));
  6722. res.set_content("a", "text/plain");
  6723. });
  6724. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6725. res.set_content("b", "text/plain");
  6726. });
  6727. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6728. auto se = detail::scope_exit([&] {
  6729. svr.stop();
  6730. listen_thread.join();
  6731. ASSERT_FALSE(svr.is_running());
  6732. });
  6733. svr.wait_until_ready();
  6734. SSLClient cli("localhost", PORT);
  6735. cli.enable_server_certificate_verification(false);
  6736. cli.set_keep_alive(true);
  6737. cli.set_read_timeout(std::chrono::seconds(1));
  6738. auto resa = cli.Get("/a");
  6739. ASSERT_TRUE(!resa);
  6740. EXPECT_EQ(Error::Read, resa.error());
  6741. auto resb = cli.Get("/b");
  6742. ASSERT_TRUE(resb);
  6743. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6744. EXPECT_EQ("b", resb->body);
  6745. }
  6746. #endif
  6747. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6748. protected:
  6749. ServerTestWithAI_PASSIVE()
  6750. : cli_(HOST, PORT)
  6751. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6752. ,
  6753. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6754. #endif
  6755. {
  6756. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6757. cli_.enable_server_certificate_verification(false);
  6758. #endif
  6759. }
  6760. virtual void SetUp() {
  6761. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6762. res.set_content("Hello World!", "text/plain");
  6763. });
  6764. t_ = thread(
  6765. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6766. svr_.wait_until_ready();
  6767. }
  6768. virtual void TearDown() {
  6769. svr_.stop();
  6770. t_.join();
  6771. }
  6772. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6773. SSLClient cli_;
  6774. SSLServer svr_;
  6775. #else
  6776. Client cli_;
  6777. Server svr_;
  6778. #endif
  6779. thread t_;
  6780. };
  6781. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6782. auto res = cli_.Get("/hi");
  6783. ASSERT_TRUE(res);
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6786. EXPECT_EQ("Hello World!", res->body);
  6787. }
  6788. class ServerUpDownTest : public ::testing::Test {
  6789. protected:
  6790. ServerUpDownTest() : cli_(HOST, PORT) {}
  6791. virtual void SetUp() {
  6792. t_ = thread([&]() {
  6793. svr_.bind_to_any_port(HOST);
  6794. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6795. ASSERT_TRUE(svr_.listen_after_bind());
  6796. });
  6797. svr_.wait_until_ready();
  6798. }
  6799. virtual void TearDown() {
  6800. svr_.stop();
  6801. t_.join();
  6802. }
  6803. Client cli_;
  6804. Server svr_;
  6805. thread t_;
  6806. };
  6807. TEST_F(ServerUpDownTest, QuickStartStop) {
  6808. // Should not crash, especially when run with
  6809. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6810. }
  6811. class PayloadMaxLengthTest : public ::testing::Test {
  6812. protected:
  6813. PayloadMaxLengthTest()
  6814. : cli_(HOST, PORT)
  6815. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6816. ,
  6817. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6818. #endif
  6819. {
  6820. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6821. cli_.enable_server_certificate_verification(false);
  6822. #endif
  6823. }
  6824. virtual void SetUp() {
  6825. svr_.set_payload_max_length(8);
  6826. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6827. res.set_content("test", "text/plain");
  6828. });
  6829. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6830. svr_.wait_until_ready();
  6831. }
  6832. virtual void TearDown() {
  6833. svr_.stop();
  6834. t_.join();
  6835. }
  6836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6837. SSLClient cli_;
  6838. SSLServer svr_;
  6839. #else
  6840. Client cli_;
  6841. Server svr_;
  6842. #endif
  6843. thread t_;
  6844. };
  6845. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6846. auto res = cli_.Post("/test", "123456789", "text/plain");
  6847. ASSERT_TRUE(res);
  6848. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6849. res = cli_.Post("/test", "12345678", "text/plain");
  6850. ASSERT_TRUE(res);
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. }
  6853. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6854. // Test chunked encoding with payload exceeding the 8-byte limit
  6855. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6856. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6857. ASSERT_TRUE(res);
  6858. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6859. }
  6860. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6861. // Test chunked encoding with payload within the 8-byte limit
  6862. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6863. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. }
  6867. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6868. // Test using send_request to send chunked data exceeding payload limit
  6869. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6870. "Host: " +
  6871. std::string(HOST) + ":" + std::to_string(PORT) +
  6872. "\r\n"
  6873. "Transfer-Encoding: chunked\r\n"
  6874. "Connection: close\r\n"
  6875. "\r\n"
  6876. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6877. "0123456789\r\n"
  6878. "0\r\n" // End chunk
  6879. "\r\n";
  6880. std::string response;
  6881. bool result = send_request(1, chunked_request, &response);
  6882. if (!result) {
  6883. // If send_request fails, it might be because the server closed the
  6884. // connection due to payload limit enforcement, which is acceptable
  6885. SUCCEED()
  6886. << "Server rejected oversized chunked request (connection closed)";
  6887. } else {
  6888. // If we got a response, check if it's an error response or connection was
  6889. // closed early Short response length indicates connection was closed due to
  6890. // payload limit
  6891. if (response.length() <= 10) {
  6892. SUCCEED() << "Server closed connection for oversized chunked request";
  6893. } else {
  6894. // Check for error status codes
  6895. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6896. response.find("Payload Too Large") != std::string::npos ||
  6897. response.find("400") != std::string::npos);
  6898. }
  6899. }
  6900. }
  6901. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6902. // Test request without Content-Length header exceeding payload limit
  6903. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6904. "Host: " +
  6905. std::string(HOST) + ":" +
  6906. std::to_string(PORT) +
  6907. "\r\n"
  6908. "Connection: close\r\n"
  6909. "\r\n";
  6910. // Add payload exceeding the 8-byte limit
  6911. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6912. request_without_content_length += large_payload;
  6913. std::string response;
  6914. bool result = send_request(1, request_without_content_length, &response);
  6915. if (!result) {
  6916. // If send_request fails, server likely closed connection due to payload
  6917. // limit
  6918. SUCCEED() << "Server rejected oversized request without Content-Length "
  6919. "(connection closed)";
  6920. } else {
  6921. // Check if server responded with error or closed connection early
  6922. if (response.length() <= 10) {
  6923. SUCCEED() << "Server closed connection for oversized request without "
  6924. "Content-Length";
  6925. } else {
  6926. // Check for error status codes
  6927. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6928. response.find("Payload Too Large") != std::string::npos ||
  6929. response.find("400") != std::string::npos);
  6930. }
  6931. }
  6932. }
  6933. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6934. // Test request without Content-Length header within payload limit
  6935. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6936. "Host: " +
  6937. std::string(HOST) + ":" +
  6938. std::to_string(PORT) +
  6939. "\r\n"
  6940. "Connection: close\r\n"
  6941. "\r\n";
  6942. // Add payload within the 8-byte limit
  6943. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6944. request_without_content_length += small_payload;
  6945. std::string response;
  6946. bool result = send_request(1, request_without_content_length, &response);
  6947. // For requests without Content-Length, the server may have different behavior
  6948. // The key is that it should not reject due to payload limit for small
  6949. // payloads
  6950. if (result) {
  6951. // Check for any HTTP response (success or error, but not connection closed)
  6952. if (response.length() > 10) {
  6953. SUCCEED()
  6954. << "Server processed request without Content-Length within limit";
  6955. } else {
  6956. // Short response might indicate connection closed, which is acceptable
  6957. SUCCEED() << "Server closed connection for request without "
  6958. "Content-Length (acceptable behavior)";
  6959. }
  6960. } else {
  6961. // Connection failure might be due to protocol requirements
  6962. SUCCEED() << "Connection issue with request without Content-Length "
  6963. "(environment-specific)";
  6964. }
  6965. }
  6966. class LargePayloadMaxLengthTest : public ::testing::Test {
  6967. protected:
  6968. LargePayloadMaxLengthTest()
  6969. : cli_(HOST, PORT)
  6970. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6971. ,
  6972. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6973. #endif
  6974. {
  6975. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6976. cli_.enable_server_certificate_verification(false);
  6977. #endif
  6978. }
  6979. virtual void SetUp() {
  6980. // Set 10MB payload limit
  6981. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6982. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  6983. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6984. res.set_content("Large payload test", "text/plain");
  6985. });
  6986. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6987. svr_.wait_until_ready();
  6988. }
  6989. virtual void TearDown() {
  6990. svr_.stop();
  6991. t_.join();
  6992. }
  6993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6994. SSLClient cli_;
  6995. SSLServer svr_;
  6996. #else
  6997. Client cli_;
  6998. Server svr_;
  6999. #endif
  7000. thread t_;
  7001. };
  7002. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7003. // Test chunked encoding with payload within 10MB limit
  7004. std::string medium_payload(5 * 1024 * 1024,
  7005. 'A'); // 5MB payload, within 10MB limit
  7006. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7007. ASSERT_TRUE(res);
  7008. EXPECT_EQ(StatusCode::OK_200, res->status);
  7009. }
  7010. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7011. // Test chunked encoding with payload exceeding 10MB limit
  7012. std::string large_payload(12 * 1024 * 1024,
  7013. 'B'); // 12MB payload, exceeds 10MB limit
  7014. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7015. ASSERT_TRUE(res);
  7016. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7017. }
  7018. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7019. // Test request without Content-Length header within 10MB limit
  7020. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7021. "Host: " +
  7022. std::string(HOST) + ":" +
  7023. std::to_string(PORT) +
  7024. "\r\n"
  7025. "Connection: close\r\n"
  7026. "\r\n";
  7027. // Add 1MB payload (within 10MB limit)
  7028. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7029. request_without_content_length += medium_payload;
  7030. std::string response;
  7031. bool result = send_request(5, request_without_content_length, &response);
  7032. if (result) {
  7033. // Should get a proper HTTP response for payloads within limit
  7034. if (response.length() > 10) {
  7035. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7036. "10MB limit";
  7037. } else {
  7038. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7039. "Content-Length)";
  7040. }
  7041. } else {
  7042. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7043. }
  7044. }
  7045. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7046. // Test request without Content-Length header exceeding 10MB limit
  7047. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7048. "Host: " +
  7049. std::string(HOST) + ":" +
  7050. std::to_string(PORT) +
  7051. "\r\n"
  7052. "Connection: close\r\n"
  7053. "\r\n";
  7054. // Add 12MB payload (exceeds 10MB limit)
  7055. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7056. request_without_content_length += large_payload;
  7057. std::string response;
  7058. bool result = send_request(10, request_without_content_length, &response);
  7059. if (!result) {
  7060. // Server should close connection due to payload limit
  7061. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7062. "(connection closed)";
  7063. } else {
  7064. // Check for error response
  7065. if (response.length() <= 10) {
  7066. SUCCEED()
  7067. << "Server closed connection for 12MB request exceeding 10MB limit";
  7068. } else {
  7069. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7070. response.find("Payload Too Large") != std::string::npos ||
  7071. response.find("400") != std::string::npos);
  7072. }
  7073. }
  7074. }
  7075. TEST(HostAndPortPropertiesTest, NoSSL) {
  7076. httplib::Client cli("www.google.com", 1234);
  7077. ASSERT_EQ("www.google.com", cli.host());
  7078. ASSERT_EQ(1234, cli.port());
  7079. }
  7080. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7081. httplib::Client cli("www.google.com:1234");
  7082. ASSERT_EQ("www.google.com", cli.host());
  7083. ASSERT_EQ(1234, cli.port());
  7084. }
  7085. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7086. TEST(HostAndPortPropertiesTest, SSL) {
  7087. httplib::SSLClient cli("www.google.com");
  7088. ASSERT_EQ("www.google.com", cli.host());
  7089. ASSERT_EQ(443, cli.port());
  7090. }
  7091. #endif
  7092. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7093. TEST(SSLClientTest, UpdateCAStore) {
  7094. httplib::SSLClient httplib_client("www.google.com");
  7095. auto ca_store_1 = X509_STORE_new();
  7096. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7097. nullptr);
  7098. httplib_client.set_ca_cert_store(ca_store_1);
  7099. auto ca_store_2 = X509_STORE_new();
  7100. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7101. nullptr);
  7102. httplib_client.set_ca_cert_store(ca_store_2);
  7103. }
  7104. TEST(SSLClientTest, ServerNameIndication_Online) {
  7105. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7106. auto host = "httpcan.org";
  7107. auto path = std::string{"/get"};
  7108. #else
  7109. auto host = "nghttp2.org";
  7110. auto path = std::string{"/httpbin/get"};
  7111. #endif
  7112. SSLClient cli(host, 443);
  7113. auto res = cli.Get(path);
  7114. ASSERT_TRUE(res);
  7115. ASSERT_EQ(StatusCode::OK_200, res->status);
  7116. }
  7117. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7118. // Use a site that will cause SSL verification failure due to self-signed cert
  7119. SSLClient cli("self-signed.badssl.com", 443);
  7120. cli.enable_server_certificate_verification(true);
  7121. auto res = cli.Get("/");
  7122. ASSERT_TRUE(!res);
  7123. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7124. // For SSL server verification errors, ssl_error should be 0, only
  7125. // ssl_openssl_error should be set
  7126. EXPECT_EQ(0, res.ssl_error());
  7127. // Verify OpenSSL error is captured for SSLServerVerification
  7128. // This occurs when SSL_get_verify_result() returns a verification failure
  7129. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7130. res.ssl_openssl_error());
  7131. }
  7132. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7133. // Use a site where hostname doesn't match the certificate
  7134. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7135. SSLClient cli("wrong.host.badssl.com", 443);
  7136. cli.enable_server_certificate_verification(true);
  7137. cli.enable_server_hostname_verification(true);
  7138. auto res = cli.Get("/");
  7139. ASSERT_TRUE(!res);
  7140. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7141. // For SSL hostname verification errors, ssl_error should be 0, only
  7142. // ssl_openssl_error should be set
  7143. EXPECT_EQ(0, res.ssl_error());
  7144. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7145. // This occurs when verify_host() fails due to hostname mismatch
  7146. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7147. res.ssl_openssl_error());
  7148. }
  7149. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7150. Client cli("https://google.com");
  7151. auto res = cli.Get("/");
  7152. ASSERT_TRUE(res);
  7153. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7154. }
  7155. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7156. SSLClient cli("google.com");
  7157. cli.set_ca_cert_path(CA_CERT_FILE);
  7158. auto res = cli.Get("/");
  7159. ASSERT_TRUE(res);
  7160. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7161. }
  7162. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7163. SSLClient cli("google.com");
  7164. cli.enable_server_certificate_verification(true);
  7165. cli.set_ca_cert_path("hello");
  7166. auto res = cli.Get("/");
  7167. ASSERT_TRUE(!res);
  7168. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7169. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7170. // should be set
  7171. EXPECT_EQ(0, res.ssl_error());
  7172. // Verify OpenSSL error is captured for SSLLoadingCerts
  7173. // This error occurs when SSL_CTX_load_verify_locations() fails
  7174. // > openssl errstr 0x80000002
  7175. // error:80000002:system library::No such file or directory
  7176. // > openssl errstr 0xA000126
  7177. // error:0A000126:SSL routines::unexpected eof while reading
  7178. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7179. res.ssl_openssl_error() == 0xA000126);
  7180. }
  7181. TEST(SSLClientTest, ServerCertificateVerification4) {
  7182. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7183. ASSERT_TRUE(svr.is_valid());
  7184. svr.Get("/test", [&](const Request &, Response &res) {
  7185. res.set_content("test", "text/plain");
  7186. svr.stop();
  7187. ASSERT_TRUE(true);
  7188. });
  7189. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7190. auto se = detail::scope_exit([&] {
  7191. t.join();
  7192. ASSERT_FALSE(svr.is_running());
  7193. });
  7194. svr.wait_until_ready();
  7195. SSLClient cli("127.0.0.1", PORT);
  7196. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7197. cli.enable_server_certificate_verification(true);
  7198. cli.set_connection_timeout(30);
  7199. auto res = cli.Get("/test");
  7200. ASSERT_TRUE(res);
  7201. ASSERT_EQ(StatusCode::OK_200, res->status);
  7202. }
  7203. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7204. std::string cert;
  7205. read_file(CA_CERT_FILE, cert);
  7206. SSLClient cli("google.com");
  7207. cli.load_ca_cert_store(cert.data(), cert.size());
  7208. const auto res = cli.Get("/");
  7209. ASSERT_TRUE(res);
  7210. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7211. }
  7212. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7213. // clang-format off
  7214. static constexpr char cert[] =
  7215. "GlobalSign Root CA\n"
  7216. "==================\n"
  7217. "-----BEGIN CERTIFICATE-----\n"
  7218. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7219. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7220. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7221. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7222. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7223. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7224. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7225. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7226. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7227. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7228. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7229. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7230. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7231. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7232. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7233. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7234. "-----END CERTIFICATE-----\n";
  7235. // clang-format on
  7236. SSLClient cli("google.com");
  7237. cli.load_ca_cert_store(cert, sizeof(cert));
  7238. const auto res = cli.Get("/");
  7239. ASSERT_TRUE(res);
  7240. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7241. }
  7242. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7243. SSLClient cli("www.youtube.com");
  7244. cli.set_ca_cert_path(CA_CERT_FILE);
  7245. cli.enable_server_certificate_verification(true);
  7246. cli.set_follow_location(true);
  7247. auto res = cli.Get("/");
  7248. ASSERT_TRUE(res);
  7249. ASSERT_EQ(StatusCode::OK_200, res->status);
  7250. }
  7251. TEST(SSLClientTest, Issue2004_Online) {
  7252. Client client("https://google.com");
  7253. client.set_follow_location(true);
  7254. auto res = client.Get("/");
  7255. ASSERT_TRUE(res);
  7256. ASSERT_EQ(StatusCode::OK_200, res->status);
  7257. auto body = res->body;
  7258. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7259. }
  7260. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7261. // Create SSLClient with invalid cert/key to make is_valid() return false
  7262. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7263. "nonexistent_key.pem");
  7264. // is_valid() should be false due to cert loading failure
  7265. ASSERT_FALSE(cli.is_valid());
  7266. auto res = cli.Get("/");
  7267. ASSERT_FALSE(res);
  7268. EXPECT_EQ(Error::SSLConnection, res.error());
  7269. }
  7270. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7271. // Test for Issue #2251: SSL error not properly reported when client cert
  7272. // and key paths are swapped or mismatched
  7273. // This simulates the scenario where user accidentally swaps the cert and key
  7274. // files
  7275. // Using client cert file as private key and vice versa (completely wrong)
  7276. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7277. // Should fail validation due to cert/key mismatch
  7278. ASSERT_FALSE(cli.is_valid());
  7279. // Attempt to make a request should fail with proper error
  7280. auto res = cli.Get("/");
  7281. ASSERT_FALSE(res);
  7282. EXPECT_EQ(Error::SSLConnection, res.error());
  7283. // SSL error should be recorded in the Result object (this is the key fix for
  7284. // Issue #2251)
  7285. auto openssl_error = res.ssl_openssl_error();
  7286. EXPECT_NE(0u, openssl_error);
  7287. }
  7288. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7289. // Another variant: using valid file paths but with mismatched cert/key pair
  7290. // This tests the case where files exist but contain incompatible key material
  7291. // Using client cert with wrong key (cert2 key)
  7292. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7293. // Should fail validation
  7294. ASSERT_FALSE(cli.is_valid());
  7295. auto res = cli.Get("/");
  7296. ASSERT_FALSE(res);
  7297. // Must report error properly, not appear as success
  7298. EXPECT_EQ(Error::SSLConnection, res.error());
  7299. // OpenSSL error should be captured in Result
  7300. EXPECT_NE(0u, res.ssl_openssl_error());
  7301. }
  7302. #if 0
  7303. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7304. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7305. ASSERT_TRUE(cli != nullptr);
  7306. cli->set_address_family(AF_INET6);
  7307. cli->set_interface("en0");
  7308. auto res = cli->Get("/get");
  7309. ASSERT_TRUE(res);
  7310. ASSERT_EQ(StatusCode::OK_200, res->status);
  7311. }
  7312. #endif
  7313. void ClientCertPresent(
  7314. const std::string &client_cert_file,
  7315. const std::string &client_private_key_file,
  7316. const std::string &client_encrypted_private_key_pass = std::string()) {
  7317. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7318. CLIENT_CA_CERT_DIR);
  7319. ASSERT_TRUE(svr.is_valid());
  7320. svr.Get("/test", [&](const Request &req, Response &res) {
  7321. res.set_content("test", "text/plain");
  7322. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7323. ASSERT_TRUE(peer_cert != nullptr);
  7324. auto subject_name = X509_get_subject_name(peer_cert);
  7325. ASSERT_TRUE(subject_name != nullptr);
  7326. std::string common_name;
  7327. {
  7328. char name[BUFSIZ];
  7329. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7330. name, sizeof(name));
  7331. common_name.assign(name, static_cast<size_t>(name_len));
  7332. }
  7333. EXPECT_EQ("Common Name", common_name);
  7334. X509_free(peer_cert);
  7335. });
  7336. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7337. auto se = detail::scope_exit([&] {
  7338. svr.stop();
  7339. t.join();
  7340. ASSERT_FALSE(svr.is_running());
  7341. });
  7342. svr.wait_until_ready();
  7343. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7344. client_encrypted_private_key_pass);
  7345. cli.enable_server_certificate_verification(false);
  7346. cli.set_connection_timeout(30);
  7347. auto res = cli.Get("/test");
  7348. ASSERT_TRUE(res);
  7349. ASSERT_EQ(StatusCode::OK_200, res->status);
  7350. }
  7351. TEST(SSLClientServerTest, ClientCertPresent) {
  7352. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7353. }
  7354. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7355. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7356. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7357. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7358. }
  7359. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7360. void MemoryClientCertPresent(
  7361. const std::string &client_cert_file,
  7362. const std::string &client_private_key_file,
  7363. const std::string &client_encrypted_private_key_pass = std::string()) {
  7364. auto f = fopen(SERVER_CERT_FILE, "r+");
  7365. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7366. fclose(f);
  7367. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7368. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7369. fclose(f);
  7370. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7371. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7372. auto client_ca_cert_store = X509_STORE_new();
  7373. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7374. X509_free(client_cert);
  7375. fclose(f);
  7376. f = fopen(client_cert_file.c_str(), "r+");
  7377. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7378. fclose(f);
  7379. f = fopen(client_private_key_file.c_str(), "r+");
  7380. auto client_private_key = PEM_read_PrivateKey(
  7381. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7382. fclose(f);
  7383. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7384. ASSERT_TRUE(svr.is_valid());
  7385. svr.Get("/test", [&](const Request &req, Response &res) {
  7386. res.set_content("test", "text/plain");
  7387. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7388. ASSERT_TRUE(peer_cert != nullptr);
  7389. auto subject_name = X509_get_subject_name(peer_cert);
  7390. ASSERT_TRUE(subject_name != nullptr);
  7391. std::string common_name;
  7392. {
  7393. char name[BUFSIZ];
  7394. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7395. name, sizeof(name));
  7396. common_name.assign(name, static_cast<size_t>(name_len));
  7397. }
  7398. EXPECT_EQ("Common Name", common_name);
  7399. X509_free(peer_cert);
  7400. });
  7401. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7402. auto se = detail::scope_exit([&] {
  7403. svr.stop();
  7404. t.join();
  7405. ASSERT_FALSE(svr.is_running());
  7406. });
  7407. svr.wait_until_ready();
  7408. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7409. client_encrypted_private_key_pass);
  7410. cli.enable_server_certificate_verification(false);
  7411. cli.set_connection_timeout(30);
  7412. auto res = cli.Get("/test");
  7413. ASSERT_TRUE(res);
  7414. ASSERT_EQ(StatusCode::OK_200, res->status);
  7415. X509_free(server_cert);
  7416. EVP_PKEY_free(server_private_key);
  7417. X509_free(client_cert);
  7418. EVP_PKEY_free(client_private_key);
  7419. }
  7420. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7421. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7422. }
  7423. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7424. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7425. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7426. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7427. }
  7428. #endif
  7429. TEST(SSLClientServerTest, ClientCertMissing) {
  7430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7431. CLIENT_CA_CERT_DIR);
  7432. ASSERT_TRUE(svr.is_valid());
  7433. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7434. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7435. auto se = detail::scope_exit([&] {
  7436. svr.stop();
  7437. t.join();
  7438. ASSERT_FALSE(svr.is_running());
  7439. });
  7440. svr.wait_until_ready();
  7441. SSLClient cli(HOST, PORT);
  7442. cli.set_connection_timeout(30);
  7443. auto res = cli.Get("/test");
  7444. ASSERT_TRUE(!res);
  7445. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7446. // For SSL server verification errors, ssl_error should be 0, only
  7447. // ssl_openssl_error should be set
  7448. EXPECT_EQ(0, res.ssl_error());
  7449. // Verify OpenSSL error is captured for SSLServerVerification
  7450. // Note: This test may have different error codes depending on the exact
  7451. // verification failure
  7452. EXPECT_NE(0UL, res.ssl_openssl_error());
  7453. }
  7454. TEST(SSLClientServerTest, TrustDirOptional) {
  7455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7456. ASSERT_TRUE(svr.is_valid());
  7457. svr.Get("/test", [&](const Request &, Response &res) {
  7458. res.set_content("test", "text/plain");
  7459. });
  7460. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7461. auto se = detail::scope_exit([&] {
  7462. svr.stop();
  7463. t.join();
  7464. ASSERT_FALSE(svr.is_running());
  7465. });
  7466. svr.wait_until_ready();
  7467. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7468. cli.enable_server_certificate_verification(false);
  7469. cli.set_connection_timeout(30);
  7470. auto res = cli.Get("/test");
  7471. ASSERT_TRUE(res);
  7472. ASSERT_EQ(StatusCode::OK_200, res->status);
  7473. }
  7474. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7475. class NoListenSSLServer : public SSLServer {
  7476. public:
  7477. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7478. const char *client_ca_cert_file_path,
  7479. const char *client_ca_cert_dir_path = nullptr)
  7480. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7481. client_ca_cert_dir_path),
  7482. stop_(false) {}
  7483. std::atomic_bool stop_;
  7484. private:
  7485. bool process_and_close_socket(socket_t /*sock*/) override {
  7486. // Don't create SSL context
  7487. while (!stop_.load()) {
  7488. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7489. }
  7490. return true;
  7491. }
  7492. };
  7493. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7494. CLIENT_CA_CERT_FILE);
  7495. ASSERT_TRUE(svr.is_valid());
  7496. svr.Get("/test", [&](const Request &, Response &res) {
  7497. res.set_content("test", "text/plain");
  7498. });
  7499. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7500. auto se = detail::scope_exit([&] {
  7501. svr.stop_ = true;
  7502. svr.stop();
  7503. t.join();
  7504. ASSERT_FALSE(svr.is_running());
  7505. });
  7506. svr.wait_until_ready();
  7507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7508. cli.enable_server_certificate_verification(false);
  7509. cli.set_connection_timeout(1);
  7510. auto res = cli.Get("/test");
  7511. ASSERT_TRUE(!res);
  7512. EXPECT_EQ(Error::SSLConnection, res.error());
  7513. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7514. }
  7515. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7516. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7517. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7518. SSL_CTX_set_options(&ssl_ctx,
  7519. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7520. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7521. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7522. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7523. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7524. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7525. "ECDHE-DSS-AES128-SHA256:"
  7526. "ECDHE-RSA-AES256-SHA256:"
  7527. "ECDHE-DSS-AES256-SHA256:";
  7528. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7529. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7530. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7531. SSL_FILETYPE_PEM) != 1) {
  7532. return false;
  7533. }
  7534. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7535. CLIENT_CA_CERT_DIR);
  7536. SSL_CTX_set_verify(
  7537. &ssl_ctx,
  7538. SSL_VERIFY_PEER |
  7539. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7540. nullptr);
  7541. return true;
  7542. };
  7543. SSLServer svr(setup_ssl_ctx_callback);
  7544. ASSERT_TRUE(svr.is_valid());
  7545. svr.Get("/test", [&](const Request &req, Response &res) {
  7546. res.set_content("test", "text/plain");
  7547. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7548. ASSERT_TRUE(peer_cert != nullptr);
  7549. auto subject_name = X509_get_subject_name(peer_cert);
  7550. ASSERT_TRUE(subject_name != nullptr);
  7551. std::string common_name;
  7552. {
  7553. char name[BUFSIZ];
  7554. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7555. name, sizeof(name));
  7556. common_name.assign(name, static_cast<size_t>(name_len));
  7557. }
  7558. EXPECT_EQ("Common Name", common_name);
  7559. X509_free(peer_cert);
  7560. });
  7561. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7562. auto se = detail::scope_exit([&] {
  7563. svr.stop();
  7564. t.join();
  7565. ASSERT_FALSE(svr.is_running());
  7566. });
  7567. svr.wait_until_ready();
  7568. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7569. cli.enable_server_certificate_verification(false);
  7570. cli.set_connection_timeout(30);
  7571. auto res = cli.Get("/test");
  7572. ASSERT_TRUE(res);
  7573. ASSERT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7577. ASSERT_TRUE(svr.is_valid());
  7578. // Set up a handler to verify client certificate is present
  7579. bool client_cert_verified = false;
  7580. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7581. // Verify that client certificate was provided
  7582. client_cert_verified = true;
  7583. res.set_content("success", "text/plain");
  7584. });
  7585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7586. auto se = detail::scope_exit([&] {
  7587. svr.stop();
  7588. t.join();
  7589. ASSERT_FALSE(svr.is_running());
  7590. });
  7591. svr.wait_until_ready();
  7592. // Client with certificate
  7593. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7594. cli.enable_server_certificate_verification(false);
  7595. cli.set_connection_timeout(30);
  7596. auto res = cli.Get("/test");
  7597. ASSERT_TRUE(res);
  7598. ASSERT_EQ(StatusCode::OK_200, res->status);
  7599. ASSERT_TRUE(client_cert_verified);
  7600. EXPECT_EQ("success", res->body);
  7601. }
  7602. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7603. // Test that when client CA cert file is provided,
  7604. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7605. // Create a server with client authentication
  7606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7607. ASSERT_TRUE(svr.is_valid());
  7608. // We can't directly access the SSL_CTX from SSLServer to verify,
  7609. // but we can test that the server properly requests client certificates
  7610. // and accepts valid ones from the specified CA
  7611. bool handler_called = false;
  7612. svr.Get("/test", [&](const Request &req, Response &res) {
  7613. handler_called = true;
  7614. // Verify that a client certificate was provided
  7615. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7616. ASSERT_TRUE(peer_cert != nullptr);
  7617. // Get the issuer name
  7618. auto issuer_name = X509_get_issuer_name(peer_cert);
  7619. ASSERT_TRUE(issuer_name != nullptr);
  7620. char issuer_buf[256];
  7621. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7622. // The client certificate should be issued by our test CA
  7623. std::string issuer_str(issuer_buf);
  7624. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7625. X509_free(peer_cert);
  7626. res.set_content("authenticated", "text/plain");
  7627. });
  7628. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7629. auto se = detail::scope_exit([&] {
  7630. svr.stop();
  7631. t.join();
  7632. ASSERT_FALSE(svr.is_running());
  7633. });
  7634. svr.wait_until_ready();
  7635. // Connect with a client certificate issued by the CA
  7636. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7637. cli.enable_server_certificate_verification(false);
  7638. cli.set_connection_timeout(30);
  7639. auto res = cli.Get("/test");
  7640. ASSERT_TRUE(res);
  7641. ASSERT_EQ(StatusCode::OK_200, res->status);
  7642. ASSERT_TRUE(handler_called);
  7643. EXPECT_EQ("authenticated", res->body);
  7644. }
  7645. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7646. // Test 1: Valid CA file - no error should be recorded
  7647. {
  7648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7649. CLIENT_CA_CERT_FILE);
  7650. ASSERT_TRUE(svr.is_valid());
  7651. // With valid setup, last_ssl_error should be 0
  7652. EXPECT_EQ(0, svr.ssl_last_error());
  7653. }
  7654. // Test 2: Invalid CA file content
  7655. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7656. {
  7657. // Create a temporary file with completely invalid content
  7658. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7659. {
  7660. std::ofstream ofs(temp_invalid_ca);
  7661. ofs << "This is not a certificate file at all\n";
  7662. ofs << "Just plain text content\n";
  7663. }
  7664. // Create server with invalid CA file
  7665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7666. // Clean up temporary file
  7667. std::remove(temp_invalid_ca);
  7668. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7669. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7670. // Note: SSL_CTX_load_verify_locations typically fails first,
  7671. // but our error handling code path is still exercised
  7672. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7673. }
  7674. }
  7675. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7676. // Test SSL server using X509_STORE constructor with client CA certificates
  7677. // This test verifies that Phase 2 implementation correctly extracts CA names
  7678. // from an X509_STORE and sets them in the SSL context
  7679. // Load the CA certificate into memory
  7680. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7681. ASSERT_NE(nullptr, bio);
  7682. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7683. BIO_free(bio);
  7684. ASSERT_NE(nullptr, ca_cert);
  7685. // Create an X509_STORE and add the CA certificate
  7686. auto store = X509_STORE_new();
  7687. ASSERT_NE(nullptr, store);
  7688. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7689. // Load server certificate and private key
  7690. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7691. ASSERT_NE(nullptr, cert_bio);
  7692. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7693. BIO_free(cert_bio);
  7694. ASSERT_NE(nullptr, server_cert);
  7695. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7696. ASSERT_NE(nullptr, key_bio);
  7697. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7698. BIO_free(key_bio);
  7699. ASSERT_NE(nullptr, server_key);
  7700. // Create SSLServer with X509_STORE constructor
  7701. // Note: X509_STORE ownership is transferred to SSL_CTX
  7702. SSLServer svr(server_cert, server_key, store);
  7703. ASSERT_TRUE(svr.is_valid());
  7704. // No SSL error should be recorded for valid setup
  7705. EXPECT_EQ(0, svr.ssl_last_error());
  7706. // Set up server endpoints
  7707. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7708. res.set_content("ok", "text/plain");
  7709. });
  7710. // Start server in a thread
  7711. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7712. svr.wait_until_ready();
  7713. // Connect with client certificate (using constructor with paths)
  7714. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7715. cli.enable_server_certificate_verification(false);
  7716. auto res = cli.Get("/test-x509store");
  7717. ASSERT_TRUE(res);
  7718. EXPECT_EQ(200, res->status);
  7719. EXPECT_EQ("ok", res->body);
  7720. // Clean up
  7721. X509_free(server_cert);
  7722. EVP_PKEY_free(server_key);
  7723. X509_free(ca_cert);
  7724. svr.stop();
  7725. server_thread.join();
  7726. }
  7727. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7728. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7729. // prepare large data
  7730. std::random_device seed_gen;
  7731. std::mt19937 random(seed_gen());
  7732. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7733. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7734. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7735. // server
  7736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7737. ASSERT_TRUE(svr.is_valid());
  7738. svr.Post("/binary", [&](const Request &req, Response &res) {
  7739. EXPECT_EQ(large_size_byte, req.body.size());
  7740. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7741. res.set_content(req.body, "application/octet-stream");
  7742. });
  7743. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7744. auto se = detail::scope_exit([&] {
  7745. svr.stop();
  7746. listen_thread.join();
  7747. ASSERT_FALSE(svr.is_running());
  7748. });
  7749. svr.wait_until_ready();
  7750. // client POST
  7751. SSLClient cli("localhost", PORT);
  7752. cli.enable_server_certificate_verification(false);
  7753. cli.set_read_timeout(std::chrono::seconds(100));
  7754. cli.set_write_timeout(std::chrono::seconds(100));
  7755. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7756. large_size_byte, "application/octet-stream");
  7757. // compare
  7758. EXPECT_EQ(StatusCode::OK_200, res->status);
  7759. EXPECT_EQ(large_size_byte, res->body.size());
  7760. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7761. }
  7762. #endif
  7763. #ifdef _WIN32
  7764. TEST(CleanupTest, WSACleanup) {
  7765. int ret = WSACleanup();
  7766. ASSERT_EQ(0, ret);
  7767. }
  7768. #endif
  7769. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7770. TEST(NoSSLSupport, SimpleInterface) {
  7771. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7772. }
  7773. #endif
  7774. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7775. TEST(InvalidScheme, SimpleInterface) {
  7776. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7777. }
  7778. #endif
  7779. TEST(NoScheme, SimpleInterface) {
  7780. Client cli("yahoo.com:80");
  7781. ASSERT_TRUE(cli.is_valid());
  7782. }
  7783. TEST(SendAPI, SimpleInterface_Online) {
  7784. Client cli("http://yahoo.com");
  7785. Request req;
  7786. req.method = "GET";
  7787. req.path = "/";
  7788. auto res = cli.send(req);
  7789. ASSERT_TRUE(res);
  7790. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7791. }
  7792. TEST(SendAPI, WithParamsInRequest) {
  7793. Server svr;
  7794. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7795. EXPECT_TRUE(req.has_param("test"));
  7796. EXPECT_EQ("test_value", req.get_param_value("test"));
  7797. });
  7798. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7799. auto se = detail::scope_exit([&] {
  7800. svr.stop();
  7801. t.join();
  7802. ASSERT_FALSE(svr.is_running());
  7803. });
  7804. svr.wait_until_ready();
  7805. Client cli(HOST, PORT);
  7806. {
  7807. Request req;
  7808. req.method = "GET";
  7809. req.path = "/";
  7810. req.params.emplace("test", "test_value");
  7811. auto res = cli.send(req);
  7812. ASSERT_TRUE(res);
  7813. }
  7814. {
  7815. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7816. ASSERT_TRUE(res);
  7817. }
  7818. }
  7819. TEST(ClientImplMethods, GetSocketTest) {
  7820. httplib::Server svr;
  7821. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7822. res.status = StatusCode::OK_200;
  7823. });
  7824. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7825. auto se = detail::scope_exit([&] {
  7826. svr.stop();
  7827. thread.join();
  7828. ASSERT_FALSE(svr.is_running());
  7829. });
  7830. svr.wait_until_ready();
  7831. {
  7832. httplib::Client cli("http://127.0.0.1:3333");
  7833. cli.set_keep_alive(true);
  7834. // Use the behavior of cpp-httplib of opening the connection
  7835. // only when the first request happens. If that changes,
  7836. // this test would be obsolete.
  7837. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7838. // This also implicitly tests the server. But other tests would fail much
  7839. // earlier than this one to be considered.
  7840. auto res = cli.Get("/");
  7841. ASSERT_TRUE(res);
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7844. }
  7845. }
  7846. // Disabled due to out-of-memory problem on GitHub Actions
  7847. #ifdef _WIN64
  7848. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7849. // allocate content size larger than 2GB in memory
  7850. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7851. char *content = (char *)malloc(content_size);
  7852. ASSERT_TRUE(content);
  7853. Server svr;
  7854. svr.Get("/foo",
  7855. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7856. res.set_content(content, content_size, "application/octet-stream");
  7857. });
  7858. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7859. auto se = detail::scope_exit([&] {
  7860. svr.stop();
  7861. listen_thread.join();
  7862. if (content) free(content);
  7863. ASSERT_FALSE(svr.is_running());
  7864. });
  7865. svr.wait_until_ready();
  7866. Client cli(HOST, PORT);
  7867. auto res = cli.Get("/foo");
  7868. ASSERT_TRUE(res);
  7869. EXPECT_EQ(StatusCode::OK_200, res->status);
  7870. EXPECT_EQ(content_size, res->body.length());
  7871. }
  7872. #endif
  7873. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7874. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7875. Client cli("http://yahoo.com");
  7876. auto res = cli.Get("/");
  7877. ASSERT_TRUE(res);
  7878. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7879. cli.set_follow_location(true);
  7880. res = cli.Get("/");
  7881. ASSERT_TRUE(res);
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7884. }
  7885. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7886. Client cli("https://yahoo.com");
  7887. auto res = cli.Get("/");
  7888. ASSERT_TRUE(res);
  7889. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7890. cli.set_follow_location(true);
  7891. res = cli.Get("/");
  7892. ASSERT_TRUE(res);
  7893. EXPECT_EQ(StatusCode::OK_200, res->status);
  7894. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7895. }
  7896. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7897. Client cli("https://yahoo.com");
  7898. auto res = cli.Get("/");
  7899. ASSERT_TRUE(res);
  7900. ASSERT_FALSE(!res);
  7901. ASSERT_TRUE(res);
  7902. ASSERT_FALSE(res == nullptr);
  7903. ASSERT_TRUE(res != nullptr);
  7904. EXPECT_EQ(Error::Success, res.error());
  7905. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7906. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7907. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7908. cli.set_follow_location(true);
  7909. res = cli.Get("/");
  7910. ASSERT_TRUE(res);
  7911. EXPECT_EQ(Error::Success, res.error());
  7912. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7913. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7916. }
  7917. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7918. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7919. Client cli("https://cdnjs.cloudflare.com");
  7920. auto res =
  7921. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7922. ASSERT_TRUE(res);
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_EQ(287630U, res->body.size());
  7925. EXPECT_EQ("application/javascript; charset=utf-8",
  7926. res->get_header_value("Content-Type"));
  7927. }
  7928. #endif
  7929. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7930. #undef REDIR_HOST // Silence compiler warning
  7931. #define REDIR_HOST "https://httpbingo.org"
  7932. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7933. Client cli(REDIR_HOST);
  7934. cli.set_follow_location(true);
  7935. auto res =
  7936. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7937. ASSERT_TRUE(res);
  7938. EXPECT_EQ(StatusCode::OK_200, res->status);
  7939. }
  7940. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7941. Client cli(REDIR_HOST);
  7942. cli.set_follow_location(true);
  7943. Params params;
  7944. params.emplace("url", "http://example.com");
  7945. params.emplace("status_code", "302");
  7946. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7947. ASSERT_TRUE(res);
  7948. EXPECT_EQ(StatusCode::OK_200, res->status);
  7949. }
  7950. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7951. Client cli(REDIR_HOST);
  7952. cli.set_follow_location(true);
  7953. Params params;
  7954. params.emplace("url", "http://example.com");
  7955. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7956. ASSERT_TRUE(res);
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. TEST(HttpToHttpsRedirectTest, CertFile) {
  7960. Server svr;
  7961. ASSERT_TRUE(svr.is_valid());
  7962. svr.Get("/index", [&](const Request &, Response &res) {
  7963. res.set_redirect("https://127.0.0.1:1235/index");
  7964. svr.stop();
  7965. });
  7966. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7967. ASSERT_TRUE(ssl_svr.is_valid());
  7968. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7969. res.set_content("test", "text/plain");
  7970. ssl_svr.stop();
  7971. });
  7972. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7973. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7974. auto se = detail::scope_exit([&] {
  7975. t2.join();
  7976. t.join();
  7977. ASSERT_FALSE(svr.is_running());
  7978. });
  7979. svr.wait_until_ready();
  7980. ssl_svr.wait_until_ready();
  7981. Client cli("127.0.0.1", PORT);
  7982. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7983. cli.enable_server_certificate_verification(true);
  7984. cli.set_follow_location(true);
  7985. cli.set_connection_timeout(30);
  7986. auto res = cli.Get("/index");
  7987. ASSERT_TRUE(res);
  7988. ASSERT_EQ(StatusCode::OK_200, res->status);
  7989. }
  7990. TEST(SSLClientRedirectTest, CertFile) {
  7991. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7992. ASSERT_TRUE(ssl_svr1.is_valid());
  7993. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  7994. res.set_redirect("https://127.0.0.1:1235/index");
  7995. ssl_svr1.stop();
  7996. });
  7997. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7998. ASSERT_TRUE(ssl_svr2.is_valid());
  7999. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8000. res.set_content("test", "text/plain");
  8001. ssl_svr2.stop();
  8002. });
  8003. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8004. thread t2 =
  8005. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8006. auto se = detail::scope_exit([&] {
  8007. t2.join();
  8008. t.join();
  8009. ASSERT_FALSE(ssl_svr1.is_running());
  8010. });
  8011. ssl_svr1.wait_until_ready();
  8012. ssl_svr2.wait_until_ready();
  8013. SSLClient cli("127.0.0.1", PORT);
  8014. std::string cert;
  8015. read_file(SERVER_CERT2_FILE, cert);
  8016. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8017. cli.enable_server_certificate_verification(true);
  8018. cli.set_follow_location(true);
  8019. cli.set_connection_timeout(30);
  8020. auto res = cli.Get("/index");
  8021. ASSERT_TRUE(res);
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. }
  8024. TEST(MultipartFormDataTest, LargeData) {
  8025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8026. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8027. const ContentReader &content_reader) {
  8028. if (req.is_multipart_form_data()) {
  8029. std::vector<FormData> items;
  8030. content_reader(
  8031. [&](const FormData &file) {
  8032. items.push_back(file);
  8033. return true;
  8034. },
  8035. [&](const char *data, size_t data_length) {
  8036. items.back().content.append(data, data_length);
  8037. return true;
  8038. });
  8039. EXPECT_TRUE(std::string(items[0].name) == "document");
  8040. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8041. EXPECT_TRUE(items[0].filename == "2MB_data");
  8042. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8043. EXPECT_TRUE(items[1].name == "hello");
  8044. EXPECT_TRUE(items[1].content == "world");
  8045. EXPECT_TRUE(items[1].filename == "");
  8046. EXPECT_TRUE(items[1].content_type == "");
  8047. } else {
  8048. std::string body;
  8049. content_reader([&](const char *data, size_t data_length) {
  8050. body.append(data, data_length);
  8051. return true;
  8052. });
  8053. }
  8054. });
  8055. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8056. auto se = detail::scope_exit([&] {
  8057. svr.stop();
  8058. t.join();
  8059. ASSERT_FALSE(svr.is_running());
  8060. });
  8061. svr.wait_until_ready();
  8062. {
  8063. std::string data(1024 * 1024 * 2, '.');
  8064. std::stringstream buffer;
  8065. buffer << data;
  8066. Client cli("https://localhost:8080");
  8067. cli.enable_server_certificate_verification(false);
  8068. UploadFormDataItems items{
  8069. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8070. {"hello", "world", "", ""},
  8071. };
  8072. auto res = cli.Post("/post", items);
  8073. ASSERT_TRUE(res);
  8074. ASSERT_EQ(StatusCode::OK_200, res->status);
  8075. }
  8076. }
  8077. TEST(MultipartFormDataTest, DataProviderItems) {
  8078. std::random_device seed_gen;
  8079. std::mt19937 random(seed_gen());
  8080. std::string rand1;
  8081. rand1.resize(1000);
  8082. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8083. std::string rand2;
  8084. rand2.resize(3000);
  8085. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8087. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8088. const ContentReader &content_reader) {
  8089. ASSERT_FALSE(req.is_multipart_form_data());
  8090. std::string body;
  8091. content_reader([&](const char *data, size_t data_length) {
  8092. body.append(data, data_length);
  8093. return true;
  8094. });
  8095. EXPECT_EQ(body, "");
  8096. });
  8097. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8098. const ContentReader &content_reader) {
  8099. ASSERT_TRUE(req.is_multipart_form_data());
  8100. std::vector<FormData> items;
  8101. content_reader(
  8102. [&](const FormData &file) {
  8103. items.push_back(file);
  8104. return true;
  8105. },
  8106. [&](const char *data, size_t data_length) {
  8107. items.back().content.append(data, data_length);
  8108. return true;
  8109. });
  8110. ASSERT_TRUE(items.size() == 2);
  8111. EXPECT_EQ(std::string(items[0].name), "name1");
  8112. EXPECT_EQ(items[0].content, "Testing123");
  8113. EXPECT_EQ(items[0].filename, "filename1");
  8114. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8115. EXPECT_EQ(items[1].name, "name2");
  8116. EXPECT_EQ(items[1].content, "Testing456");
  8117. EXPECT_EQ(items[1].filename, "");
  8118. EXPECT_EQ(items[1].content_type, "");
  8119. });
  8120. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8121. const ContentReader &content_reader) {
  8122. ASSERT_TRUE(req.is_multipart_form_data());
  8123. std::vector<FormData> items;
  8124. content_reader(
  8125. [&](const FormData &file) {
  8126. items.push_back(file);
  8127. return true;
  8128. },
  8129. [&](const char *data, size_t data_length) {
  8130. items.back().content.append(data, data_length);
  8131. return true;
  8132. });
  8133. ASSERT_TRUE(items.size() == 2);
  8134. EXPECT_EQ(items[0].name, "name3");
  8135. EXPECT_EQ(items[0].content, rand1);
  8136. EXPECT_EQ(items[0].filename, "filename3");
  8137. EXPECT_EQ(items[0].content_type, "");
  8138. EXPECT_EQ(items[1].name, "name4");
  8139. EXPECT_EQ(items[1].content, rand2);
  8140. EXPECT_EQ(items[1].filename, "filename4");
  8141. EXPECT_EQ(items[1].content_type, "");
  8142. });
  8143. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8144. const ContentReader &content_reader) {
  8145. ASSERT_TRUE(req.is_multipart_form_data());
  8146. std::vector<FormData> items;
  8147. content_reader(
  8148. [&](const FormData &file) {
  8149. items.push_back(file);
  8150. return true;
  8151. },
  8152. [&](const char *data, size_t data_length) {
  8153. items.back().content.append(data, data_length);
  8154. return true;
  8155. });
  8156. ASSERT_TRUE(items.size() == 4);
  8157. EXPECT_EQ(std::string(items[0].name), "name1");
  8158. EXPECT_EQ(items[0].content, "Testing123");
  8159. EXPECT_EQ(items[0].filename, "filename1");
  8160. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8161. EXPECT_EQ(items[1].name, "name2");
  8162. EXPECT_EQ(items[1].content, "Testing456");
  8163. EXPECT_EQ(items[1].filename, "");
  8164. EXPECT_EQ(items[1].content_type, "");
  8165. EXPECT_EQ(items[2].name, "name3");
  8166. EXPECT_EQ(items[2].content, rand1);
  8167. EXPECT_EQ(items[2].filename, "filename3");
  8168. EXPECT_EQ(items[2].content_type, "");
  8169. EXPECT_EQ(items[3].name, "name4");
  8170. EXPECT_EQ(items[3].content, rand2);
  8171. EXPECT_EQ(items[3].filename, "filename4");
  8172. EXPECT_EQ(items[3].content_type, "");
  8173. });
  8174. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8175. auto se = detail::scope_exit([&] {
  8176. svr.stop();
  8177. t.join();
  8178. ASSERT_FALSE(svr.is_running());
  8179. });
  8180. svr.wait_until_ready();
  8181. {
  8182. Client cli("https://localhost:8080");
  8183. cli.enable_server_certificate_verification(false);
  8184. UploadFormDataItems items{
  8185. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8186. {"name2", "Testing456", "", ""}, // not a file
  8187. };
  8188. {
  8189. auto res = cli.Post("/post-none", {}, {}, {});
  8190. ASSERT_TRUE(res);
  8191. ASSERT_EQ(StatusCode::OK_200, res->status);
  8192. }
  8193. FormDataProviderItems providers;
  8194. {
  8195. auto res =
  8196. cli.Post("/post-items", {}, items, providers); // empty providers
  8197. ASSERT_TRUE(res);
  8198. ASSERT_EQ(StatusCode::OK_200, res->status);
  8199. }
  8200. providers.push_back({"name3",
  8201. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8202. // test the offset is given correctly at each step
  8203. if (!offset)
  8204. sink.os.write(rand1.data(), 30);
  8205. else if (offset == 30)
  8206. sink.os.write(rand1.data() + 30, 300);
  8207. else if (offset == 330)
  8208. sink.os.write(rand1.data() + 330, 670);
  8209. else if (offset == rand1.size())
  8210. sink.done();
  8211. return true;
  8212. },
  8213. "filename3",
  8214. {}});
  8215. providers.push_back({"name4",
  8216. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8217. // test the offset is given correctly at each step
  8218. if (!offset)
  8219. sink.os.write(rand2.data(), 2000);
  8220. else if (offset == 2000)
  8221. sink.os.write(rand2.data() + 2000, 1);
  8222. else if (offset == 2001)
  8223. sink.os.write(rand2.data() + 2001, 999);
  8224. else if (offset == rand2.size())
  8225. sink.done();
  8226. return true;
  8227. },
  8228. "filename4",
  8229. {}});
  8230. {
  8231. auto res = cli.Post("/post-providers", {}, {}, providers);
  8232. ASSERT_TRUE(res);
  8233. ASSERT_EQ(StatusCode::OK_200, res->status);
  8234. }
  8235. {
  8236. auto res = cli.Post("/post-both", {}, items, providers);
  8237. ASSERT_TRUE(res);
  8238. ASSERT_EQ(StatusCode::OK_200, res->status);
  8239. }
  8240. }
  8241. }
  8242. TEST(MultipartFormDataTest, BadHeader) {
  8243. Server svr;
  8244. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8245. res.set_content("ok", "text/plain");
  8246. });
  8247. thread t = thread([&] { svr.listen(HOST, PORT); });
  8248. auto se = detail::scope_exit([&] {
  8249. svr.stop();
  8250. t.join();
  8251. ASSERT_FALSE(svr.is_running());
  8252. });
  8253. svr.wait_until_ready();
  8254. const std::string body =
  8255. "This is the preamble. It is to be ignored, though it\r\n"
  8256. "is a handy place for composition agents to include an\r\n"
  8257. "explanatory note to non-MIME conformant readers.\r\n"
  8258. "\r\n"
  8259. "\r\n"
  8260. "--simple boundary\r\n"
  8261. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8262. ": BAD...\r\n"
  8263. "\r\n"
  8264. "value1\r\n"
  8265. "--simple boundary\r\n"
  8266. "Content-Disposition: form-data; name=\"field2\"; "
  8267. "filename=\"example.txt\"\r\n"
  8268. "\r\n"
  8269. "value2\r\n"
  8270. "--simple boundary--\r\n"
  8271. "This is the epilogue. It is also to be ignored.\r\n";
  8272. std::string content_type =
  8273. R"(multipart/form-data; boundary="simple boundary")";
  8274. Client cli(HOST, PORT);
  8275. auto res = cli.Post("/post", body, content_type.c_str());
  8276. ASSERT_TRUE(res);
  8277. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8278. }
  8279. TEST(MultipartFormDataTest, WithPreamble) {
  8280. Server svr;
  8281. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8282. res.set_content("ok", "text/plain");
  8283. });
  8284. thread t = thread([&] { svr.listen(HOST, PORT); });
  8285. auto se = detail::scope_exit([&] {
  8286. svr.stop();
  8287. t.join();
  8288. ASSERT_FALSE(svr.is_running());
  8289. });
  8290. svr.wait_until_ready();
  8291. const std::string body =
  8292. "This is the preamble. It is to be ignored, though it\r\n"
  8293. "is a handy place for composition agents to include an\r\n"
  8294. "explanatory note to non-MIME conformant readers.\r\n"
  8295. "\r\n"
  8296. "\r\n"
  8297. "--simple boundary\r\n"
  8298. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8299. "\r\n"
  8300. "value1\r\n"
  8301. "--simple boundary\r\n"
  8302. "Content-Disposition: form-data; name=\"field2\"; "
  8303. "filename=\"example.txt\"\r\n"
  8304. "\r\n"
  8305. "value2\r\n"
  8306. "--simple boundary--\r\n"
  8307. "This is the epilogue. It is also to be ignored.\r\n";
  8308. std::string content_type =
  8309. R"(multipart/form-data; boundary="simple boundary")";
  8310. Client cli(HOST, PORT);
  8311. auto res = cli.Post("/post", body, content_type.c_str());
  8312. ASSERT_TRUE(res);
  8313. EXPECT_EQ(StatusCode::OK_200, res->status);
  8314. }
  8315. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8317. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8318. const ContentReader &content_reader) {
  8319. if (req.is_multipart_form_data()) {
  8320. std::vector<FormData> items;
  8321. content_reader(
  8322. [&](const FormData &file) {
  8323. items.push_back(file);
  8324. return true;
  8325. },
  8326. [&](const char *data, size_t data_length) {
  8327. items.back().content.append(data, data_length);
  8328. return true;
  8329. });
  8330. EXPECT_TRUE(std::string(items[0].name) == "document");
  8331. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8332. EXPECT_TRUE(items[0].filename == "2MB_data");
  8333. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8334. EXPECT_TRUE(items[1].name == "hello");
  8335. EXPECT_TRUE(items[1].content == "world");
  8336. EXPECT_TRUE(items[1].filename == "");
  8337. EXPECT_TRUE(items[1].content_type == "");
  8338. } else {
  8339. std::string body;
  8340. content_reader([&](const char *data, size_t data_length) {
  8341. body.append(data, data_length);
  8342. return true;
  8343. });
  8344. }
  8345. });
  8346. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8347. auto se = detail::scope_exit([&] {
  8348. svr.stop();
  8349. t.join();
  8350. ASSERT_FALSE(svr.is_running());
  8351. });
  8352. svr.wait_until_ready();
  8353. {
  8354. std::string data(1024 * 1024 * 2, '.');
  8355. std::stringstream buffer;
  8356. buffer << data;
  8357. Client cli("https://localhost:8080");
  8358. cli.enable_server_certificate_verification(false);
  8359. UploadFormDataItems items{
  8360. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8361. {"hello", "world", "", ""},
  8362. };
  8363. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8364. ASSERT_TRUE(res);
  8365. ASSERT_EQ(StatusCode::OK_200, res->status);
  8366. }
  8367. }
  8368. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8369. std::string data(1024 * 1024 * 2, '&');
  8370. std::stringstream buffer;
  8371. buffer << data;
  8372. Client cli("https://localhost:8080");
  8373. UploadFormDataItems items{
  8374. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8375. {"hello", "world", "", ""},
  8376. };
  8377. for (const char &c : " \t\r\n") {
  8378. auto res =
  8379. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8380. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8381. ASSERT_FALSE(res);
  8382. }
  8383. }
  8384. TEST(MultipartFormDataTest, PutFormData) {
  8385. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8386. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8387. const ContentReader &content_reader) {
  8388. if (req.is_multipart_form_data()) {
  8389. std::vector<FormData> items;
  8390. content_reader(
  8391. [&](const FormData &file) {
  8392. items.push_back(file);
  8393. return true;
  8394. },
  8395. [&](const char *data, size_t data_length) {
  8396. items.back().content.append(data, data_length);
  8397. return true;
  8398. });
  8399. EXPECT_TRUE(std::string(items[0].name) == "document");
  8400. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8401. EXPECT_TRUE(items[0].filename == "2MB_data");
  8402. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8403. EXPECT_TRUE(items[1].name == "hello");
  8404. EXPECT_TRUE(items[1].content == "world");
  8405. EXPECT_TRUE(items[1].filename == "");
  8406. EXPECT_TRUE(items[1].content_type == "");
  8407. } else {
  8408. std::string body;
  8409. content_reader([&](const char *data, size_t data_length) {
  8410. body.append(data, data_length);
  8411. return true;
  8412. });
  8413. }
  8414. });
  8415. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8416. auto se = detail::scope_exit([&] {
  8417. svr.stop();
  8418. t.join();
  8419. ASSERT_FALSE(svr.is_running());
  8420. });
  8421. svr.wait_until_ready();
  8422. {
  8423. std::string data(1024 * 1024 * 2, '&');
  8424. std::stringstream buffer;
  8425. buffer << data;
  8426. Client cli("https://localhost:8080");
  8427. cli.enable_server_certificate_verification(false);
  8428. UploadFormDataItems items{
  8429. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8430. {"hello", "world", "", ""},
  8431. };
  8432. auto res = cli.Put("/put", items);
  8433. ASSERT_TRUE(res);
  8434. ASSERT_EQ(StatusCode::OK_200, res->status);
  8435. }
  8436. }
  8437. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8439. svr.Put("/put_customboundary",
  8440. [&](const Request &req, const Response & /*res*/,
  8441. const ContentReader &content_reader) {
  8442. if (req.is_multipart_form_data()) {
  8443. std::vector<FormData> items;
  8444. content_reader(
  8445. [&](const FormData &file) {
  8446. items.push_back(file);
  8447. return true;
  8448. },
  8449. [&](const char *data, size_t data_length) {
  8450. items.back().content.append(data, data_length);
  8451. return true;
  8452. });
  8453. EXPECT_TRUE(std::string(items[0].name) == "document");
  8454. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8455. EXPECT_TRUE(items[0].filename == "2MB_data");
  8456. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8457. EXPECT_TRUE(items[1].name == "hello");
  8458. EXPECT_TRUE(items[1].content == "world");
  8459. EXPECT_TRUE(items[1].filename == "");
  8460. EXPECT_TRUE(items[1].content_type == "");
  8461. } else {
  8462. std::string body;
  8463. content_reader([&](const char *data, size_t data_length) {
  8464. body.append(data, data_length);
  8465. return true;
  8466. });
  8467. }
  8468. });
  8469. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8470. auto se = detail::scope_exit([&] {
  8471. svr.stop();
  8472. t.join();
  8473. ASSERT_FALSE(svr.is_running());
  8474. });
  8475. svr.wait_until_ready();
  8476. {
  8477. std::string data(1024 * 1024 * 2, '&');
  8478. std::stringstream buffer;
  8479. buffer << data;
  8480. Client cli("https://localhost:8080");
  8481. cli.enable_server_certificate_verification(false);
  8482. UploadFormDataItems items{
  8483. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8484. {"hello", "world", "", ""},
  8485. };
  8486. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8487. ASSERT_TRUE(res);
  8488. ASSERT_EQ(StatusCode::OK_200, res->status);
  8489. }
  8490. }
  8491. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8492. std::string data(1024 * 1024 * 2, '&');
  8493. std::stringstream buffer;
  8494. buffer << data;
  8495. Client cli("https://localhost:8080");
  8496. cli.enable_server_certificate_verification(false);
  8497. UploadFormDataItems items{
  8498. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8499. {"hello", "world", "", ""},
  8500. };
  8501. for (const char &c : " \t\r\n") {
  8502. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8503. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8504. ASSERT_FALSE(res);
  8505. }
  8506. }
  8507. TEST(MultipartFormDataTest, AlternateFilename) {
  8508. auto handled = false;
  8509. Server svr;
  8510. svr.Post("/test", [&](const Request &req, Response &res) {
  8511. ASSERT_EQ(2u, req.form.files.size());
  8512. ASSERT_EQ(1u, req.form.fields.size());
  8513. // Test files
  8514. const auto &file1 = req.form.get_file("file1");
  8515. ASSERT_EQ("file1", file1.name);
  8516. ASSERT_EQ("A.txt", file1.filename);
  8517. ASSERT_EQ("text/plain", file1.content_type);
  8518. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8519. const auto &file2 = req.form.get_file("file2");
  8520. ASSERT_EQ("file2", file2.name);
  8521. ASSERT_EQ("a.html", file2.filename);
  8522. ASSERT_EQ("text/html", file2.content_type);
  8523. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8524. file2.content);
  8525. // Test text field
  8526. const auto &text = req.form.get_field("text");
  8527. ASSERT_EQ("text default", text);
  8528. res.set_content("ok", "text/plain");
  8529. handled = true;
  8530. });
  8531. thread t = thread([&] { svr.listen(HOST, PORT); });
  8532. auto se = detail::scope_exit([&] {
  8533. svr.stop();
  8534. t.join();
  8535. ASSERT_FALSE(svr.is_running());
  8536. ASSERT_TRUE(handled);
  8537. });
  8538. svr.wait_until_ready();
  8539. auto req = "POST /test HTTP/1.1\r\n"
  8540. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8541. "Content-Length: 399\r\n"
  8542. "\r\n"
  8543. "----------\r\n"
  8544. "Content-Disposition: form-data; name=\"text\"\r\n"
  8545. "\r\n"
  8546. "text default\r\n"
  8547. "----------\r\n"
  8548. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8549. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8550. "Content-Type: text/plain\r\n"
  8551. "\r\n"
  8552. "Content of a.txt.\r\n"
  8553. "\r\n"
  8554. "----------\r\n"
  8555. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8556. "\"a.html\"\r\n"
  8557. "Content-Type: text/html\r\n"
  8558. "\r\n"
  8559. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8560. "\r\n"
  8561. "------------\r\n";
  8562. ASSERT_TRUE(send_request(1, req));
  8563. }
  8564. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8565. auto handled = false;
  8566. Server svr;
  8567. svr.Post("/test", [&](const Request &req, Response &) {
  8568. ASSERT_EQ(2u, req.form.fields.size());
  8569. const auto &text1 = req.form.get_field("text1");
  8570. ASSERT_EQ("text1", text1);
  8571. const auto &text2 = req.form.get_field("text2");
  8572. ASSERT_EQ("text2", text2);
  8573. handled = true;
  8574. });
  8575. thread t = thread([&] { svr.listen(HOST, PORT); });
  8576. auto se = detail::scope_exit([&] {
  8577. svr.stop();
  8578. t.join();
  8579. ASSERT_FALSE(svr.is_running());
  8580. ASSERT_TRUE(handled);
  8581. });
  8582. svr.wait_until_ready();
  8583. auto req = "POST /test HTTP/1.1\r\n"
  8584. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8585. "Content-Length: 146\r\n"
  8586. "\r\n----------\r\n"
  8587. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8588. "\r\n"
  8589. "text1"
  8590. "\r\n----------\r\n"
  8591. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8592. "\r\n"
  8593. "text2"
  8594. "\r\n------------";
  8595. std::string response;
  8596. ASSERT_TRUE(send_request(1, req, &response));
  8597. ASSERT_EQ("200", response.substr(9, 3));
  8598. }
  8599. TEST(MultipartFormDataTest, ContentLength) {
  8600. auto handled = false;
  8601. Server svr;
  8602. svr.Post("/test", [&](const Request &req, Response &) {
  8603. ASSERT_EQ(2u, req.form.fields.size());
  8604. const auto &text1 = req.form.get_field("text1");
  8605. ASSERT_EQ("text1", text1);
  8606. const auto &text2 = req.form.get_field("text2");
  8607. ASSERT_EQ("text2", text2);
  8608. handled = true;
  8609. });
  8610. thread t = thread([&] { svr.listen(HOST, PORT); });
  8611. auto se = detail::scope_exit([&] {
  8612. svr.stop();
  8613. t.join();
  8614. ASSERT_FALSE(svr.is_running());
  8615. ASSERT_TRUE(handled);
  8616. });
  8617. svr.wait_until_ready();
  8618. auto req = "POST /test HTTP/1.1\r\n"
  8619. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8620. "Content-Length: 167\r\n"
  8621. "\r\n----------\r\n"
  8622. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8623. "Content-Length: 5\r\n"
  8624. "\r\n"
  8625. "text1"
  8626. "\r\n----------\r\n"
  8627. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8628. "\r\n"
  8629. "text2"
  8630. "\r\n------------\r\n";
  8631. std::string response;
  8632. ASSERT_TRUE(send_request(1, req, &response));
  8633. ASSERT_EQ("200", response.substr(9, 3));
  8634. }
  8635. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8636. auto handled = false;
  8637. Server svr;
  8638. svr.Post("/test", [&](const Request &req, Response &) {
  8639. ASSERT_EQ(2u, req.form.fields.size());
  8640. const auto &text1 = req.form.get_field("text1");
  8641. ASSERT_EQ("text1", text1);
  8642. // TODO: Add header access for text fields if needed
  8643. const auto &text2 = req.form.get_field("text2");
  8644. ASSERT_EQ("text2", text2);
  8645. // TODO: Header access for text fields needs to be implemented
  8646. // auto &headers = it->second.headers;
  8647. // ASSERT_EQ(3U, headers.size());
  8648. // auto custom_header = headers.find("x-whatever");
  8649. // ASSERT_TRUE(custom_header != headers.end());
  8650. // ASSERT_NE("customvalue", custom_header->second);
  8651. // ASSERT_EQ("CustomValue", custom_header->second);
  8652. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8653. handled = true;
  8654. });
  8655. thread t = thread([&] { svr.listen(HOST, PORT); });
  8656. auto se = detail::scope_exit([&] {
  8657. svr.stop();
  8658. t.join();
  8659. ASSERT_FALSE(svr.is_running());
  8660. ASSERT_TRUE(handled);
  8661. });
  8662. svr.wait_until_ready();
  8663. auto req = "POST /test HTTP/1.1\r\n"
  8664. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8665. "Content-Length: 232\r\n"
  8666. "\r\n----------\r\n"
  8667. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8668. "Content-Length: 5\r\n"
  8669. "X-Test: 1\r\n"
  8670. "\r\n"
  8671. "text1"
  8672. "\r\n----------\r\n"
  8673. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8674. "Content-Type: text/plain\r\n"
  8675. "X-Whatever: CustomValue\r\n"
  8676. "\r\n"
  8677. "text2"
  8678. "\r\n------------\r\n"
  8679. "That should be disregarded. Not even read";
  8680. std::string response;
  8681. ASSERT_TRUE(send_request(1, req, &response));
  8682. ASSERT_EQ("200", response.substr(9, 3));
  8683. }
  8684. #endif
  8685. TEST(MultipartFormDataTest, LargeHeader) {
  8686. auto handled = false;
  8687. Server svr;
  8688. svr.Post("/test", [&](const Request &req, Response &) {
  8689. ASSERT_EQ(1u, req.form.fields.size());
  8690. const auto &text = req.form.get_field("name1");
  8691. ASSERT_EQ("text1", text);
  8692. handled = true;
  8693. });
  8694. thread t = thread([&] { svr.listen(HOST, PORT); });
  8695. auto se = detail::scope_exit([&] {
  8696. svr.stop();
  8697. t.join();
  8698. ASSERT_FALSE(svr.is_running());
  8699. ASSERT_TRUE(handled);
  8700. });
  8701. svr.wait_until_ready();
  8702. auto boundary = std::string("cpp-httplib-multipart-data");
  8703. std::string content = "--" + boundary +
  8704. "\r\n"
  8705. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8706. "\r\n"
  8707. "text1\r\n"
  8708. "--" +
  8709. boundary + "--\r\n";
  8710. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8711. "Content-Type: multipart/form-data;boundary=" +
  8712. boundary +
  8713. "\r\n"
  8714. "Content-Length: " +
  8715. std::to_string(content.size()) +
  8716. "\r\n"
  8717. "Dummy-Header: ";
  8718. std::string header_suffix = "\r\n"
  8719. "\r\n";
  8720. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8721. size_t header_dummy_size =
  8722. read_buff_size -
  8723. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8724. auto header_dummy = std::string(header_dummy_size, '@');
  8725. auto req = header_prefix + header_dummy + header_suffix + content;
  8726. std::string response;
  8727. ASSERT_TRUE(send_request(1, req, &response));
  8728. ASSERT_EQ("200", response.substr(9, 3));
  8729. }
  8730. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8731. static constexpr unsigned int number_of_tasks{1000000};
  8732. std::atomic_uint count{0};
  8733. std::unique_ptr<TaskQueue> task_queue{
  8734. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8735. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8736. auto queued = task_queue->enqueue(
  8737. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8738. EXPECT_TRUE(queued);
  8739. }
  8740. EXPECT_NO_THROW(task_queue->shutdown());
  8741. EXPECT_EQ(number_of_tasks, count.load());
  8742. }
  8743. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8744. static constexpr unsigned int number_of_tasks{1000000};
  8745. static constexpr unsigned int qlimit{2};
  8746. unsigned int queued_count{0};
  8747. std::atomic_uint count{0};
  8748. std::unique_ptr<TaskQueue> task_queue{
  8749. new ThreadPool{/*num_threads=*/1, qlimit}};
  8750. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8751. if (task_queue->enqueue(
  8752. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8753. queued_count++;
  8754. }
  8755. }
  8756. EXPECT_NO_THROW(task_queue->shutdown());
  8757. EXPECT_EQ(queued_count, count.load());
  8758. EXPECT_TRUE(queued_count <= number_of_tasks);
  8759. EXPECT_TRUE(queued_count >= qlimit);
  8760. }
  8761. TEST(TaskQueueTest, MaxQueuedRequests) {
  8762. static constexpr unsigned int qlimit{3};
  8763. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8764. std::condition_variable sem_cv;
  8765. std::mutex sem_mtx;
  8766. int credits = 0;
  8767. bool queued;
  8768. /* Fill up the queue with tasks that will block until we give them credits to
  8769. * complete. */
  8770. for (unsigned int n = 0; n <= qlimit;) {
  8771. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8772. std::unique_lock<std::mutex> lock(sem_mtx);
  8773. while (credits <= 0) {
  8774. sem_cv.wait(lock);
  8775. }
  8776. /* Consume the credit and signal the test code if they are all gone. */
  8777. if (--credits == 0) { sem_cv.notify_one(); }
  8778. });
  8779. if (n < qlimit) {
  8780. /* The first qlimit enqueues must succeed. */
  8781. EXPECT_TRUE(queued);
  8782. } else {
  8783. /* The last one will succeed only when the worker thread
  8784. * starts and dequeues the first blocking task. Although
  8785. * not necessary for the correctness of this test, we sleep for
  8786. * a short while to avoid busy waiting. */
  8787. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8788. }
  8789. if (queued) { n++; }
  8790. }
  8791. /* Further enqueues must fail since the queue is full. */
  8792. for (auto i = 0; i < 4; i++) {
  8793. queued = task_queue->enqueue([] {});
  8794. EXPECT_FALSE(queued);
  8795. }
  8796. /* Give the credits to allow the previous tasks to complete. */
  8797. {
  8798. std::unique_lock<std::mutex> lock(sem_mtx);
  8799. credits += qlimit + 1;
  8800. }
  8801. sem_cv.notify_all();
  8802. /* Wait for all the credits to be consumed. */
  8803. {
  8804. std::unique_lock<std::mutex> lock(sem_mtx);
  8805. while (credits > 0) {
  8806. sem_cv.wait(lock);
  8807. }
  8808. }
  8809. /* Check that we are able again to enqueue at least qlimit tasks. */
  8810. for (unsigned int i = 0; i < qlimit; i++) {
  8811. queued = task_queue->enqueue([] {});
  8812. EXPECT_TRUE(queued);
  8813. }
  8814. EXPECT_NO_THROW(task_queue->shutdown());
  8815. }
  8816. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8817. Server svr;
  8818. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8819. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8820. });
  8821. svr.Get("/hello", [](const Request &req, Response &res) {
  8822. res.set_content(req.get_param_value("key"), "text/plain");
  8823. });
  8824. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8825. auto se = detail::scope_exit([&] {
  8826. svr.stop();
  8827. thread.join();
  8828. ASSERT_FALSE(svr.is_running());
  8829. });
  8830. svr.wait_until_ready();
  8831. {
  8832. Client cli(HOST, PORT);
  8833. cli.set_follow_location(true);
  8834. auto res = cli.Get("/");
  8835. ASSERT_TRUE(res);
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("val&key2=val2", res->body);
  8838. }
  8839. }
  8840. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8841. Server svr;
  8842. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8843. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8844. });
  8845. svr.Get("/hello", [](const Request &req, Response &res) {
  8846. res.set_content(req.get_param_value("key"), "text/plain");
  8847. });
  8848. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. thread.join();
  8852. ASSERT_FALSE(svr.is_running());
  8853. });
  8854. svr.wait_until_ready();
  8855. {
  8856. Client cli(HOST, PORT);
  8857. cli.set_follow_location(true);
  8858. auto res = cli.Get("/");
  8859. ASSERT_TRUE(res);
  8860. EXPECT_EQ(StatusCode::OK_200, res->status);
  8861. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8862. }
  8863. }
  8864. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8865. TEST(RedirectTest, Issue2185_Online) {
  8866. SSLClient client("github.com");
  8867. client.set_follow_location(true);
  8868. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8869. "Coollab-Windows.zip");
  8870. ASSERT_TRUE(res);
  8871. EXPECT_EQ(StatusCode::OK_200, res->status);
  8872. EXPECT_EQ(9920427U, res->body.size());
  8873. }
  8874. #endif
  8875. TEST(VulnerabilityTest, CRLFInjection) {
  8876. Server svr;
  8877. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8878. res.set_content("Hello 1", "text/plain");
  8879. });
  8880. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8881. res.set_content("Hello 2", "text/plain");
  8882. });
  8883. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8884. res.set_content("Hello 3", "text/plain");
  8885. });
  8886. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8887. res.set_content("Hello 4", "text/plain");
  8888. });
  8889. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8890. for (const auto &x : req.headers) {
  8891. auto key = x.first;
  8892. EXPECT_STRNE("evil", key.c_str());
  8893. }
  8894. });
  8895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8896. auto se = detail::scope_exit([&] {
  8897. svr.stop();
  8898. thread.join();
  8899. ASSERT_FALSE(svr.is_running());
  8900. });
  8901. svr.wait_until_ready();
  8902. {
  8903. Client cli(HOST, PORT);
  8904. cli.Post("/test1", "A=B",
  8905. "application/x-www-form-urlencoded\r\nevil: hello1");
  8906. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8907. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8908. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8909. }
  8910. }
  8911. TEST(PathParamsTest, StaticMatch) {
  8912. const auto pattern = "/users/all";
  8913. detail::PathParamsMatcher matcher(pattern);
  8914. Request request;
  8915. request.path = "/users/all";
  8916. ASSERT_TRUE(matcher.match(request));
  8917. std::unordered_map<std::string, std::string> expected_params = {};
  8918. EXPECT_EQ(request.path_params, expected_params);
  8919. }
  8920. TEST(PathParamsTest, StaticMismatch) {
  8921. const auto pattern = "/users/all";
  8922. detail::PathParamsMatcher matcher(pattern);
  8923. Request request;
  8924. request.path = "/users/1";
  8925. ASSERT_FALSE(matcher.match(request));
  8926. }
  8927. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8928. const auto pattern = "/users/:id/subscriptions";
  8929. detail::PathParamsMatcher matcher(pattern);
  8930. Request request;
  8931. request.path = "/users/42/subscriptions";
  8932. ASSERT_TRUE(matcher.match(request));
  8933. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8934. EXPECT_EQ(request.path_params, expected_params);
  8935. }
  8936. TEST(PathParamsTest, SingleParamInTheEnd) {
  8937. const auto pattern = "/users/:id";
  8938. detail::PathParamsMatcher matcher(pattern);
  8939. Request request;
  8940. request.path = "/users/24";
  8941. ASSERT_TRUE(matcher.match(request));
  8942. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  8943. EXPECT_EQ(request.path_params, expected_params);
  8944. }
  8945. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  8946. const auto pattern = "/users/:id/";
  8947. detail::PathParamsMatcher matcher(pattern);
  8948. Request request;
  8949. request.path = "/users/42/";
  8950. ASSERT_TRUE(matcher.match(request));
  8951. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  8952. EXPECT_EQ(request.path_params, expected_params);
  8953. }
  8954. TEST(PathParamsTest, EmptyParam) {
  8955. const auto pattern = "/users/:id/";
  8956. detail::PathParamsMatcher matcher(pattern);
  8957. Request request;
  8958. request.path = "/users//";
  8959. ASSERT_TRUE(matcher.match(request));
  8960. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  8961. EXPECT_EQ(request.path_params, expected_params);
  8962. }
  8963. TEST(PathParamsTest, FragmentMismatch) {
  8964. const auto pattern = "/users/:id/";
  8965. detail::PathParamsMatcher matcher(pattern);
  8966. Request request;
  8967. request.path = "/admins/24/";
  8968. ASSERT_FALSE(matcher.match(request));
  8969. }
  8970. TEST(PathParamsTest, ExtraFragments) {
  8971. const auto pattern = "/users/:id";
  8972. detail::PathParamsMatcher matcher(pattern);
  8973. Request request;
  8974. request.path = "/users/42/subscriptions";
  8975. ASSERT_FALSE(matcher.match(request));
  8976. }
  8977. TEST(PathParamsTest, MissingTrailingParam) {
  8978. const auto pattern = "/users/:id";
  8979. detail::PathParamsMatcher matcher(pattern);
  8980. Request request;
  8981. request.path = "/users";
  8982. ASSERT_FALSE(matcher.match(request));
  8983. }
  8984. TEST(PathParamsTest, MissingParamInTheMiddle) {
  8985. const auto pattern = "/users/:id/subscriptions";
  8986. detail::PathParamsMatcher matcher(pattern);
  8987. Request request;
  8988. request.path = "/users/subscriptions";
  8989. ASSERT_FALSE(matcher.match(request));
  8990. }
  8991. TEST(PathParamsTest, MultipleParams) {
  8992. const auto pattern = "/users/:userid/subscriptions/:subid";
  8993. detail::PathParamsMatcher matcher(pattern);
  8994. Request request;
  8995. request.path = "/users/42/subscriptions/2";
  8996. ASSERT_TRUE(matcher.match(request));
  8997. std::unordered_map<std::string, std::string> expected_params = {
  8998. {"userid", "42"}, {"subid", "2"}};
  8999. EXPECT_EQ(request.path_params, expected_params);
  9000. }
  9001. TEST(PathParamsTest, SequenceOfParams) {
  9002. const auto pattern = "/values/:x/:y/:z";
  9003. detail::PathParamsMatcher matcher(pattern);
  9004. Request request;
  9005. request.path = "/values/1/2/3";
  9006. ASSERT_TRUE(matcher.match(request));
  9007. std::unordered_map<std::string, std::string> expected_params = {
  9008. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9009. EXPECT_EQ(request.path_params, expected_params);
  9010. }
  9011. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9012. const auto pattern = "/prefix:suffix";
  9013. detail::PathParamsMatcher matcher(pattern);
  9014. Request request;
  9015. request.path = "/prefix:suffix";
  9016. ASSERT_TRUE(matcher.match(request));
  9017. const std::unordered_map<std::string, std::string> expected_params = {};
  9018. EXPECT_EQ(request.path_params, expected_params);
  9019. }
  9020. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9021. // If ipv6 regex working, regex match codepath is taken.
  9022. // else port will default to 80 in Client impl
  9023. int clientImplMagicPort = 80;
  9024. int port = 4321;
  9025. // above ports must be different to avoid false negative
  9026. EXPECT_NE(clientImplMagicPort, port);
  9027. std::string ipV6TestURL = "http://[ff06::c3]";
  9028. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9029. CLIENT_PRIVATE_KEY_FILE);
  9030. EXPECT_EQ(cli.port(), port);
  9031. }
  9032. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9033. auto file_path = "./www/dir/index.html";
  9034. auto dir_path = "./www/dir";
  9035. detail::FileStat stat_file(file_path);
  9036. EXPECT_TRUE(stat_file.is_file());
  9037. EXPECT_FALSE(stat_file.is_dir());
  9038. detail::FileStat stat_dir(dir_path);
  9039. EXPECT_FALSE(stat_dir.is_file());
  9040. EXPECT_TRUE(stat_dir.is_dir());
  9041. }
  9042. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9043. // IPv4 with default HTTP port (80)
  9044. EXPECT_EQ("example.com",
  9045. detail::make_host_and_port_string("example.com", 80, false));
  9046. // IPv4 with default HTTPS port (443)
  9047. EXPECT_EQ("example.com",
  9048. detail::make_host_and_port_string("example.com", 443, true));
  9049. // IPv4 with non-default HTTP port
  9050. EXPECT_EQ("example.com:8080",
  9051. detail::make_host_and_port_string("example.com", 8080, false));
  9052. // IPv4 with non-default HTTPS port
  9053. EXPECT_EQ("example.com:8443",
  9054. detail::make_host_and_port_string("example.com", 8443, true));
  9055. // IPv6 with default HTTP port (80)
  9056. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9057. // IPv6 with default HTTPS port (443)
  9058. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9059. // IPv6 with non-default HTTP port
  9060. EXPECT_EQ("[::1]:8080",
  9061. detail::make_host_and_port_string("::1", 8080, false));
  9062. // IPv6 with non-default HTTPS port
  9063. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9064. // IPv6 full address with default port
  9065. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9066. detail::make_host_and_port_string(
  9067. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9068. // IPv6 full address with non-default port
  9069. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9070. detail::make_host_and_port_string(
  9071. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9072. // IPv6 localhost with non-default port
  9073. EXPECT_EQ("[::1]:3000",
  9074. detail::make_host_and_port_string("::1", 3000, false));
  9075. // IPv6 with zone ID (link-local address) with default port
  9076. EXPECT_EQ("[fe80::1%eth0]",
  9077. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9078. // IPv6 with zone ID (link-local address) with non-default port
  9079. EXPECT_EQ("[fe80::1%eth0]:8080",
  9080. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9081. // Edge case: Port 443 with is_ssl=false (should add port)
  9082. EXPECT_EQ("example.com:443",
  9083. detail::make_host_and_port_string("example.com", 443, false));
  9084. // Edge case: Port 80 with is_ssl=true (should add port)
  9085. EXPECT_EQ("example.com:80",
  9086. detail::make_host_and_port_string("example.com", 80, true));
  9087. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9088. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9089. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9090. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9091. // Security fix: Already bracketed IPv6 should not get double brackets
  9092. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9093. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9094. EXPECT_EQ("[::1]:8080",
  9095. detail::make_host_and_port_string("[::1]", 8080, false));
  9096. EXPECT_EQ("[2001:db8::1]:8080",
  9097. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9098. EXPECT_EQ("[fe80::1%eth0]",
  9099. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9100. EXPECT_EQ("[fe80::1%eth0]:8080",
  9101. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9102. // Edge case: Empty host (should return as-is)
  9103. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9104. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9105. // This is a known limitation but shouldn't crash
  9106. EXPECT_EQ("[host:name]",
  9107. detail::make_host_and_port_string("host:name", 80, false));
  9108. // Port number edge cases (no validation, but should not crash)
  9109. EXPECT_EQ("example.com:0",
  9110. detail::make_host_and_port_string("example.com", 0, false));
  9111. EXPECT_EQ("example.com:-1",
  9112. detail::make_host_and_port_string("example.com", -1, false));
  9113. EXPECT_EQ("example.com:65535",
  9114. detail::make_host_and_port_string("example.com", 65535, false));
  9115. EXPECT_EQ("example.com:65536",
  9116. detail::make_host_and_port_string("example.com", 65536, false));
  9117. }
  9118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9119. TEST(SSLClientHostHeaderTest, Issue2301) {
  9120. httplib::SSLClient cli("roblox.com", 443);
  9121. cli.set_follow_location(true);
  9122. auto res = cli.Get("/");
  9123. ASSERT_TRUE(res);
  9124. EXPECT_EQ(StatusCode::OK_200, res->status);
  9125. }
  9126. #endif
  9127. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9128. Server svr;
  9129. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9130. EXPECT_EQ(res.status, 400);
  9131. });
  9132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9133. auto se = detail::scope_exit([&] {
  9134. svr.stop();
  9135. thread.join();
  9136. ASSERT_FALSE(svr.is_running());
  9137. });
  9138. svr.wait_until_ready();
  9139. Client cli(HOST, PORT);
  9140. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9141. }
  9142. TEST(InvalidHeaderCharsTest, is_field_name) {
  9143. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9144. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9145. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9146. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9147. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9148. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9149. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9150. EXPECT_FALSE(detail::fields::is_field_name(""));
  9151. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9152. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9153. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9154. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9155. }
  9156. TEST(InvalidHeaderCharsTest, is_field_value) {
  9157. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9158. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9159. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9160. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9161. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9162. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9163. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9164. EXPECT_TRUE(detail::fields::is_field_value(""));
  9165. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9166. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9167. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9168. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9169. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9170. }
  9171. TEST(InvalidHeaderCharsTest, OnServer) {
  9172. Server svr;
  9173. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9174. std::string header = "Not Set";
  9175. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9176. res.set_header(header, "value");
  9177. res.set_content("Page Content Page Content", "text/plain");
  9178. });
  9179. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9180. std::string header = "Not Set";
  9181. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9182. res.set_header("X-Test", header);
  9183. res.set_content("Page Content Page Content", "text/plain");
  9184. });
  9185. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9186. auto se = detail::scope_exit([&] {
  9187. svr.stop();
  9188. thread.join();
  9189. ASSERT_FALSE(svr.is_running());
  9190. });
  9191. svr.wait_until_ready();
  9192. Client cli(HOST, PORT);
  9193. {
  9194. auto res = cli.Get(
  9195. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9196. ASSERT_TRUE(res);
  9197. EXPECT_EQ("Page Content Page Content", res->body);
  9198. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9199. }
  9200. {
  9201. auto res = cli.Get(
  9202. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9203. ASSERT_TRUE(res);
  9204. EXPECT_EQ("Page Content Page Content", res->body);
  9205. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9206. }
  9207. }
  9208. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9209. auto handled = false;
  9210. Server svr;
  9211. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9212. thread t = thread([&] { svr.listen(HOST, PORT); });
  9213. auto se = detail::scope_exit([&] {
  9214. svr.stop();
  9215. t.join();
  9216. ASSERT_FALSE(svr.is_running());
  9217. ASSERT_FALSE(handled);
  9218. });
  9219. svr.wait_until_ready();
  9220. auto req = "POST /test HTTP/1.1\r\n"
  9221. "Content-Length: x\r\n"
  9222. "\r\n";
  9223. std::string response;
  9224. ASSERT_TRUE(send_request(1, req, &response));
  9225. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9226. response.substr(0, response.find("\r\n")));
  9227. }
  9228. #ifndef _WIN32
  9229. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9230. static constexpr char reject[] = "Unauthorized";
  9231. static constexpr char accept[] = "Upload accepted";
  9232. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9233. Server svr;
  9234. svr.set_expect_100_continue_handler(
  9235. [](const Request & /*req*/, Response &res) {
  9236. res.status = StatusCode::Unauthorized_401;
  9237. res.set_content(reject, "text/plain");
  9238. return res.status;
  9239. });
  9240. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9241. res.set_content(accept, "text/plain");
  9242. });
  9243. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9244. auto se = detail::scope_exit([&] {
  9245. svr.stop();
  9246. thread.join();
  9247. ASSERT_FALSE(svr.is_running());
  9248. });
  9249. svr.wait_until_ready();
  9250. {
  9251. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9252. curl_easy_init(), &curl_easy_cleanup};
  9253. ASSERT_NE(curl, nullptr);
  9254. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9255. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9256. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9257. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9258. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9259. &curl_slist_free_all};
  9260. ASSERT_NE(list, nullptr);
  9261. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9262. struct read_data {
  9263. size_t read_size;
  9264. size_t total_size;
  9265. } data = {0, total_size};
  9266. using read_callback_t =
  9267. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9268. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9269. void *userdata) -> size_t {
  9270. read_data *data = (read_data *)userdata;
  9271. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9272. std::fill_n(ptr, size * nmemb, 'A');
  9273. data->read_size += size * nmemb;
  9274. return size * nmemb;
  9275. };
  9276. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9277. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9278. std::vector<char> buffer;
  9279. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9280. using write_callback_t =
  9281. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9282. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9283. void *userdata) -> size_t {
  9284. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9285. buffer->reserve(buffer->size() + size * nmemb + 1);
  9286. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9287. return size * nmemb;
  9288. };
  9289. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9290. {
  9291. const auto res = curl_easy_perform(curl.get());
  9292. ASSERT_EQ(res, CURLE_OK);
  9293. }
  9294. {
  9295. auto response_code = long{};
  9296. const auto res =
  9297. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9298. ASSERT_EQ(res, CURLE_OK);
  9299. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9300. }
  9301. {
  9302. auto dl = curl_off_t{};
  9303. const auto res =
  9304. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9305. ASSERT_EQ(res, CURLE_OK);
  9306. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9307. }
  9308. {
  9309. buffer.push_back('\0');
  9310. ASSERT_STRCASEEQ(buffer.data(), reject);
  9311. }
  9312. }
  9313. }
  9314. #endif
  9315. template <typename S, typename C>
  9316. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9317. svr.Get("/stream", [&](const Request &, Response &res) {
  9318. auto data = new std::string("01234567890123456789");
  9319. res.set_content_provider(
  9320. data->size(), "text/plain",
  9321. [&, data](size_t offset, size_t length, DataSink &sink) {
  9322. const size_t DATA_CHUNK_SIZE = 4;
  9323. const auto &d = *data;
  9324. std::this_thread::sleep_for(std::chrono::seconds(1));
  9325. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9326. return true;
  9327. },
  9328. [data](bool success) {
  9329. EXPECT_FALSE(success);
  9330. delete data;
  9331. });
  9332. });
  9333. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9334. auto i = new size_t(0);
  9335. res.set_content_provider(
  9336. "text/plain",
  9337. [i](size_t, DataSink &sink) {
  9338. if (*i < 5) {
  9339. std::this_thread::sleep_for(std::chrono::seconds(1));
  9340. sink.write("abcd", 4);
  9341. (*i)++;
  9342. } else {
  9343. sink.done();
  9344. }
  9345. return true;
  9346. },
  9347. [i](bool success) {
  9348. EXPECT_FALSE(success);
  9349. delete i;
  9350. });
  9351. });
  9352. svr.Get("/chunked", [&](const Request &, Response &res) {
  9353. auto i = new size_t(0);
  9354. res.set_chunked_content_provider(
  9355. "text/plain",
  9356. [i](size_t, DataSink &sink) {
  9357. if (*i < 5) {
  9358. std::this_thread::sleep_for(std::chrono::seconds(1));
  9359. sink.os << "abcd";
  9360. (*i)++;
  9361. } else {
  9362. sink.done();
  9363. }
  9364. return true;
  9365. },
  9366. [i](bool success) {
  9367. EXPECT_FALSE(success);
  9368. delete i;
  9369. });
  9370. });
  9371. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9372. auto se = detail::scope_exit([&] {
  9373. svr.stop();
  9374. listen_thread.join();
  9375. ASSERT_FALSE(svr.is_running());
  9376. });
  9377. svr.wait_until_ready();
  9378. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9379. {
  9380. auto start = std::chrono::steady_clock::now();
  9381. auto res = cli.Get("/stream");
  9382. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9383. std::chrono::steady_clock::now() - start)
  9384. .count();
  9385. ASSERT_FALSE(res);
  9386. EXPECT_EQ(Error::Read, res.error());
  9387. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9388. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9389. }
  9390. {
  9391. auto start = std::chrono::steady_clock::now();
  9392. auto res = cli.Get("/stream_without_length");
  9393. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9394. std::chrono::steady_clock::now() - start)
  9395. .count();
  9396. ASSERT_FALSE(res);
  9397. EXPECT_EQ(Error::Read, res.error());
  9398. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9399. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9400. }
  9401. {
  9402. auto start = std::chrono::steady_clock::now();
  9403. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9404. EXPECT_EQ("abcd", string(data, data_length));
  9405. return true;
  9406. });
  9407. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9408. std::chrono::steady_clock::now() - start)
  9409. .count();
  9410. ASSERT_FALSE(res);
  9411. EXPECT_EQ(Error::Read, res.error());
  9412. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9413. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9414. }
  9415. }
  9416. TEST(MaxTimeoutTest, ContentStream) {
  9417. time_t timeout = 2000;
  9418. time_t threshold = 200;
  9419. Server svr;
  9420. Client cli("localhost", PORT);
  9421. max_timeout_test(svr, cli, timeout, threshold);
  9422. }
  9423. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9424. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9425. time_t timeout = 2000;
  9426. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9428. SSLClient cli("localhost", PORT);
  9429. cli.enable_server_certificate_verification(false);
  9430. max_timeout_test(svr, cli, timeout, threshold);
  9431. }
  9432. #endif
  9433. class EventDispatcher {
  9434. public:
  9435. EventDispatcher() {}
  9436. bool wait_event(DataSink *sink) {
  9437. unique_lock<mutex> lk(m_);
  9438. int id = id_;
  9439. // Wait with timeout to prevent hanging if client disconnects
  9440. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9441. [&] { return cid_ == id; })) {
  9442. return false; // Timeout occurred
  9443. }
  9444. sink->write(message_.data(), message_.size());
  9445. return true;
  9446. }
  9447. void send_event(const string &message) {
  9448. lock_guard<mutex> lk(m_);
  9449. cid_ = id_++;
  9450. message_ = message;
  9451. cv_.notify_all();
  9452. }
  9453. private:
  9454. mutex m_;
  9455. condition_variable cv_;
  9456. atomic_int id_{0};
  9457. atomic_int cid_{-1};
  9458. string message_;
  9459. };
  9460. TEST(ClientInThreadTest, Issue2068) {
  9461. EventDispatcher ed;
  9462. Server svr;
  9463. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9464. res.set_chunked_content_provider("text/event-stream",
  9465. [&](size_t /*offset*/, DataSink &sink) {
  9466. return ed.wait_event(&sink);
  9467. });
  9468. });
  9469. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9470. svr.wait_until_ready();
  9471. thread event_thread([&] {
  9472. int id = 0;
  9473. while (svr.is_running()) {
  9474. this_thread::sleep_for(chrono::milliseconds(500));
  9475. std::stringstream ss;
  9476. ss << "data: " << id << "\n\n";
  9477. ed.send_event(ss.str());
  9478. id++;
  9479. }
  9480. });
  9481. auto se = detail::scope_exit([&] {
  9482. svr.stop();
  9483. listen_thread.join();
  9484. event_thread.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. });
  9487. {
  9488. auto client = detail::make_unique<Client>(HOST, PORT);
  9489. client->set_read_timeout(std::chrono::minutes(10));
  9490. std::atomic<bool> stop{false};
  9491. std::thread t([&] {
  9492. client->Get("/event1",
  9493. [&](const char *, size_t) -> bool { return !stop; });
  9494. });
  9495. std::this_thread::sleep_for(std::chrono::seconds(2));
  9496. stop = true;
  9497. client->stop();
  9498. t.join();
  9499. // Reset client after thread has finished
  9500. client.reset();
  9501. }
  9502. }
  9503. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9504. Server svr;
  9505. svr.Get("/", [](const Request &req, Response &res) {
  9506. EXPECT_EQ(2U, req.trailers.size());
  9507. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9508. // Denied
  9509. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9510. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9511. // Accepted
  9512. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9513. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9514. EXPECT_TRUE(req.has_trailer("X-World"));
  9515. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9516. res.set_content("ok", "text/plain");
  9517. });
  9518. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9519. auto se = detail::scope_exit([&] {
  9520. svr.stop();
  9521. t.join();
  9522. ASSERT_FALSE(svr.is_running());
  9523. });
  9524. svr.wait_until_ready();
  9525. const std::string req = "GET / HTTP/1.1\r\n"
  9526. "Transfer-Encoding: chunked\r\n"
  9527. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9528. "\r\n"
  9529. "0\r\n"
  9530. "Content-Length: 10\r\n"
  9531. "Host: internal.local\r\n"
  9532. "Content-Type: malicious/content\r\n"
  9533. "Cookie: any\r\n"
  9534. "Set-Cookie: any\r\n"
  9535. "X-Forwarded-For: attacker.com\r\n"
  9536. "X-Real-Ip: 1.1.1.1\r\n"
  9537. "X-Hello: hello\r\n"
  9538. "X-World: world\r\n"
  9539. "\r\n";
  9540. std::string res;
  9541. ASSERT_TRUE(send_request(1, req, &res));
  9542. }
  9543. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9544. Server svr;
  9545. std::string observed_remote_addr;
  9546. std::string observed_xff;
  9547. svr.Get("/ip", [&](const Request &req, Response &res) {
  9548. observed_remote_addr = req.remote_addr;
  9549. observed_xff = req.get_header_value("X-Forwarded-For");
  9550. res.set_content("ok", "text/plain");
  9551. });
  9552. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. t.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. Client cli(HOST, PORT);
  9560. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9561. ASSERT_TRUE(res);
  9562. EXPECT_EQ(StatusCode::OK_200, res->status);
  9563. EXPECT_EQ(observed_xff, "203.0.113.66");
  9564. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9565. observed_remote_addr == "127.0.0.1");
  9566. }
  9567. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9568. Server svr;
  9569. svr.set_trusted_proxies({"203.0.113.66"});
  9570. std::string observed_remote_addr;
  9571. std::string observed_xff;
  9572. svr.Get("/ip", [&](const Request &req, Response &res) {
  9573. observed_remote_addr = req.remote_addr;
  9574. observed_xff = req.get_header_value("X-Forwarded-For");
  9575. res.set_content("ok", "text/plain");
  9576. });
  9577. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9578. auto se = detail::scope_exit([&] {
  9579. svr.stop();
  9580. t.join();
  9581. ASSERT_FALSE(svr.is_running());
  9582. });
  9583. svr.wait_until_ready();
  9584. Client cli(HOST, PORT);
  9585. auto res = cli.Get("/ip");
  9586. ASSERT_TRUE(res);
  9587. EXPECT_EQ(StatusCode::OK_200, res->status);
  9588. EXPECT_EQ(observed_xff, "");
  9589. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9590. observed_remote_addr == "127.0.0.1");
  9591. }
  9592. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9593. Server svr;
  9594. svr.set_trusted_proxies({"203.0.113.66"});
  9595. std::string observed_remote_addr;
  9596. std::string observed_xff;
  9597. svr.Get("/ip", [&](const Request &req, Response &res) {
  9598. observed_remote_addr = req.remote_addr;
  9599. observed_xff = req.get_header_value("X-Forwarded-For");
  9600. res.set_content("ok", "text/plain");
  9601. });
  9602. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. ASSERT_FALSE(svr.is_running());
  9607. });
  9608. svr.wait_until_ready();
  9609. Client cli(HOST, PORT);
  9610. auto res =
  9611. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9612. ASSERT_TRUE(res);
  9613. EXPECT_EQ(StatusCode::OK_200, res->status);
  9614. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9615. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9616. }
  9617. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9618. Server svr;
  9619. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9620. std::string observed_remote_addr;
  9621. std::string observed_xff;
  9622. svr.Get("/ip", [&](const Request &req, Response &res) {
  9623. observed_remote_addr = req.remote_addr;
  9624. observed_xff = req.get_header_value("X-Forwarded-For");
  9625. res.set_content("ok", "text/plain");
  9626. });
  9627. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9628. auto se = detail::scope_exit([&] {
  9629. svr.stop();
  9630. t.join();
  9631. ASSERT_FALSE(svr.is_running());
  9632. });
  9633. svr.wait_until_ready();
  9634. Client cli(HOST, PORT);
  9635. auto res = cli.Get(
  9636. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9637. ASSERT_TRUE(res);
  9638. EXPECT_EQ(StatusCode::OK_200, res->status);
  9639. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9640. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9641. }
  9642. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9643. Server svr;
  9644. svr.set_trusted_proxies({"192.0.2.45"});
  9645. std::string observed_remote_addr;
  9646. std::string observed_xff;
  9647. svr.Get("/ip", [&](const Request &req, Response &res) {
  9648. observed_remote_addr = req.remote_addr;
  9649. observed_xff = req.get_header_value("X-Forwarded-For");
  9650. res.set_content("ok", "text/plain");
  9651. });
  9652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. svr.stop();
  9655. t.join();
  9656. ASSERT_FALSE(svr.is_running());
  9657. });
  9658. svr.wait_until_ready();
  9659. Client cli(HOST, PORT);
  9660. auto res =
  9661. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9662. ASSERT_TRUE(res);
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9665. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9666. }
  9667. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9668. Server svr;
  9669. svr.set_trusted_proxies({"192.0.2.45"});
  9670. std::string observed_remote_addr;
  9671. std::string observed_xff;
  9672. svr.Get("/ip", [&](const Request &req, Response &res) {
  9673. observed_remote_addr = req.remote_addr;
  9674. observed_xff = req.get_header_value("X-Forwarded-For");
  9675. res.set_content("ok", "text/plain");
  9676. });
  9677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9678. auto se = detail::scope_exit([&] {
  9679. svr.stop();
  9680. t.join();
  9681. ASSERT_FALSE(svr.is_running());
  9682. });
  9683. svr.wait_until_ready();
  9684. Client cli(HOST, PORT);
  9685. auto res = cli.Get(
  9686. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9687. ASSERT_TRUE(res);
  9688. EXPECT_EQ(StatusCode::OK_200, res->status);
  9689. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9690. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9691. }
  9692. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9693. Server svr;
  9694. svr.set_trusted_proxies({"192.0.2.45"});
  9695. std::string observed_remote_addr;
  9696. std::string observed_xff;
  9697. svr.Get("/ip", [&](const Request &req, Response &res) {
  9698. observed_remote_addr = req.remote_addr;
  9699. observed_xff = req.get_header_value("X-Forwarded-For");
  9700. res.set_content("ok", "text/plain");
  9701. });
  9702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. t.join();
  9706. ASSERT_FALSE(svr.is_running());
  9707. });
  9708. svr.wait_until_ready();
  9709. Client cli(HOST, PORT);
  9710. auto res = cli.Get("/ip", {{"X-Forwarded-For",
  9711. " 198.51.100.23 , 203.0.113.66 , 192.0.2.45 "}});
  9712. ASSERT_TRUE(res);
  9713. EXPECT_EQ(StatusCode::OK_200, res->status);
  9714. // Header parser trims surrounding whitespace of the header value
  9715. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9716. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9717. }
  9718. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9719. Server svr;
  9720. svr.Post("/post", [&](const Request &req, Response &res) {
  9721. res.set_content(req.body, "text/plain");
  9722. });
  9723. svr.Put("/put", [&](const Request &req, Response &res) {
  9724. res.set_content(req.body, "text/plain");
  9725. });
  9726. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9727. res.set_content(req.body, "text/plain");
  9728. });
  9729. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9730. res.set_content(req.body, "text/plain");
  9731. });
  9732. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9733. auto se = detail::scope_exit([&] {
  9734. svr.stop();
  9735. t.join();
  9736. ASSERT_FALSE(svr.is_running());
  9737. });
  9738. svr.wait_until_ready();
  9739. std::string resp;
  9740. // POST without Content-Length
  9741. ASSERT_TRUE(send_request(5,
  9742. "POST /post HTTP/1.1\r\n"
  9743. "Host: localhost\r\n"
  9744. "Connection: close\r\n"
  9745. "\r\n",
  9746. &resp));
  9747. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9748. // PUT without Content-Length
  9749. resp.clear();
  9750. ASSERT_TRUE(send_request(5,
  9751. "PUT /put HTTP/1.1\r\n"
  9752. "Host: localhost\r\n"
  9753. "Connection: close\r\n"
  9754. "\r\n",
  9755. &resp));
  9756. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9757. // PATCH without Content-Length
  9758. resp.clear();
  9759. ASSERT_TRUE(send_request(5,
  9760. "PATCH /patch HTTP/1.1\r\n"
  9761. "Host: localhost\r\n"
  9762. "Connection: close\r\n"
  9763. "\r\n",
  9764. &resp));
  9765. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9766. // DELETE without Content-Length
  9767. resp.clear();
  9768. ASSERT_TRUE(send_request(5,
  9769. "DELETE /delete HTTP/1.1\r\n"
  9770. "Host: localhost\r\n"
  9771. "Connection: close\r\n"
  9772. "\r\n",
  9773. &resp));
  9774. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9775. }
  9776. //==============================================================================
  9777. // open_stream() Tests
  9778. //==============================================================================
  9779. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9780. std::string result;
  9781. char buf[8192];
  9782. ssize_t n;
  9783. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9784. result.append(buf, static_cast<size_t>(n));
  9785. }
  9786. return result;
  9787. }
  9788. // Mock stream for unit tests
  9789. class MockStream : public Stream {
  9790. public:
  9791. std::string data;
  9792. size_t pos = 0;
  9793. ssize_t error_after = -1; // -1 = no error
  9794. explicit MockStream(const std::string &d, ssize_t err = -1)
  9795. : data(d), error_after(err) {}
  9796. bool is_readable() const override { return true; }
  9797. bool wait_readable() const override { return true; }
  9798. bool wait_writable() const override { return true; }
  9799. ssize_t read(char *ptr, size_t size) override {
  9800. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9801. if (pos >= data.size()) return 0;
  9802. size_t limit =
  9803. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9804. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9805. std::memcpy(ptr, data.data() + pos, to_read);
  9806. pos += to_read;
  9807. return static_cast<ssize_t>(to_read);
  9808. }
  9809. ssize_t write(const char *, size_t) override { return -1; }
  9810. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9811. ip = "127.0.0.1";
  9812. port = 0;
  9813. }
  9814. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9815. ip = "127.0.0.1";
  9816. port = 0;
  9817. }
  9818. socket_t socket() const override { return INVALID_SOCKET; }
  9819. time_t duration() const override { return 0; }
  9820. };
  9821. TEST(StreamHandleTest, Basic) {
  9822. ClientImpl::StreamHandle handle;
  9823. EXPECT_FALSE(handle.is_valid());
  9824. handle.response = detail::make_unique<Response>();
  9825. handle.error = Error::Connection;
  9826. EXPECT_FALSE(handle.is_valid());
  9827. handle.error = Error::Success;
  9828. EXPECT_TRUE(handle.is_valid());
  9829. }
  9830. TEST(BodyReaderTest, Basic) {
  9831. MockStream stream("Hello, World!");
  9832. detail::BodyReader reader;
  9833. reader.stream = &stream;
  9834. reader.content_length = 13;
  9835. char buf[32];
  9836. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9837. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9838. EXPECT_TRUE(reader.eof);
  9839. }
  9840. TEST(BodyReaderTest, NoStream) {
  9841. detail::BodyReader reader;
  9842. char buf[32];
  9843. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9844. EXPECT_EQ(Error::Connection, reader.last_error);
  9845. }
  9846. TEST(BodyReaderTest, Error) {
  9847. MockStream stream("Hello, World!", 5);
  9848. detail::BodyReader reader;
  9849. reader.stream = &stream;
  9850. reader.content_length = 13;
  9851. char buf[32];
  9852. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9853. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9854. EXPECT_EQ(Error::Read, reader.last_error);
  9855. }
  9856. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9857. // Mock-based StreamHandle tests relying on private internals are removed.
  9858. class OpenStreamTest : public ::testing::Test {
  9859. protected:
  9860. void SetUp() override {
  9861. svr_.Get("/hello", [](const Request &, Response &res) {
  9862. res.set_content("Hello World!", "text/plain");
  9863. });
  9864. svr_.Get("/large", [](const Request &, Response &res) {
  9865. res.set_content(std::string(10000, 'X'), "text/plain");
  9866. });
  9867. svr_.Get("/chunked", [](const Request &, Response &res) {
  9868. res.set_chunked_content_provider("text/plain",
  9869. [](size_t offset, DataSink &sink) {
  9870. if (offset < 15) {
  9871. sink.write("chunk", 5);
  9872. return true;
  9873. }
  9874. sink.done();
  9875. return true;
  9876. });
  9877. });
  9878. svr_.Get("/compressible", [](const Request &, Response &res) {
  9879. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9880. DataSink &sink) {
  9881. if (offset < 100 * 1024) {
  9882. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9883. sink.write(chunk.data(), chunk.size());
  9884. return true;
  9885. }
  9886. sink.done();
  9887. return true;
  9888. });
  9889. });
  9890. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9891. [](const Request & /*req*/, Response &res) {
  9892. auto i = new int(0);
  9893. res.set_header("Trailer", "Content-Length, X-Allowed");
  9894. res.set_chunked_content_provider(
  9895. "text/plain",
  9896. [i](size_t /*offset*/, DataSink &sink) {
  9897. switch (*i) {
  9898. case 0: sink.os << "123"; break;
  9899. case 1: sink.os << "456"; break;
  9900. case 2: sink.os << "789"; break;
  9901. case 3: {
  9902. sink.done_with_trailer(
  9903. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9904. } break;
  9905. }
  9906. (*i)++;
  9907. return true;
  9908. },
  9909. [i](bool success) {
  9910. EXPECT_TRUE(success);
  9911. delete i;
  9912. });
  9913. });
  9914. // Echo headers endpoint for header-related tests
  9915. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9916. std::string body;
  9917. for (const auto &h : req.headers) {
  9918. body.append(h.first);
  9919. body.push_back(':');
  9920. body.append(h.second);
  9921. body.push_back('\n');
  9922. }
  9923. res.set_content(body, "text/plain");
  9924. });
  9925. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9926. std::string body;
  9927. for (const auto &h : req.headers) {
  9928. body.append(h.first);
  9929. body.push_back(':');
  9930. body.append(h.second);
  9931. body.push_back('\n');
  9932. }
  9933. res.set_content(body, "text/plain");
  9934. });
  9935. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  9936. svr_.wait_until_ready();
  9937. }
  9938. void TearDown() override {
  9939. svr_.stop();
  9940. if (thread_.joinable()) thread_.join();
  9941. }
  9942. Server svr_;
  9943. std::thread thread_;
  9944. };
  9945. TEST_F(OpenStreamTest, Basic) {
  9946. Client cli("127.0.0.1", 8787);
  9947. auto handle = cli.open_stream("GET", "/hello");
  9948. EXPECT_TRUE(handle.is_valid());
  9949. EXPECT_EQ("Hello World!", read_all(handle));
  9950. }
  9951. TEST_F(OpenStreamTest, SmallBuffer) {
  9952. Client cli("127.0.0.1", 8787);
  9953. auto handle = cli.open_stream("GET", "/hello");
  9954. std::string result;
  9955. char buf[4];
  9956. ssize_t n;
  9957. while ((n = handle.read(buf, sizeof(buf))) > 0)
  9958. result.append(buf, static_cast<size_t>(n));
  9959. EXPECT_EQ("Hello World!", result);
  9960. }
  9961. TEST_F(OpenStreamTest, DefaultHeaders) {
  9962. Client cli("127.0.0.1", 8787);
  9963. // open_stream GET should include Host, User-Agent and Accept-Encoding
  9964. {
  9965. auto handle = cli.open_stream("GET", "/echo-headers");
  9966. ASSERT_TRUE(handle.is_valid());
  9967. auto body = read_all(handle);
  9968. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  9969. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  9970. std::string::npos);
  9971. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  9972. }
  9973. // open_stream POST with body and no explicit content_type should NOT add
  9974. // text/plain Content-Type (behavior differs from non-streaming path), but
  9975. // should include Content-Length
  9976. {
  9977. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  9978. ASSERT_TRUE(handle.is_valid());
  9979. auto body = read_all(handle);
  9980. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  9981. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  9982. }
  9983. // open_stream POST with explicit Content-Type should preserve it
  9984. {
  9985. auto handle = cli.open_stream("POST", "/echo-headers", {},
  9986. {{"Content-Type", "application/custom"}},
  9987. "{}", "application/custom");
  9988. ASSERT_TRUE(handle.is_valid());
  9989. auto body = read_all(handle);
  9990. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  9991. }
  9992. // User-specified User-Agent must not be overwritten for stream API
  9993. {
  9994. auto handle = cli.open_stream("GET", "/echo-headers", {},
  9995. {{"User-Agent", "MyAgent/1.2"}});
  9996. ASSERT_TRUE(handle.is_valid());
  9997. auto body = read_all(handle);
  9998. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  9999. }
  10000. }
  10001. TEST_F(OpenStreamTest, Large) {
  10002. Client cli("127.0.0.1", 8787);
  10003. auto handle = cli.open_stream("GET", "/large");
  10004. EXPECT_EQ(10000u, read_all(handle).size());
  10005. }
  10006. TEST_F(OpenStreamTest, ConnectionError) {
  10007. Client cli("127.0.0.1", 9999);
  10008. auto handle = cli.open_stream("GET", "/hello");
  10009. EXPECT_FALSE(handle.is_valid());
  10010. }
  10011. TEST_F(OpenStreamTest, Chunked) {
  10012. Client cli("127.0.0.1", 8787);
  10013. auto handle = cli.open_stream("GET", "/chunked");
  10014. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10015. "Transfer-Encoding") == "chunked");
  10016. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10017. }
  10018. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10019. Client cli("127.0.0.1", 8787);
  10020. auto handle =
  10021. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10022. ASSERT_TRUE(handle.is_valid());
  10023. // Consume body to allow trailers to be received/parsed
  10024. auto body = read_all(handle);
  10025. // Explicitly parse trailers (ensure trailers are available for assertion)
  10026. handle.parse_trailers_if_needed();
  10027. EXPECT_EQ(std::string("123456789"), body);
  10028. // The response should include a Trailer header declaring both names
  10029. ASSERT_TRUE(handle.response);
  10030. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10031. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10032. handle.response->get_header_value("Trailer"));
  10033. // Prohibited trailer must not be present
  10034. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10035. // Allowed trailer should be present
  10036. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10037. EXPECT_EQ(std::string("yes"),
  10038. handle.response->get_trailer_value("X-Allowed"));
  10039. // Verify trailers are NOT present as regular headers
  10040. EXPECT_EQ(std::string(""),
  10041. handle.response->get_header_value("Content-Length"));
  10042. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10043. }
  10044. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10045. TEST_F(OpenStreamTest, Gzip) {
  10046. Client cli("127.0.0.1", 8787);
  10047. auto handle = cli.open_stream("GET", "/compressible", {},
  10048. {{"Accept-Encoding", "gzip"}});
  10049. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10050. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10051. }
  10052. #endif
  10053. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10054. TEST_F(OpenStreamTest, Brotli) {
  10055. Client cli("127.0.0.1", 8787);
  10056. auto handle =
  10057. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10058. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10059. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10060. }
  10061. #endif
  10062. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10063. TEST_F(OpenStreamTest, Zstd) {
  10064. Client cli("127.0.0.1", 8787);
  10065. auto handle = cli.open_stream("GET", "/compressible", {},
  10066. {{"Accept-Encoding", "zstd"}});
  10067. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10068. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10069. }
  10070. #endif
  10071. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10072. class SSLOpenStreamTest : public ::testing::Test {
  10073. protected:
  10074. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10075. void SetUp() override {
  10076. svr_.Get("/hello", [](const Request &, Response &res) {
  10077. res.set_content("Hello SSL World!", "text/plain");
  10078. });
  10079. svr_.Get("/chunked", [](const Request &, Response &res) {
  10080. res.set_chunked_content_provider("text/plain",
  10081. [](size_t offset, DataSink &sink) {
  10082. if (offset < 15) {
  10083. sink.write("chunk", 5);
  10084. return true;
  10085. }
  10086. sink.done();
  10087. return true;
  10088. });
  10089. });
  10090. svr_.Post("/echo", [](const Request &req, Response &res) {
  10091. res.set_content(req.body, req.get_header_value("Content-Type"));
  10092. });
  10093. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10094. std::string body = req.body;
  10095. res.set_chunked_content_provider(
  10096. "text/plain", [body](size_t offset, DataSink &sink) {
  10097. if (offset < body.size()) {
  10098. sink.write(body.data() + offset, body.size() - offset);
  10099. }
  10100. sink.done();
  10101. return true;
  10102. });
  10103. });
  10104. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10105. svr_.wait_until_ready();
  10106. }
  10107. void TearDown() override {
  10108. svr_.stop();
  10109. if (thread_.joinable()) thread_.join();
  10110. }
  10111. SSLServer svr_;
  10112. std::thread thread_;
  10113. };
  10114. TEST_F(SSLOpenStreamTest, Basic) {
  10115. SSLClient cli("127.0.0.1", 8788);
  10116. cli.enable_server_certificate_verification(false);
  10117. auto handle = cli.open_stream("GET", "/hello");
  10118. ASSERT_TRUE(handle.is_valid());
  10119. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10120. }
  10121. TEST_F(SSLOpenStreamTest, Chunked) {
  10122. SSLClient cli("127.0.0.1", 8788);
  10123. cli.enable_server_certificate_verification(false);
  10124. auto handle = cli.open_stream("GET", "/chunked");
  10125. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10126. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10127. "Transfer-Encoding") == "chunked");
  10128. auto body = read_all(handle);
  10129. EXPECT_EQ("chunkchunkchunk", body);
  10130. }
  10131. TEST_F(SSLOpenStreamTest, Post) {
  10132. SSLClient cli("127.0.0.1", 8788);
  10133. cli.enable_server_certificate_verification(false);
  10134. auto handle =
  10135. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10136. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10137. EXPECT_EQ(200, handle.response->status);
  10138. auto body = read_all(handle);
  10139. EXPECT_EQ("Hello SSL POST", body);
  10140. }
  10141. TEST_F(SSLOpenStreamTest, PostChunked) {
  10142. SSLClient cli("127.0.0.1", 8788);
  10143. cli.enable_server_certificate_verification(false);
  10144. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10145. "Chunked SSL Data", "text/plain");
  10146. ASSERT_TRUE(handle.is_valid());
  10147. EXPECT_EQ(200, handle.response->status);
  10148. auto body = read_all(handle);
  10149. EXPECT_EQ("Chunked SSL Data", body);
  10150. }
  10151. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10152. //==============================================================================
  10153. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10154. // results for various scenarios.
  10155. //==============================================================================
  10156. TEST(ParityTest, GetVsOpenStream) {
  10157. Server svr;
  10158. const std::string path = "/parity";
  10159. const std::string content = "Parity test content: hello world";
  10160. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10161. res.set_content(content, "text/plain");
  10162. });
  10163. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10164. auto se = detail::scope_exit([&] {
  10165. svr.stop();
  10166. t.join();
  10167. ASSERT_FALSE(svr.is_running());
  10168. });
  10169. svr.wait_until_ready();
  10170. Client cli(HOST, PORT);
  10171. // Non-stream path
  10172. auto r1 = cli.Get(path);
  10173. ASSERT_TRUE(r1);
  10174. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10175. // Stream path
  10176. auto h = cli.open_stream("GET", path);
  10177. ASSERT_TRUE(h.is_valid());
  10178. EXPECT_EQ(r1->body, read_all(h));
  10179. }
  10180. // Helper to compress data with provided compressor type T
  10181. template <typename Compressor>
  10182. static std::string compress_payload_for_parity(const std::string &in) {
  10183. std::string out;
  10184. Compressor compressor;
  10185. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10186. [&](const char *data, size_t n) {
  10187. out.append(data, n);
  10188. return true;
  10189. });
  10190. EXPECT_TRUE(ok);
  10191. return out;
  10192. }
  10193. // Helper function for compression parity tests
  10194. template <typename Compressor>
  10195. static void test_compression_parity(const std::string &original,
  10196. const std::string &path,
  10197. const std::string &encoding) {
  10198. const std::string compressed =
  10199. compress_payload_for_parity<Compressor>(original);
  10200. Server svr;
  10201. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10202. res.set_content(compressed, "application/octet-stream");
  10203. res.set_header("Content-Encoding", encoding);
  10204. });
  10205. auto t = std::thread([&] { svr.listen("localhost", 1234); });
  10206. auto se = detail::scope_exit([&] {
  10207. svr.stop();
  10208. t.join();
  10209. ASSERT_FALSE(svr.is_running());
  10210. });
  10211. svr.wait_until_ready();
  10212. Client cli("localhost", 1234);
  10213. // Non-streaming
  10214. {
  10215. auto res = cli.Get(path);
  10216. ASSERT_TRUE(res);
  10217. EXPECT_EQ(StatusCode::OK_200, res->status);
  10218. EXPECT_EQ(original, res->body);
  10219. }
  10220. // Streaming
  10221. {
  10222. auto h = cli.open_stream("GET", path);
  10223. ASSERT_TRUE(h.is_valid());
  10224. EXPECT_EQ(original, read_all(h));
  10225. }
  10226. }
  10227. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10228. TEST(ParityTest, Gzip) {
  10229. test_compression_parity<detail::gzip_compressor>(
  10230. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10231. }
  10232. #endif
  10233. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10234. TEST(ParityTest, Brotli) {
  10235. test_compression_parity<detail::brotli_compressor>(
  10236. "Hello, brotli parity test payload", "/parity-br", "br");
  10237. }
  10238. #endif
  10239. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10240. TEST(ParityTest, Zstd) {
  10241. test_compression_parity<detail::zstd_compressor>(
  10242. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10243. }
  10244. #endif
  10245. //==============================================================================
  10246. // New Stream API Tests
  10247. //==============================================================================
  10248. inline std::string read_body(httplib::stream::Result &result) {
  10249. std::string body;
  10250. while (result.next()) {
  10251. body.append(result.data(), result.size());
  10252. }
  10253. return body;
  10254. }
  10255. TEST(ClientConnectionTest, Basic) {
  10256. httplib::ClientConnection conn;
  10257. EXPECT_FALSE(conn.is_open());
  10258. conn.sock = 1;
  10259. EXPECT_TRUE(conn.is_open());
  10260. httplib::ClientConnection conn2(std::move(conn));
  10261. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10262. conn2.sock = INVALID_SOCKET;
  10263. }
  10264. // Unified test server for all stream::* tests
  10265. class StreamApiTest : public ::testing::Test {
  10266. protected:
  10267. void SetUp() override {
  10268. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10269. res.set_content("Hello World!", "text/plain");
  10270. });
  10271. svr_.Get("/echo-params",
  10272. [](const httplib::Request &req, httplib::Response &res) {
  10273. std::string r;
  10274. for (const auto &p : req.params) {
  10275. if (!r.empty()) r += "&";
  10276. r += p.first + "=" + p.second;
  10277. }
  10278. res.set_content(r, "text/plain");
  10279. });
  10280. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10281. res.set_content(req.body, req.get_header_value("Content-Type"));
  10282. });
  10283. svr_.Post("/echo-headers",
  10284. [](const httplib::Request &req, httplib::Response &res) {
  10285. std::string r;
  10286. for (const auto &h : req.headers)
  10287. r += h.first + ": " + h.second + "\n";
  10288. res.set_content(r, "text/plain");
  10289. });
  10290. svr_.Post("/echo-params",
  10291. [](const httplib::Request &req, httplib::Response &res) {
  10292. std::string r = "params:";
  10293. for (const auto &p : req.params)
  10294. r += p.first + "=" + p.second + ";";
  10295. res.set_content(r + " body:" + req.body, "text/plain");
  10296. });
  10297. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10298. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10299. });
  10300. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10301. res.set_content("PUT:" + req.body, "text/plain");
  10302. });
  10303. svr_.Patch("/echo",
  10304. [](const httplib::Request &req, httplib::Response &res) {
  10305. res.set_content("PATCH:" + req.body, "text/plain");
  10306. });
  10307. svr_.Delete(
  10308. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10309. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10310. "text/plain");
  10311. });
  10312. svr_.Get("/head-test",
  10313. [](const httplib::Request &, httplib::Response &res) {
  10314. res.set_content("body for HEAD", "text/plain");
  10315. });
  10316. svr_.Options("/options",
  10317. [](const httplib::Request &, httplib::Response &res) {
  10318. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10319. });
  10320. thread_ = std::thread([this]() { svr_.listen("localhost", 8790); });
  10321. svr_.wait_until_ready();
  10322. }
  10323. void TearDown() override {
  10324. svr_.stop();
  10325. if (thread_.joinable()) thread_.join();
  10326. }
  10327. httplib::Server svr_;
  10328. std::thread thread_;
  10329. };
  10330. // stream::Get tests
  10331. TEST_F(StreamApiTest, GetBasic) {
  10332. httplib::Client cli("localhost", 8790);
  10333. auto result = httplib::stream::Get(cli, "/hello");
  10334. ASSERT_TRUE(result.is_valid());
  10335. EXPECT_EQ(200, result.status());
  10336. EXPECT_EQ("Hello World!", read_body(result));
  10337. }
  10338. TEST_F(StreamApiTest, GetWithParams) {
  10339. httplib::Client cli("localhost", 8790);
  10340. httplib::Params params{{"foo", "bar"}};
  10341. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10342. ASSERT_TRUE(result.is_valid());
  10343. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10344. }
  10345. TEST_F(StreamApiTest, GetConnectionError) {
  10346. httplib::Client cli("localhost", 9999);
  10347. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10348. }
  10349. TEST_F(StreamApiTest, Get404) {
  10350. httplib::Client cli("localhost", 8790);
  10351. auto result = httplib::stream::Get(cli, "/nonexistent");
  10352. EXPECT_TRUE(result.is_valid());
  10353. EXPECT_EQ(404, result.status());
  10354. }
  10355. // stream::Post tests
  10356. TEST_F(StreamApiTest, PostBasic) {
  10357. httplib::Client cli("localhost", 8790);
  10358. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10359. "application/json");
  10360. ASSERT_TRUE(result.is_valid());
  10361. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10362. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10363. }
  10364. TEST_F(StreamApiTest, PostWithHeaders) {
  10365. httplib::Client cli("localhost", 8790);
  10366. httplib::Headers headers{{"X-Custom", "value"}};
  10367. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10368. "text/plain");
  10369. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10370. }
  10371. TEST_F(StreamApiTest, PostWithParams) {
  10372. httplib::Client cli("localhost", 8790);
  10373. httplib::Params params{{"k", "v"}};
  10374. auto result =
  10375. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10376. auto body = read_body(result);
  10377. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10378. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10379. }
  10380. TEST_F(StreamApiTest, PostLarge) {
  10381. httplib::Client cli("localhost", 8790);
  10382. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10383. size_t total = 0;
  10384. while (result.next()) {
  10385. total += result.size();
  10386. }
  10387. EXPECT_EQ(100u * 1024u, total);
  10388. }
  10389. // stream::Put/Patch tests
  10390. TEST_F(StreamApiTest, PutAndPatch) {
  10391. httplib::Client cli("localhost", 8790);
  10392. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10393. EXPECT_EQ("PUT:test", read_body(put));
  10394. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10395. EXPECT_EQ("PATCH:test", read_body(patch));
  10396. }
  10397. // stream::Delete tests
  10398. TEST_F(StreamApiTest, Delete) {
  10399. httplib::Client cli("localhost", 8790);
  10400. auto del1 = httplib::stream::Delete(cli, "/resource");
  10401. EXPECT_EQ("Deleted", read_body(del1));
  10402. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10403. EXPECT_EQ("Deleted:data", read_body(del2));
  10404. }
  10405. // stream::Head/Options tests
  10406. TEST_F(StreamApiTest, HeadAndOptions) {
  10407. httplib::Client cli("localhost", 8790);
  10408. auto head = httplib::stream::Head(cli, "/head-test");
  10409. EXPECT_TRUE(head.is_valid());
  10410. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10411. auto opts = httplib::stream::Options(cli, "/options");
  10412. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10413. }
  10414. // SSL stream::* tests
  10415. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10416. class SSLStreamApiTest : public ::testing::Test {
  10417. protected:
  10418. void SetUp() override {
  10419. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10420. res.set_content("Hello SSL!", "text/plain");
  10421. });
  10422. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10423. res.set_content(req.body, "text/plain");
  10424. });
  10425. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10426. svr_.wait_until_ready();
  10427. }
  10428. void TearDown() override {
  10429. svr_.stop();
  10430. if (thread_.joinable()) thread_.join();
  10431. }
  10432. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10433. std::thread thread_;
  10434. };
  10435. TEST_F(SSLStreamApiTest, GetAndPost) {
  10436. httplib::SSLClient cli("127.0.0.1", 8803);
  10437. cli.enable_server_certificate_verification(false);
  10438. auto get = httplib::stream::Get(cli, "/hello");
  10439. EXPECT_EQ("Hello SSL!", read_body(get));
  10440. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10441. EXPECT_EQ("test", read_body(post));
  10442. }
  10443. #endif
  10444. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10445. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10446. // BodyReader
  10447. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10448. // Test that read timeout during streaming is detected
  10449. // Use a large content-length response where server delays mid-stream
  10450. Server svr;
  10451. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10452. // Send a large response with delay in the middle
  10453. res.set_content_provider(
  10454. 1000, // content_length
  10455. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10456. if (offset < 100) {
  10457. // Send first 100 bytes immediately
  10458. std::string data(100, 'A');
  10459. sink.write(data.c_str(), data.size());
  10460. return true;
  10461. }
  10462. // Then delay longer than client timeout
  10463. std::this_thread::sleep_for(std::chrono::seconds(3));
  10464. std::string data(900, 'B');
  10465. sink.write(data.c_str(), data.size());
  10466. return true;
  10467. });
  10468. });
  10469. auto port = 8091;
  10470. std::thread t([&]() { svr.listen("localhost", port); });
  10471. svr.wait_until_ready();
  10472. Client cli("localhost", port);
  10473. cli.set_read_timeout(1, 0); // 1 second timeout
  10474. auto handle = cli.open_stream("GET", "/slow-stream");
  10475. ASSERT_TRUE(handle.is_valid());
  10476. char buf[256];
  10477. ssize_t total = 0;
  10478. ssize_t n;
  10479. bool got_error = false;
  10480. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10481. total += n;
  10482. }
  10483. if (n < 0) {
  10484. got_error = true;
  10485. // Should be timeout or read error
  10486. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10487. handle.get_read_error() == Error::Read)
  10488. << "Actual error: " << to_string(handle.get_read_error());
  10489. }
  10490. // Either we got an error, or we got less data than expected
  10491. EXPECT_TRUE(got_error || total < 1000)
  10492. << "Expected timeout but got all " << total << " bytes";
  10493. svr.stop();
  10494. t.join();
  10495. }
  10496. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10497. // Test connection closed detection via BodyReader
  10498. Server svr;
  10499. std::atomic<bool> close_now{false};
  10500. svr.Get("/will-close", [&](const Request &, Response &res) {
  10501. res.set_content_provider(
  10502. 10000, // Large content_length that we won't fully send
  10503. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10504. if (offset < 100) {
  10505. std::string data(100, 'X');
  10506. sink.write(data.c_str(), data.size());
  10507. return true;
  10508. }
  10509. // Wait for signal then abort
  10510. while (!close_now) {
  10511. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10512. }
  10513. return false; // Abort - server will close connection
  10514. });
  10515. });
  10516. auto port = 8092;
  10517. std::thread t([&]() { svr.listen("localhost", port); });
  10518. svr.wait_until_ready();
  10519. Client cli("localhost", port);
  10520. auto handle = cli.open_stream("GET", "/will-close");
  10521. ASSERT_TRUE(handle.is_valid());
  10522. char buf[256];
  10523. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10524. EXPECT_GT(n, 0) << "First read should succeed";
  10525. // Signal server to close
  10526. close_now = true;
  10527. // Keep reading until error or EOF
  10528. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10529. // Keep reading
  10530. }
  10531. // Should get an error since content_length wasn't satisfied
  10532. if (n < 0) {
  10533. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10534. handle.get_read_error() == Error::Read)
  10535. << "Actual error: " << to_string(handle.get_read_error());
  10536. }
  10537. svr.stop();
  10538. t.join();
  10539. }
  10540. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10541. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10542. // Test that read timeout during SSL streaming is detected
  10543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10544. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10545. res.set_content_provider(
  10546. 1000, "text/plain",
  10547. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10548. if (offset < 100) {
  10549. std::string data(100, 'A');
  10550. sink.write(data.c_str(), data.size());
  10551. return true;
  10552. }
  10553. std::this_thread::sleep_for(std::chrono::seconds(3));
  10554. std::string data(900, 'B');
  10555. sink.write(data.c_str(), data.size());
  10556. return true;
  10557. });
  10558. });
  10559. auto port = 8093;
  10560. std::thread t([&]() { svr.listen("localhost", port); });
  10561. svr.wait_until_ready();
  10562. SSLClient cli("localhost", port);
  10563. cli.enable_server_certificate_verification(false);
  10564. cli.set_read_timeout(1, 0); // 1 second timeout
  10565. auto handle = cli.open_stream("GET", "/slow-stream");
  10566. ASSERT_TRUE(handle.is_valid());
  10567. char buf[256];
  10568. ssize_t total = 0;
  10569. ssize_t n;
  10570. bool got_error = false;
  10571. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10572. total += n;
  10573. }
  10574. if (n < 0) {
  10575. got_error = true;
  10576. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10577. handle.get_read_error() == Error::Read)
  10578. << "Actual error: " << to_string(handle.get_read_error());
  10579. }
  10580. EXPECT_TRUE(got_error || total < 1000)
  10581. << "Expected timeout but got all " << total << " bytes";
  10582. svr.stop();
  10583. t.join();
  10584. }
  10585. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10586. // Test SSL connection closed detection
  10587. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10588. std::atomic<bool> close_now{false};
  10589. svr.Get("/will-close", [&](const Request &, Response &res) {
  10590. res.set_content_provider(
  10591. 10000, "text/plain",
  10592. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10593. if (offset < 100) {
  10594. std::string data(100, 'X');
  10595. sink.write(data.c_str(), data.size());
  10596. return true;
  10597. }
  10598. while (!close_now) {
  10599. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10600. }
  10601. return false;
  10602. });
  10603. });
  10604. auto port = 8094;
  10605. std::thread t([&]() { svr.listen("localhost", port); });
  10606. svr.wait_until_ready();
  10607. SSLClient cli("localhost", port);
  10608. cli.enable_server_certificate_verification(false);
  10609. auto handle = cli.open_stream("GET", "/will-close");
  10610. ASSERT_TRUE(handle.is_valid());
  10611. char buf[256];
  10612. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10613. EXPECT_GT(n, 0);
  10614. // Signal server to close
  10615. close_now = true;
  10616. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10617. // Keep reading
  10618. }
  10619. if (n < 0) {
  10620. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10621. handle.get_read_error() == Error::Read)
  10622. << "Actual error: " << to_string(handle.get_read_error());
  10623. }
  10624. svr.stop();
  10625. t.join();
  10626. }
  10627. #endif
  10628. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10629. using namespace httplib;
  10630. // Create a test file
  10631. const char *fname = "etag_testfile.txt";
  10632. const char *content = "etag-content";
  10633. {
  10634. std::ofstream ofs(fname);
  10635. ofs << content;
  10636. ASSERT_TRUE(ofs.good());
  10637. }
  10638. Server svr;
  10639. svr.set_mount_point("/static", ".");
  10640. auto t = std::thread([&]() { svr.listen("localhost", 8087); });
  10641. svr.wait_until_ready();
  10642. Client cli("localhost", 8087);
  10643. // First request: should get 200 with ETag header
  10644. auto res1 = cli.Get("/static/etag_testfile.txt");
  10645. ASSERT_TRUE(res1);
  10646. ASSERT_EQ(200, res1->status);
  10647. ASSERT_TRUE(res1->has_header("ETag"));
  10648. std::string etag = res1->get_header_value("ETag");
  10649. EXPECT_FALSE(etag.empty());
  10650. // Verify ETag format: W/"hex-hex"
  10651. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10652. EXPECT_EQ('W', etag[0]);
  10653. EXPECT_EQ('/', etag[1]);
  10654. EXPECT_EQ('"', etag[2]);
  10655. EXPECT_EQ('"', etag.back());
  10656. // Exact match: expect 304 Not Modified
  10657. Headers h2 = {{"If-None-Match", etag}};
  10658. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10659. ASSERT_TRUE(res2);
  10660. EXPECT_EQ(304, res2->status);
  10661. // Wildcard match: expect 304 Not Modified
  10662. Headers h3 = {{"If-None-Match", "*"}};
  10663. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10664. ASSERT_TRUE(res3);
  10665. EXPECT_EQ(304, res3->status);
  10666. // Non-matching ETag: expect 200
  10667. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10668. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10669. ASSERT_TRUE(res4);
  10670. EXPECT_EQ(200, res4->status);
  10671. // Multiple ETags with one matching: expect 304
  10672. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10673. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10674. ASSERT_TRUE(res5);
  10675. EXPECT_EQ(304, res5->status);
  10676. svr.stop();
  10677. t.join();
  10678. std::remove(fname);
  10679. }
  10680. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10681. using namespace httplib;
  10682. Server svr;
  10683. svr.set_mount_point("/static", ".");
  10684. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10685. svr.wait_until_ready();
  10686. Client cli("localhost", 8090);
  10687. // Send If-None-Match: * to a non-existent file
  10688. Headers h = {{"If-None-Match", "*"}};
  10689. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10690. ASSERT_TRUE(res);
  10691. EXPECT_EQ(404, res->status);
  10692. svr.stop();
  10693. t.join();
  10694. }
  10695. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10696. using namespace httplib;
  10697. // Create a test file
  10698. const char *fname = "ims_testfile.txt";
  10699. const char *content = "if-modified-since-test";
  10700. {
  10701. std::ofstream ofs(fname);
  10702. ofs << content;
  10703. ASSERT_TRUE(ofs.good());
  10704. }
  10705. Server svr;
  10706. svr.set_mount_point("/static", ".");
  10707. auto t = std::thread([&]() { svr.listen("localhost", 8088); });
  10708. svr.wait_until_ready();
  10709. Client cli("localhost", 8088);
  10710. // First request: should get 200 with Last-Modified header
  10711. auto res1 = cli.Get("/static/ims_testfile.txt");
  10712. ASSERT_TRUE(res1);
  10713. ASSERT_EQ(200, res1->status);
  10714. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10715. std::string last_modified = res1->get_header_value("Last-Modified");
  10716. EXPECT_FALSE(last_modified.empty());
  10717. // If-Modified-Since with same time: expect 304
  10718. Headers h2 = {{"If-Modified-Since", last_modified}};
  10719. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10720. ASSERT_TRUE(res2);
  10721. EXPECT_EQ(304, res2->status);
  10722. // If-Modified-Since with future time: expect 304
  10723. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10724. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10725. ASSERT_TRUE(res3);
  10726. EXPECT_EQ(304, res3->status);
  10727. // If-Modified-Since with past time: expect 200
  10728. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10729. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10730. ASSERT_TRUE(res4);
  10731. EXPECT_EQ(200, res4->status);
  10732. // If-None-Match takes precedence over If-Modified-Since
  10733. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10734. ASSERT_TRUE(res1->has_header("ETag"));
  10735. std::string etag = res1->get_header_value("ETag");
  10736. Headers h5 = {{"If-None-Match", etag},
  10737. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10738. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10739. ASSERT_TRUE(res5);
  10740. EXPECT_EQ(304, res5->status);
  10741. svr.stop();
  10742. t.join();
  10743. std::remove(fname);
  10744. }
  10745. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10746. using namespace httplib;
  10747. Server svr;
  10748. // Endpoint that returns compressible content
  10749. svr.Get("/compressible", [](const Request &, Response &res) {
  10750. // Return a large enough body to trigger compression
  10751. std::string body(1000, 'a');
  10752. res.set_content(body, "text/plain");
  10753. });
  10754. auto t = std::thread([&]() { svr.listen("localhost", 8089); });
  10755. svr.wait_until_ready();
  10756. Client cli("localhost", 8089);
  10757. // Request with gzip support: should get Vary header when compressed
  10758. cli.set_compress(true);
  10759. auto res1 = cli.Get("/compressible");
  10760. ASSERT_TRUE(res1);
  10761. EXPECT_EQ(200, res1->status);
  10762. // If Content-Encoding is set, Vary should also be set
  10763. if (res1->has_header("Content-Encoding")) {
  10764. EXPECT_TRUE(res1->has_header("Vary"));
  10765. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10766. }
  10767. // Request without Accept-Encoding header: should not have compression
  10768. Headers h_no_compress;
  10769. auto res2 = cli.Get("/compressible", h_no_compress);
  10770. ASSERT_TRUE(res2);
  10771. EXPECT_EQ(200, res2->status);
  10772. // Verify Vary header is present when compression is applied
  10773. // (the exact behavior depends on server configuration)
  10774. svr.stop();
  10775. t.join();
  10776. }
  10777. TEST(ETagTest, IfRangeWithETag) {
  10778. using namespace httplib;
  10779. // Create a test file with known content
  10780. const char *fname = "if_range_testfile.txt";
  10781. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10782. {
  10783. std::ofstream ofs(fname);
  10784. ofs << content;
  10785. ASSERT_TRUE(ofs.good());
  10786. }
  10787. Server svr;
  10788. svr.set_mount_point("/static", ".");
  10789. auto t = std::thread([&]() { svr.listen("localhost", 8090); });
  10790. svr.wait_until_ready();
  10791. Client cli("localhost", 8090);
  10792. // First request: get ETag
  10793. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10794. ASSERT_TRUE(res1);
  10795. ASSERT_EQ(200, res1->status);
  10796. ASSERT_TRUE(res1->has_header("ETag"));
  10797. std::string etag = res1->get_header_value("ETag");
  10798. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10799. // Since our server generates weak ETags (W/"..."), If-Range with our
  10800. // ETag should NOT result in partial content - it should return full content.
  10801. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10802. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10803. ASSERT_TRUE(res2);
  10804. // Weak ETag in If-Range -> full content (200), not partial (206)
  10805. EXPECT_EQ(200, res2->status);
  10806. EXPECT_EQ(content, res2->body);
  10807. EXPECT_FALSE(res2->has_header("Content-Range"));
  10808. // Range request with non-matching If-Range (ETag): should get 200 (full
  10809. // content)
  10810. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10811. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10812. ASSERT_TRUE(res3);
  10813. EXPECT_EQ(200, res3->status);
  10814. EXPECT_EQ(content, res3->body);
  10815. EXPECT_FALSE(res3->has_header("Content-Range"));
  10816. // Range request with strong ETag (hypothetical - our server doesn't generate
  10817. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10818. // should return full content)
  10819. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10820. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10821. ASSERT_TRUE(res4);
  10822. EXPECT_EQ(200, res4->status);
  10823. EXPECT_EQ(content, res4->body);
  10824. EXPECT_FALSE(res4->has_header("Content-Range"));
  10825. svr.stop();
  10826. t.join();
  10827. std::remove(fname);
  10828. }
  10829. TEST(ETagTest, IfRangeWithDate) {
  10830. using namespace httplib;
  10831. // Create a test file
  10832. const char *fname = "if_range_date_testfile.txt";
  10833. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10834. {
  10835. std::ofstream ofs(fname);
  10836. ofs << content;
  10837. ASSERT_TRUE(ofs.good());
  10838. }
  10839. Server svr;
  10840. svr.set_mount_point("/static", ".");
  10841. auto t = std::thread([&]() { svr.listen("localhost", 8091); });
  10842. svr.wait_until_ready();
  10843. Client cli("localhost", 8091);
  10844. // First request: get Last-Modified
  10845. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10846. ASSERT_TRUE(res1);
  10847. ASSERT_EQ(200, res1->status);
  10848. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10849. std::string last_modified = res1->get_header_value("Last-Modified");
  10850. // Range request with matching If-Range (date): should get 206
  10851. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10852. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10853. ASSERT_TRUE(res2);
  10854. EXPECT_EQ(206, res2->status);
  10855. EXPECT_EQ("FGHIJ", res2->body);
  10856. // Range request with old If-Range date: should get 200 (full content)
  10857. Headers h3 = {{"Range", "bytes=5-9"},
  10858. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10859. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10860. ASSERT_TRUE(res3);
  10861. EXPECT_EQ(200, res3->status);
  10862. EXPECT_EQ(content, res3->body);
  10863. // Range request with future If-Range date: should get 206
  10864. Headers h4 = {{"Range", "bytes=0-4"},
  10865. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10866. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10867. ASSERT_TRUE(res4);
  10868. EXPECT_EQ(206, res4->status);
  10869. EXPECT_EQ("ABCDE", res4->body);
  10870. svr.stop();
  10871. t.join();
  10872. std::remove(fname);
  10873. }
  10874. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10875. using namespace httplib;
  10876. const char *fname = "etag_malformed.txt";
  10877. const char *content = "malformed-etag";
  10878. {
  10879. std::ofstream ofs(fname);
  10880. ofs << content;
  10881. ASSERT_TRUE(ofs.good());
  10882. }
  10883. Server svr;
  10884. svr.set_mount_point("/static", ".");
  10885. auto t = std::thread([&]() { svr.listen("localhost", 8092); });
  10886. svr.wait_until_ready();
  10887. Client cli("localhost", 8092);
  10888. // baseline: should get 200 and an ETag
  10889. auto res1 = cli.Get("/static/etag_malformed.txt");
  10890. ASSERT_TRUE(res1);
  10891. ASSERT_EQ(200, res1->status);
  10892. ASSERT_TRUE(res1->has_header("ETag"));
  10893. // Malformed ETag value (missing quotes) should be treated as non-matching
  10894. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10895. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10896. ASSERT_TRUE(res_bad);
  10897. EXPECT_EQ(200, res_bad->status);
  10898. // Whitespace-only header value should be considered invalid / non-matching
  10899. Headers h_space = {{"If-None-Match", " "}};
  10900. auto res_space = cli.Get("/static/etag_malformed.txt", h_space);
  10901. ASSERT_TRUE(res_space);
  10902. EXPECT_EQ(200, res_space->status);
  10903. svr.stop();
  10904. t.join();
  10905. std::remove(fname);
  10906. }
  10907. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10908. using namespace httplib;
  10909. const char *fname = "ims_invalid_format.txt";
  10910. const char *content = "ims-bad-format";
  10911. {
  10912. std::ofstream ofs(fname);
  10913. ofs << content;
  10914. ASSERT_TRUE(ofs.good());
  10915. }
  10916. Server svr;
  10917. svr.set_mount_point("/static", ".");
  10918. auto t = std::thread([&]() { svr.listen("localhost", 8093); });
  10919. svr.wait_until_ready();
  10920. Client cli("localhost", 8093);
  10921. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10922. ASSERT_TRUE(res1);
  10923. ASSERT_EQ(200, res1->status);
  10924. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10925. // If-Modified-Since with invalid format should not result in 304
  10926. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  10927. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  10928. ASSERT_TRUE(res_bad);
  10929. EXPECT_EQ(200, res_bad->status);
  10930. // If-Range with invalid date format should be treated as mismatch -> full
  10931. // content (200)
  10932. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  10933. {"If-Range", "invalid-date"}};
  10934. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  10935. ASSERT_TRUE(res_ifrange);
  10936. EXPECT_EQ(200, res_ifrange->status);
  10937. svr.stop();
  10938. t.join();
  10939. std::remove(fname);
  10940. }
  10941. TEST(ETagTest, IfRangeWithMalformedETag) {
  10942. using namespace httplib;
  10943. const char *fname = "ifrange_malformed.txt";
  10944. const std::string content = "0123456789";
  10945. {
  10946. std::ofstream ofs(fname);
  10947. ofs << content;
  10948. ASSERT_TRUE(ofs.good());
  10949. }
  10950. Server svr;
  10951. svr.set_mount_point("/static", ".");
  10952. auto t = std::thread([&]() { svr.listen("localhost", 8094); });
  10953. svr.wait_until_ready();
  10954. Client cli("localhost", 8094);
  10955. // First request: get ETag
  10956. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  10957. ASSERT_TRUE(res1);
  10958. ASSERT_EQ(200, res1->status);
  10959. ASSERT_TRUE(res1->has_header("ETag"));
  10960. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  10961. // full content (200)
  10962. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  10963. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  10964. ASSERT_TRUE(res2);
  10965. EXPECT_EQ(200, res2->status);
  10966. EXPECT_EQ(content, res2->body);
  10967. svr.stop();
  10968. t.join();
  10969. std::remove(fname);
  10970. }
  10971. TEST(ETagTest, ExtremeLargeDateValues) {
  10972. using namespace httplib;
  10973. const char *fname = "ims_extreme_date.txt";
  10974. const char *content = "ims-extreme-date";
  10975. {
  10976. std::ofstream ofs(fname);
  10977. ofs << content;
  10978. ASSERT_TRUE(ofs.good());
  10979. }
  10980. Server svr;
  10981. svr.set_mount_point("/static", ".");
  10982. auto t = std::thread([&]() { svr.listen("localhost", 8095); });
  10983. svr.wait_until_ready();
  10984. Client cli("localhost", 8095);
  10985. auto res1 = cli.Get(std::string("/static/") + fname);
  10986. ASSERT_TRUE(res1);
  10987. ASSERT_EQ(200, res1->status);
  10988. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10989. // Extremely large year that may overflow date parsing routines.
  10990. Headers h_large_date = {
  10991. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  10992. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  10993. ASSERT_TRUE(res_bad);
  10994. // Expect server to treat this as invalid/mismatch and return full content
  10995. EXPECT_EQ(200, res_bad->status);
  10996. // If-Range with extremely large date should be treated as mismatch -> full
  10997. // content (200)
  10998. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  10999. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11000. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11001. ASSERT_TRUE(res_ifrange);
  11002. EXPECT_EQ(200, res_ifrange->status);
  11003. svr.stop();
  11004. t.join();
  11005. std::remove(fname);
  11006. }
  11007. TEST(ETagTest, NegativeFileModificationTime) {
  11008. using namespace httplib;
  11009. const char *fname = "ims_negative_mtime.txt";
  11010. const std::string content = "negative-mtime";
  11011. {
  11012. std::ofstream ofs(fname);
  11013. ofs << content;
  11014. ASSERT_TRUE(ofs.good());
  11015. }
  11016. // Try to set file mtime to a negative value. This may fail on some
  11017. // platforms/filesystems; if it fails, the test will still verify server
  11018. // behaves safely by performing a regular conditional request.
  11019. #if defined(__APPLE__) || defined(__linux__)
  11020. bool set_negative = false;
  11021. do {
  11022. struct timeval times[2];
  11023. // access time: now
  11024. times[0].tv_sec = time(nullptr);
  11025. times[0].tv_usec = 0;
  11026. // modification time: negative (e.g., -1)
  11027. times[1].tv_sec = -1;
  11028. times[1].tv_usec = 0;
  11029. if (utimes(fname, times) == 0) { set_negative = true; }
  11030. } while (0);
  11031. #else
  11032. bool set_negative = false;
  11033. #endif
  11034. Server svr;
  11035. svr.set_mount_point("/static", ".");
  11036. auto t = std::thread([&]() { svr.listen("localhost", 8096); });
  11037. svr.wait_until_ready();
  11038. Client cli("localhost", 8096);
  11039. auto res1 = cli.Get(std::string("/static/") + fname);
  11040. ASSERT_TRUE(res1);
  11041. ASSERT_EQ(200, res1->status);
  11042. bool has_last_modified = res1->has_header("Last-Modified");
  11043. std::string last_modified;
  11044. if (has_last_modified) {
  11045. last_modified = res1->get_header_value("Last-Modified");
  11046. }
  11047. if (set_negative) {
  11048. // If we successfully set a negative mtime, ensure server returns a
  11049. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11050. // with an old date and ensure server handles it without crash.
  11051. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11052. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11053. ASSERT_TRUE(res2);
  11054. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11055. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11056. } else {
  11057. // Could not set negative mtime on this platform; fall back to verifying
  11058. // that normal invalid/malformed dates are treated safely (non-304).
  11059. Headers h_bad_date = {
  11060. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11061. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11062. ASSERT_TRUE(res_bad);
  11063. EXPECT_EQ(200, res_bad->status);
  11064. }
  11065. svr.stop();
  11066. t.join();
  11067. std::remove(fname);
  11068. }
  11069. //==============================================================================
  11070. // SSE Parsing Tests
  11071. //==============================================================================
  11072. class SSEParsingTest : public ::testing::Test {
  11073. protected:
  11074. // Test helper that mimics SSE parsing behavior
  11075. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11076. int &retry_ms) {
  11077. // Blank line signals end of event
  11078. if (line.empty() || line == "\r") { return true; }
  11079. // Lines starting with ':' are comments (ignored)
  11080. if (!line.empty() && line[0] == ':') { return false; }
  11081. // Find the colon separator
  11082. auto colon_pos = line.find(':');
  11083. if (colon_pos == std::string::npos) {
  11084. // Line with no colon is treated as field name with empty value
  11085. return false;
  11086. }
  11087. std::string field = line.substr(0, colon_pos);
  11088. std::string value;
  11089. // Value starts after colon, skip optional single space
  11090. if (colon_pos + 1 < line.size()) {
  11091. size_t value_start = colon_pos + 1;
  11092. if (line[value_start] == ' ') { value_start++; }
  11093. value = line.substr(value_start);
  11094. // Remove trailing \r if present
  11095. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11096. }
  11097. // Handle known fields
  11098. if (field == "event") {
  11099. msg.event = value;
  11100. } else if (field == "data") {
  11101. // Multiple data lines are concatenated with newlines
  11102. if (!msg.data.empty()) { msg.data += "\n"; }
  11103. msg.data += value;
  11104. } else if (field == "id") {
  11105. // Empty id is valid (clears the last event ID)
  11106. msg.id = value;
  11107. } else if (field == "retry") {
  11108. // Parse retry interval in milliseconds
  11109. try {
  11110. retry_ms = std::stoi(value);
  11111. } catch (...) {
  11112. // Invalid retry value, ignore
  11113. }
  11114. }
  11115. // Unknown fields are ignored per SSE spec
  11116. return false;
  11117. }
  11118. };
  11119. // Test: Single-line data
  11120. TEST_F(SSEParsingTest, SingleLineData) {
  11121. sse::SSEMessage msg;
  11122. int retry_ms = 3000;
  11123. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11124. EXPECT_EQ(msg.data, "hello");
  11125. EXPECT_EQ(msg.event, "message");
  11126. // Blank line ends event
  11127. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11128. }
  11129. // Test: Multi-line data
  11130. TEST_F(SSEParsingTest, MultiLineData) {
  11131. sse::SSEMessage msg;
  11132. int retry_ms = 3000;
  11133. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11134. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11135. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11136. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11137. }
  11138. // Test: Custom event types
  11139. TEST_F(SSEParsingTest, CustomEventType) {
  11140. sse::SSEMessage msg;
  11141. int retry_ms = 3000;
  11142. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11143. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11144. EXPECT_EQ(msg.event, "update");
  11145. EXPECT_EQ(msg.data, "payload");
  11146. }
  11147. // Test: Event ID handling
  11148. TEST_F(SSEParsingTest, EventIdHandling) {
  11149. sse::SSEMessage msg;
  11150. int retry_ms = 3000;
  11151. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11152. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11153. EXPECT_EQ(msg.id, "12345");
  11154. }
  11155. // Test: Empty event ID (clears last event ID)
  11156. TEST_F(SSEParsingTest, EmptyEventId) {
  11157. sse::SSEMessage msg;
  11158. msg.id = "previous";
  11159. int retry_ms = 3000;
  11160. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11161. EXPECT_EQ(msg.id, "");
  11162. }
  11163. // Test: Retry field parsing
  11164. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11165. sse::SSEMessage msg;
  11166. int retry_ms = 3000;
  11167. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11168. EXPECT_EQ(retry_ms, 5000);
  11169. }
  11170. // Test: Invalid retry value
  11171. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11172. sse::SSEMessage msg;
  11173. int retry_ms = 3000;
  11174. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11175. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11176. }
  11177. // Test: Comments (lines starting with :)
  11178. TEST_F(SSEParsingTest, CommentsIgnored) {
  11179. sse::SSEMessage msg;
  11180. int retry_ms = 3000;
  11181. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11182. EXPECT_EQ(msg.data, "");
  11183. EXPECT_EQ(msg.event, "message");
  11184. }
  11185. // Test: Colon in value
  11186. TEST_F(SSEParsingTest, ColonInValue) {
  11187. sse::SSEMessage msg;
  11188. int retry_ms = 3000;
  11189. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11190. EXPECT_EQ(msg.data, "hello:world:test");
  11191. }
  11192. // Test: Line with no colon (field name only)
  11193. TEST_F(SSEParsingTest, FieldNameOnly) {
  11194. sse::SSEMessage msg;
  11195. int retry_ms = 3000;
  11196. // According to SSE spec, this is treated as field name with empty value
  11197. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11198. // Since we don't recognize "data" without colon, data should be empty
  11199. EXPECT_EQ(msg.data, "");
  11200. }
  11201. // Test: Trailing \r handling
  11202. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11203. sse::SSEMessage msg;
  11204. int retry_ms = 3000;
  11205. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11206. EXPECT_EQ(msg.data, "hello");
  11207. }
  11208. // Test: Unknown fields ignored
  11209. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11210. sse::SSEMessage msg;
  11211. int retry_ms = 3000;
  11212. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11213. EXPECT_EQ(msg.data, "");
  11214. EXPECT_EQ(msg.event, "message");
  11215. }
  11216. // Test: Space after colon is optional
  11217. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11218. sse::SSEMessage msg1, msg2;
  11219. int retry_ms = 3000;
  11220. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11221. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11222. EXPECT_EQ(msg1.data, "hello");
  11223. EXPECT_EQ(msg2.data, "hello");
  11224. }
  11225. // Test: SSEMessage clear
  11226. TEST_F(SSEParsingTest, MessageClear) {
  11227. sse::SSEMessage msg;
  11228. msg.event = "custom";
  11229. msg.data = "some data";
  11230. msg.id = "123";
  11231. msg.clear();
  11232. EXPECT_EQ(msg.event, "message");
  11233. EXPECT_EQ(msg.data, "");
  11234. EXPECT_EQ(msg.id, "");
  11235. }
  11236. // Test: Complete event parsing
  11237. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11238. sse::SSEMessage msg;
  11239. int retry_ms = 3000;
  11240. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11241. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11242. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11243. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11244. // Blank line ends event
  11245. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11246. EXPECT_EQ(msg.event, "notification");
  11247. EXPECT_EQ(msg.id, "evt-42");
  11248. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11249. EXPECT_EQ(retry_ms, 1000);
  11250. }
  11251. //==============================================================================
  11252. // Integration Tests with Server
  11253. //==============================================================================
  11254. class SSEIntegrationTest : public ::testing::Test {
  11255. protected:
  11256. void SetUp() override {
  11257. stop_server_.store(false);
  11258. events_.clear();
  11259. server_ = httplib::detail::make_unique<Server>();
  11260. setup_server();
  11261. start_server();
  11262. }
  11263. void TearDown() override {
  11264. stop_server_.store(true);
  11265. event_cv_.notify_all();
  11266. server_->stop();
  11267. if (server_thread_.joinable()) { server_thread_.join(); }
  11268. }
  11269. void setup_server() {
  11270. // Simple SSE endpoint
  11271. server_->Get("/events", [this](const Request &req, Response &res) {
  11272. auto last_id = req.get_header_value("Last-Event-ID");
  11273. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11274. res.set_chunked_content_provider(
  11275. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11276. std::unique_lock<std::mutex> lock(event_mutex_);
  11277. if (event_cv_.wait_for(
  11278. lock, std::chrono::milliseconds(200), [this] {
  11279. return !events_.empty() || stop_server_.load();
  11280. })) {
  11281. if (stop_server_.load()) { return false; }
  11282. if (!events_.empty()) {
  11283. std::string event = events_.front();
  11284. events_.erase(events_.begin());
  11285. sink.write(event.data(), event.size());
  11286. return true;
  11287. }
  11288. }
  11289. return !stop_server_.load();
  11290. });
  11291. });
  11292. // Endpoint that returns error
  11293. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11294. res.status = 500;
  11295. res.set_content("Internal Server Error", "text/plain");
  11296. });
  11297. // Endpoint for custom event types
  11298. server_->Get("/custom-events", [](const Request &, Response &res) {
  11299. res.set_chunked_content_provider(
  11300. "text/event-stream", [](size_t offset, DataSink &sink) {
  11301. if (offset == 0) {
  11302. std::string event = "event: update\ndata: updated\n\n"
  11303. "event: delete\ndata: deleted\n\n";
  11304. sink.write(event.data(), event.size());
  11305. }
  11306. return false; // End stream after sending
  11307. });
  11308. });
  11309. }
  11310. void start_server() {
  11311. port_ = server_->bind_to_any_port("localhost");
  11312. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11313. // Wait for server to start
  11314. while (!server_->is_running()) {
  11315. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11316. }
  11317. }
  11318. int get_port() const { return port_; }
  11319. void send_event(const std::string &event) {
  11320. std::lock_guard<std::mutex> lock(event_mutex_);
  11321. events_.push_back(event);
  11322. event_cv_.notify_all();
  11323. }
  11324. std::unique_ptr<Server> server_;
  11325. std::thread server_thread_;
  11326. std::mutex event_mutex_;
  11327. std::condition_variable event_cv_;
  11328. std::vector<std::string> events_;
  11329. std::atomic<bool> stop_server_{false};
  11330. std::string last_received_event_id_;
  11331. int port_ = 0;
  11332. };
  11333. // Test: Successful connection and on_open callback
  11334. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11335. // Add a simple endpoint that sends one event and closes
  11336. server_->Get("/simple-event", [](const Request &, Response &res) {
  11337. res.set_chunked_content_provider(
  11338. "text/event-stream", [](size_t offset, DataSink &sink) {
  11339. if (offset == 0) {
  11340. std::string event = "data: hello\n\n";
  11341. sink.write(event.data(), event.size());
  11342. }
  11343. return false; // Close stream after sending
  11344. });
  11345. });
  11346. Client client("localhost", get_port());
  11347. sse::SSEClient sse(client, "/simple-event");
  11348. std::atomic<bool> open_called{false};
  11349. std::atomic<bool> message_received{false};
  11350. sse.on_open([&open_called]() { open_called.store(true); });
  11351. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11352. if (msg.data == "hello") { message_received.store(true); }
  11353. });
  11354. sse.set_reconnect_interval(100);
  11355. sse.set_max_reconnect_attempts(1);
  11356. // Start async
  11357. sse.start_async();
  11358. // Wait for message to be processed
  11359. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11360. sse.stop();
  11361. EXPECT_TRUE(open_called.load());
  11362. EXPECT_TRUE(message_received.load());
  11363. }
  11364. // Test: on_message callback
  11365. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11366. // Endpoint that sends multiple events then closes
  11367. server_->Get("/multi-event", [](const Request &, Response &res) {
  11368. res.set_chunked_content_provider(
  11369. "text/event-stream", [](size_t offset, DataSink &sink) {
  11370. if (offset == 0) {
  11371. std::string events = "data: message1\n\ndata: message2\n\n";
  11372. sink.write(events.data(), events.size());
  11373. }
  11374. return false;
  11375. });
  11376. });
  11377. Client client("localhost", get_port());
  11378. sse::SSEClient sse(client, "/multi-event");
  11379. std::vector<std::string> received_messages;
  11380. std::mutex messages_mutex;
  11381. sse.on_message([&](const sse::SSEMessage &msg) {
  11382. std::lock_guard<std::mutex> lock(messages_mutex);
  11383. received_messages.push_back(msg.data);
  11384. });
  11385. sse.set_reconnect_interval(100);
  11386. sse.set_max_reconnect_attempts(1);
  11387. sse.start_async();
  11388. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11389. sse.stop();
  11390. std::lock_guard<std::mutex> lock(messages_mutex);
  11391. EXPECT_GE(received_messages.size(), 2u);
  11392. if (received_messages.size() >= 2) {
  11393. EXPECT_EQ(received_messages[0], "message1");
  11394. EXPECT_EQ(received_messages[1], "message2");
  11395. }
  11396. }
  11397. // Test: on_event for specific types
  11398. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11399. Client client("localhost", get_port());
  11400. sse::SSEClient sse(client, "/custom-events");
  11401. std::atomic<bool> update_received{false};
  11402. std::atomic<bool> delete_received{false};
  11403. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11404. if (msg.data == "updated") { update_received.store(true); }
  11405. });
  11406. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11407. if (msg.data == "deleted") { delete_received.store(true); }
  11408. });
  11409. sse.set_max_reconnect_attempts(1);
  11410. sse.start_async();
  11411. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11412. sse.stop();
  11413. EXPECT_TRUE(update_received.load());
  11414. EXPECT_TRUE(delete_received.load());
  11415. }
  11416. // Test: on_error callback on connection failure
  11417. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11418. // Connect to a non-existent port
  11419. Client client("localhost", 59999);
  11420. sse::SSEClient sse(client, "/events");
  11421. std::atomic<bool> error_called{false};
  11422. Error received_error = Error::Success;
  11423. sse.on_error([&](Error err) {
  11424. error_called.store(true);
  11425. received_error = err;
  11426. });
  11427. sse.set_reconnect_interval(50);
  11428. sse.set_max_reconnect_attempts(1);
  11429. sse.start_async();
  11430. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11431. sse.stop();
  11432. EXPECT_TRUE(error_called.load());
  11433. EXPECT_NE(received_error, Error::Success);
  11434. }
  11435. // Test: Last-Event-ID header sent on reconnect
  11436. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11437. // Endpoint that sends event with ID
  11438. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11439. res.set_chunked_content_provider(
  11440. "text/event-stream", [](size_t offset, DataSink &sink) {
  11441. if (offset == 0) {
  11442. std::string event = "id: evt-123\ndata: test\n\n";
  11443. sink.write(event.data(), event.size());
  11444. }
  11445. return false;
  11446. });
  11447. });
  11448. Client client("localhost", get_port());
  11449. sse::SSEClient sse(client, "/event-with-id");
  11450. std::atomic<bool> id_received{false};
  11451. sse.on_message([&](const sse::SSEMessage &msg) {
  11452. if (!msg.id.empty()) { id_received.store(true); }
  11453. });
  11454. sse.set_reconnect_interval(100);
  11455. sse.set_max_reconnect_attempts(1);
  11456. sse.start_async();
  11457. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11458. sse.stop();
  11459. EXPECT_TRUE(id_received.load());
  11460. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11461. }
  11462. // Test: Manual stop
  11463. TEST_F(SSEIntegrationTest, ManualStop) {
  11464. // Endpoint that sends one event and stays open briefly
  11465. std::atomic<bool> handler_running{true};
  11466. server_->Get("/stay-open", [&handler_running](const Request &,
  11467. Response &res) {
  11468. res.set_chunked_content_provider(
  11469. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11470. if (offset == 0) {
  11471. std::string event = "data: connected\n\n";
  11472. sink.write(event.data(), event.size());
  11473. }
  11474. // Keep connection open while handler_running is true
  11475. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11476. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11477. }
  11478. return false;
  11479. });
  11480. });
  11481. Client client("localhost", get_port());
  11482. sse::SSEClient sse(client, "/stay-open");
  11483. std::atomic<bool> connected{false};
  11484. sse.on_open([&connected]() { connected.store(true); });
  11485. sse.set_reconnect_interval(100);
  11486. sse.set_max_reconnect_attempts(1);
  11487. sse.start_async();
  11488. // Wait for connection to establish
  11489. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11490. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11491. }
  11492. EXPECT_TRUE(connected.load());
  11493. EXPECT_TRUE(sse.is_connected());
  11494. // Signal handler to stop
  11495. handler_running.store(false);
  11496. // Stop SSE client
  11497. sse.stop();
  11498. EXPECT_FALSE(sse.is_connected());
  11499. }
  11500. // Test: SSEClient with custom headers
  11501. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11502. // Setup a server endpoint that checks for custom header
  11503. std::atomic<bool> header_received{false};
  11504. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11505. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11506. header_received.store(true);
  11507. }
  11508. res.set_chunked_content_provider("text/event-stream",
  11509. [](size_t, DataSink &) { return false; });
  11510. });
  11511. Client client("localhost", get_port());
  11512. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11513. sse::SSEClient sse(client, "/header-check", headers);
  11514. sse.set_max_reconnect_attempts(1);
  11515. sse.start_async();
  11516. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11517. sse.stop();
  11518. EXPECT_TRUE(header_received.load());
  11519. }
  11520. // Test: Reconnect interval configuration
  11521. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11522. Client client("localhost", get_port());
  11523. sse::SSEClient sse(client, "/events");
  11524. auto &result = sse.set_reconnect_interval(500);
  11525. // Builder pattern should return reference to self
  11526. EXPECT_EQ(&result, &sse);
  11527. }
  11528. // Test: Max reconnect attempts
  11529. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11530. // Connect to non-existent port to force reconnects
  11531. Client client("localhost", 59998);
  11532. sse::SSEClient sse(client, "/events");
  11533. std::atomic<int> error_count{0};
  11534. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11535. sse.set_reconnect_interval(50);
  11536. sse.set_max_reconnect_attempts(2);
  11537. auto start = std::chrono::steady_clock::now();
  11538. sse.start(); // Blocking call
  11539. auto end = std::chrono::steady_clock::now();
  11540. // Should have stopped after 2 failed attempts
  11541. EXPECT_GE(error_count.load(), 2);
  11542. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11543. auto duration =
  11544. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11545. #ifdef _WIN32
  11546. // Windows is much slower for socket connection failures
  11547. EXPECT_LT(duration.count(), 7000);
  11548. #else
  11549. EXPECT_LT(duration.count(), 1000);
  11550. #endif
  11551. }
  11552. // Test: Multi-line data in integration
  11553. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11554. // Endpoint with multi-line data
  11555. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11556. res.set_chunked_content_provider(
  11557. "text/event-stream", [](size_t offset, DataSink &sink) {
  11558. if (offset == 0) {
  11559. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11560. sink.write(event.data(), event.size());
  11561. }
  11562. return false;
  11563. });
  11564. });
  11565. Client client("localhost", get_port());
  11566. sse::SSEClient sse(client, "/multiline-data");
  11567. std::string received_data;
  11568. std::mutex data_mutex;
  11569. sse.on_message([&](const sse::SSEMessage &msg) {
  11570. std::lock_guard<std::mutex> lock(data_mutex);
  11571. received_data = msg.data;
  11572. });
  11573. sse.set_reconnect_interval(100);
  11574. sse.set_max_reconnect_attempts(1);
  11575. sse.start_async();
  11576. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11577. sse.stop();
  11578. std::lock_guard<std::mutex> lock(data_mutex);
  11579. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11580. }
  11581. // Test: Auto-reconnect after server disconnection
  11582. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11583. std::atomic<int> connection_count{0};
  11584. std::atomic<int> message_count{0};
  11585. // Endpoint that sends one event and closes, forcing reconnect
  11586. server_->Get("/reconnect-test",
  11587. [&connection_count](const Request &, Response &res) {
  11588. connection_count.fetch_add(1);
  11589. res.set_chunked_content_provider(
  11590. "text/event-stream", [](size_t offset, DataSink &sink) {
  11591. if (offset == 0) {
  11592. std::string event = "data: hello\n\n";
  11593. sink.write(event.data(), event.size());
  11594. }
  11595. return false; // Close connection after sending
  11596. });
  11597. });
  11598. Client client("localhost", get_port());
  11599. sse::SSEClient sse(client, "/reconnect-test");
  11600. sse.on_message([&message_count](const sse::SSEMessage &) {
  11601. message_count.fetch_add(1);
  11602. });
  11603. sse.set_reconnect_interval(100);
  11604. sse.set_max_reconnect_attempts(3);
  11605. sse.start_async();
  11606. // Wait long enough for multiple reconnects
  11607. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11608. sse.stop();
  11609. // Should have connected multiple times (initial + reconnects)
  11610. EXPECT_GE(connection_count.load(), 2);
  11611. // Should have received messages from multiple connections
  11612. EXPECT_GE(message_count.load(), 2);
  11613. }
  11614. // Test: Last-Event-ID sent on reconnect
  11615. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11616. std::atomic<int> connection_count{0};
  11617. std::vector<std::string> received_last_event_ids;
  11618. std::mutex id_mutex;
  11619. // Endpoint that checks Last-Event-ID header and sends event with ID
  11620. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11621. int conn = connection_count.fetch_add(1);
  11622. // Capture the Last-Event-ID header from each connection
  11623. {
  11624. std::lock_guard<std::mutex> lock(id_mutex);
  11625. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11626. }
  11627. res.set_chunked_content_provider(
  11628. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11629. if (offset == 0) {
  11630. std::string event =
  11631. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11632. sink.write(event.data(), event.size());
  11633. }
  11634. return false;
  11635. });
  11636. });
  11637. Client client("localhost", get_port());
  11638. sse::SSEClient sse(client, "/reconnect-with-id");
  11639. sse.set_reconnect_interval(100);
  11640. sse.set_max_reconnect_attempts(3);
  11641. sse.start_async();
  11642. // Wait for at least 2 connections
  11643. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11644. sse.stop();
  11645. // Verify behavior
  11646. std::lock_guard<std::mutex> lock(id_mutex);
  11647. EXPECT_GE(received_last_event_ids.size(), 2u);
  11648. // First connection should have no Last-Event-ID
  11649. if (!received_last_event_ids.empty()) {
  11650. EXPECT_EQ(received_last_event_ids[0], "");
  11651. }
  11652. // Second connection should have Last-Event-ID from first connection
  11653. if (received_last_event_ids.size() >= 2) {
  11654. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11655. }
  11656. }