test.cc 228 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <limits>
  8. #include <memory>
  9. #include <sstream>
  10. #include <stdexcept>
  11. #include <thread>
  12. #include <type_traits>
  13. #define SERVER_CERT_FILE "./cert.pem"
  14. #define SERVER_CERT2_FILE "./cert2.pem"
  15. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  16. #define CA_CERT_FILE "./ca-bundle.crt"
  17. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  18. #define CLIENT_CA_CERT_DIR "."
  19. #define CLIENT_CERT_FILE "./client.cert.pem"
  20. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  21. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  22. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  23. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  24. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  25. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  26. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  27. using namespace std;
  28. using namespace httplib;
  29. const char *HOST = "localhost";
  30. const int PORT = 1234;
  31. const string LONG_QUERY_VALUE = string(25000, '@');
  32. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  33. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  34. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  35. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  36. const char *key) {
  37. auto it = std::find_if(
  38. files.begin(), files.end(),
  39. [&](const MultipartFormData &file) { return file.name == key; });
  40. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  41. return *it;
  42. #else
  43. if (it != files.end()) { return *it; }
  44. throw std::runtime_error("invalid multipart form data name error");
  45. #endif
  46. }
  47. #ifndef _WIN32
  48. class UnixSocketTest : public ::testing::Test {
  49. protected:
  50. void TearDown() override { std::remove(pathname_.c_str()); }
  51. void client_GET(const std::string &addr) {
  52. httplib::Client cli{addr};
  53. cli.set_address_family(AF_UNIX);
  54. ASSERT_TRUE(cli.is_valid());
  55. const auto &result = cli.Get(pattern_);
  56. ASSERT_TRUE(result) << "error: " << result.error();
  57. const auto &resp = result.value();
  58. EXPECT_EQ(resp.status, StatusCode::OK_200);
  59. EXPECT_EQ(resp.body, content_);
  60. }
  61. const std::string pathname_{"./httplib-server.sock"};
  62. const std::string pattern_{"/hi"};
  63. const std::string content_{"Hello World!"};
  64. };
  65. TEST_F(UnixSocketTest, pathname) {
  66. httplib::Server svr;
  67. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  68. res.set_content(content_, "text/plain");
  69. });
  70. std::thread t{[&] {
  71. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  72. }};
  73. auto se = detail::scope_exit([&] {
  74. svr.stop();
  75. t.join();
  76. ASSERT_FALSE(svr.is_running());
  77. });
  78. svr.wait_until_ready();
  79. ASSERT_TRUE(svr.is_running());
  80. client_GET(pathname_);
  81. }
  82. #if defined(__linux__) || \
  83. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  84. TEST_F(UnixSocketTest, PeerPid) {
  85. httplib::Server svr;
  86. std::string remote_port_val;
  87. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. remote_port_val = req.get_header_value("REMOTE_PORT");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  103. }
  104. #endif
  105. #ifdef __linux__
  106. TEST_F(UnixSocketTest, abstract) {
  107. constexpr char svr_path[]{"\x00httplib-server.sock"};
  108. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  109. httplib::Server svr;
  110. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  111. res.set_content(content_, "text/plain");
  112. });
  113. std::thread t{[&] {
  114. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  115. }};
  116. auto se = detail::scope_exit([&] {
  117. svr.stop();
  118. t.join();
  119. ASSERT_FALSE(svr.is_running());
  120. });
  121. svr.wait_until_ready();
  122. ASSERT_TRUE(svr.is_running());
  123. client_GET(abstract_addr);
  124. }
  125. #endif
  126. TEST(SocketStream, is_writable_UNIX) {
  127. int fds[2];
  128. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  129. const auto asSocketStream = [&](socket_t fd,
  130. std::function<bool(Stream &)> func) {
  131. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  132. };
  133. asSocketStream(fds[0], [&](Stream &s0) {
  134. EXPECT_EQ(s0.socket(), fds[0]);
  135. EXPECT_TRUE(s0.is_writable());
  136. EXPECT_EQ(0, close(fds[1]));
  137. EXPECT_FALSE(s0.is_writable());
  138. return true;
  139. });
  140. EXPECT_EQ(0, close(fds[0]));
  141. }
  142. TEST(SocketStream, is_writable_INET) {
  143. sockaddr_in addr;
  144. memset(&addr, 0, sizeof(addr));
  145. addr.sin_family = AF_INET;
  146. addr.sin_port = htons(PORT + 1);
  147. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  148. int disconnected_svr_sock = -1;
  149. std::thread svr{[&] {
  150. const int s = socket(AF_INET, SOCK_STREAM, 0);
  151. ASSERT_LE(0, s);
  152. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  153. ASSERT_EQ(0, listen(s, 1));
  154. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  155. ASSERT_EQ(0, close(s));
  156. }};
  157. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  158. std::thread cli{[&] {
  159. const int s = socket(AF_INET, SOCK_STREAM, 0);
  160. ASSERT_LE(0, s);
  161. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  162. ASSERT_EQ(0, close(s));
  163. }};
  164. cli.join();
  165. svr.join();
  166. ASSERT_NE(disconnected_svr_sock, -1);
  167. const auto asSocketStream = [&](socket_t fd,
  168. std::function<bool(Stream &)> func) {
  169. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  170. };
  171. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  172. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  173. EXPECT_FALSE(ss.is_writable());
  174. return true;
  175. });
  176. ASSERT_EQ(0, close(disconnected_svr_sock));
  177. }
  178. #endif // #ifndef _WIN32
  179. TEST(ClientTest, MoveConstructible) {
  180. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  181. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  182. }
  183. TEST(ClientTest, MoveAssignable) {
  184. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  185. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  186. }
  187. #ifdef _WIN32
  188. TEST(StartupTest, WSAStartup) {
  189. WSADATA wsaData;
  190. int ret = WSAStartup(0x0002, &wsaData);
  191. ASSERT_EQ(0, ret);
  192. }
  193. #endif
  194. TEST(DecodeURLTest, PercentCharacter) {
  195. EXPECT_EQ(
  196. detail::decode_url(
  197. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  198. false),
  199. R"(descrip=Gastos áéíóúñÑ 6)");
  200. }
  201. TEST(DecodeURLTest, PercentCharacterNUL) {
  202. string expected;
  203. expected.push_back('x');
  204. expected.push_back('\0');
  205. expected.push_back('x');
  206. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  207. }
  208. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  209. string unescapedCharacters = "-_.!~*'()";
  210. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  211. }
  212. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  213. string reservedCharacters = ";,/?:@&=+$";
  214. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  215. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  216. }
  217. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  218. string chineseCharacters = "中国語";
  219. string russianCharacters = "дом";
  220. string brazilianCharacters = "óculos";
  221. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  222. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  223. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  224. "%D0%B4%D0%BE%D0%BC");
  225. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  226. }
  227. TEST(TrimTests, TrimStringTests) {
  228. EXPECT_EQ("abc", detail::trim_copy("abc"));
  229. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  230. EXPECT_TRUE(detail::trim_copy("").empty());
  231. }
  232. TEST(DivideTest, DivideStringTests) {
  233. auto divide = [](const std::string &str, char d) {
  234. std::string lhs;
  235. std::string rhs;
  236. detail::divide(str, d,
  237. [&](const char *lhs_data, std::size_t lhs_size,
  238. const char *rhs_data, std::size_t rhs_size) {
  239. lhs.assign(lhs_data, lhs_size);
  240. rhs.assign(rhs_data, rhs_size);
  241. });
  242. return std::make_pair(std::move(lhs), std::move(rhs));
  243. };
  244. {
  245. const auto res = divide("", '=');
  246. EXPECT_EQ(res.first, "");
  247. EXPECT_EQ(res.second, "");
  248. }
  249. {
  250. const auto res = divide("=", '=');
  251. EXPECT_EQ(res.first, "");
  252. EXPECT_EQ(res.second, "");
  253. }
  254. {
  255. const auto res = divide(" ", '=');
  256. EXPECT_EQ(res.first, " ");
  257. EXPECT_EQ(res.second, "");
  258. }
  259. {
  260. const auto res = divide("a", '=');
  261. EXPECT_EQ(res.first, "a");
  262. EXPECT_EQ(res.second, "");
  263. }
  264. {
  265. const auto res = divide("a=", '=');
  266. EXPECT_EQ(res.first, "a");
  267. EXPECT_EQ(res.second, "");
  268. }
  269. {
  270. const auto res = divide("=b", '=');
  271. EXPECT_EQ(res.first, "");
  272. EXPECT_EQ(res.second, "b");
  273. }
  274. {
  275. const auto res = divide("a=b", '=');
  276. EXPECT_EQ(res.first, "a");
  277. EXPECT_EQ(res.second, "b");
  278. }
  279. {
  280. const auto res = divide("a=b=", '=');
  281. EXPECT_EQ(res.first, "a");
  282. EXPECT_EQ(res.second, "b=");
  283. }
  284. {
  285. const auto res = divide("a=b=c", '=');
  286. EXPECT_EQ(res.first, "a");
  287. EXPECT_EQ(res.second, "b=c");
  288. }
  289. }
  290. TEST(SplitTest, ParseQueryString) {
  291. string s = "key1=val1&key2=val2&key3=val3";
  292. Params dic;
  293. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  294. [&](const char *b, const char *e) {
  295. string key, val;
  296. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  297. if (key.empty()) {
  298. key.assign(b2, e2);
  299. } else {
  300. val.assign(b2, e2);
  301. }
  302. });
  303. dic.emplace(key, val);
  304. });
  305. EXPECT_EQ("val1", dic.find("key1")->second);
  306. EXPECT_EQ("val2", dic.find("key2")->second);
  307. EXPECT_EQ("val3", dic.find("key3")->second);
  308. }
  309. TEST(SplitTest, ParseInvalidQueryTests) {
  310. {
  311. string s = " ";
  312. Params dict;
  313. detail::parse_query_text(s, dict);
  314. EXPECT_TRUE(dict.empty());
  315. }
  316. {
  317. string s = " = =";
  318. Params dict;
  319. detail::parse_query_text(s, dict);
  320. EXPECT_TRUE(dict.empty());
  321. }
  322. }
  323. TEST(ParseQueryTest, ParseQueryString) {
  324. {
  325. std::string s = "key1=val1&key2=val2&key3=val3";
  326. Params dic;
  327. detail::parse_query_text(s, dic);
  328. EXPECT_EQ("val1", dic.find("key1")->second);
  329. EXPECT_EQ("val2", dic.find("key2")->second);
  330. EXPECT_EQ("val3", dic.find("key3")->second);
  331. }
  332. {
  333. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  334. Params dic;
  335. detail::parse_query_text(s, dic);
  336. EXPECT_EQ("", dic.find("key1")->second);
  337. EXPECT_EQ("val1", dic.find("key2")->second);
  338. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  339. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  340. }
  341. }
  342. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  343. Params dic;
  344. EXPECT_EQ(detail::params_to_query_str(dic), "");
  345. dic.emplace("key1", "val1");
  346. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  347. dic.emplace("key2", "val2");
  348. dic.emplace("key3", "val3");
  349. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  350. }
  351. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  352. string content_type = "multipart/form-data; boundary=something";
  353. string boundary;
  354. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  355. EXPECT_TRUE(ret);
  356. EXPECT_EQ(boundary, "something");
  357. }
  358. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  359. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  360. string boundary;
  361. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  362. EXPECT_TRUE(ret);
  363. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  364. }
  365. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  366. string content_type =
  367. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  368. string boundary;
  369. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  370. EXPECT_TRUE(ret);
  371. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  372. }
  373. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  374. string content_type =
  375. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  376. string boundary;
  377. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  378. EXPECT_TRUE(ret);
  379. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  380. }
  381. TEST(GetHeaderValueTest, DefaultValue) {
  382. Headers headers = {{"Dummy", "Dummy"}};
  383. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  384. EXPECT_STREQ("text/plain", val);
  385. }
  386. TEST(GetHeaderValueTest, DefaultValueInt) {
  387. Headers headers = {{"Dummy", "Dummy"}};
  388. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  389. EXPECT_EQ(100ull, val);
  390. }
  391. TEST(GetHeaderValueTest, RegularValue) {
  392. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  393. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  394. EXPECT_STREQ("text/html", val);
  395. }
  396. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  397. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  398. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  399. EXPECT_STREQ("text/html", val);
  400. }
  401. TEST(GetHeaderValueTest, SetContent) {
  402. Response res;
  403. res.set_content("html", "text/html");
  404. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  405. res.set_content("text", "text/plain");
  406. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  407. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  408. }
  409. TEST(GetHeaderValueTest, RegularValueInt) {
  410. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  411. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  412. EXPECT_EQ(100ull, val);
  413. }
  414. TEST(GetHeaderValueTest, Range) {
  415. {
  416. Headers headers = {make_range_header({{1, -1}})};
  417. auto val = detail::get_header_value(headers, "Range", 0, 0);
  418. EXPECT_STREQ("bytes=1-", val);
  419. }
  420. {
  421. Headers headers = {make_range_header({{-1, 1}})};
  422. auto val = detail::get_header_value(headers, "Range", 0, 0);
  423. EXPECT_STREQ("bytes=-1", val);
  424. }
  425. {
  426. Headers headers = {make_range_header({{1, 10}})};
  427. auto val = detail::get_header_value(headers, "Range", 0, 0);
  428. EXPECT_STREQ("bytes=1-10", val);
  429. }
  430. {
  431. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  432. auto val = detail::get_header_value(headers, "Range", 0, 0);
  433. EXPECT_STREQ("bytes=1-10, 100-", val);
  434. }
  435. {
  436. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  437. auto val = detail::get_header_value(headers, "Range", 0, 0);
  438. EXPECT_STREQ("bytes=1-10, 100-200", val);
  439. }
  440. {
  441. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  442. auto val = detail::get_header_value(headers, "Range", 0, 0);
  443. EXPECT_STREQ("bytes=0-0, -1", val);
  444. }
  445. }
  446. TEST(ParseHeaderValueTest, Range) {
  447. {
  448. Ranges ranges;
  449. auto ret = detail::parse_range_header("bytes=1-", ranges);
  450. EXPECT_TRUE(ret);
  451. EXPECT_EQ(1u, ranges.size());
  452. EXPECT_EQ(1u, ranges[0].first);
  453. EXPECT_EQ(-1, ranges[0].second);
  454. }
  455. {
  456. Ranges ranges;
  457. auto ret = detail::parse_range_header("bytes=-1", ranges);
  458. EXPECT_TRUE(ret);
  459. EXPECT_EQ(1u, ranges.size());
  460. EXPECT_EQ(-1, ranges[0].first);
  461. EXPECT_EQ(1u, ranges[0].second);
  462. }
  463. {
  464. Ranges ranges;
  465. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  466. EXPECT_TRUE(ret);
  467. EXPECT_EQ(1u, ranges.size());
  468. EXPECT_EQ(1u, ranges[0].first);
  469. EXPECT_EQ(10u, ranges[0].second);
  470. }
  471. {
  472. Ranges ranges;
  473. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  474. EXPECT_FALSE(ret);
  475. }
  476. {
  477. Ranges ranges;
  478. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  479. EXPECT_TRUE(ret);
  480. EXPECT_EQ(2u, ranges.size());
  481. EXPECT_EQ(1u, ranges[0].first);
  482. EXPECT_EQ(10u, ranges[0].second);
  483. EXPECT_EQ(100u, ranges[1].first);
  484. EXPECT_EQ(-1, ranges[1].second);
  485. }
  486. {
  487. Ranges ranges;
  488. auto ret =
  489. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  490. EXPECT_TRUE(ret);
  491. EXPECT_EQ(3u, ranges.size());
  492. EXPECT_EQ(1u, ranges[0].first);
  493. EXPECT_EQ(10u, ranges[0].second);
  494. EXPECT_EQ(100u, ranges[1].first);
  495. EXPECT_EQ(200u, ranges[1].second);
  496. EXPECT_EQ(300u, ranges[2].first);
  497. EXPECT_EQ(400u, ranges[2].second);
  498. }
  499. {
  500. Ranges ranges;
  501. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  502. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  503. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  504. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  505. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  506. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  507. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  508. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  509. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  510. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  511. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  512. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  513. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  514. EXPECT_TRUE(ranges.empty());
  515. }
  516. }
  517. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  518. Request req;
  519. req.set_header("Accept-Encoding", "gzip");
  520. Response res;
  521. res.set_header("Content-Type", "text/plain");
  522. auto ret = detail::encoding_type(req, res);
  523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  524. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  525. #else
  526. EXPECT_TRUE(ret == detail::EncodingType::None);
  527. #endif
  528. }
  529. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  530. Request req;
  531. req.set_header("Accept-Encoding", "gzip, deflate, br");
  532. Response res;
  533. res.set_header("Content-Type", "text/plain");
  534. auto ret = detail::encoding_type(req, res);
  535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  536. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  537. #elif CPPHTTPLIB_ZLIB_SUPPORT
  538. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  539. #else
  540. EXPECT_TRUE(ret == detail::EncodingType::None);
  541. #endif
  542. }
  543. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  544. Request req;
  545. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  546. Response res;
  547. res.set_header("Content-Type", "text/plain");
  548. auto ret = detail::encoding_type(req, res);
  549. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  550. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  551. #elif CPPHTTPLIB_ZLIB_SUPPORT
  552. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  553. #else
  554. EXPECT_TRUE(ret == detail::EncodingType::None);
  555. #endif
  556. }
  557. TEST(BufferStreamTest, read) {
  558. detail::BufferStream strm1;
  559. Stream &strm = strm1;
  560. EXPECT_EQ(5, strm.write("hello"));
  561. char buf[512];
  562. EXPECT_EQ(2, strm.read(buf, 2));
  563. EXPECT_EQ('h', buf[0]);
  564. EXPECT_EQ('e', buf[1]);
  565. EXPECT_EQ(2, strm.read(buf, 2));
  566. EXPECT_EQ('l', buf[0]);
  567. EXPECT_EQ('l', buf[1]);
  568. EXPECT_EQ(1, strm.read(buf, 1));
  569. EXPECT_EQ('o', buf[0]);
  570. EXPECT_EQ(0, strm.read(buf, 1));
  571. }
  572. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  573. auto host = "www.httpwatch.com";
  574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  575. auto port = 443;
  576. SSLClient cli(host, port);
  577. #else
  578. auto port = 80;
  579. Client cli(host, port);
  580. #endif
  581. cli.set_connection_timeout(2);
  582. auto res =
  583. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  584. ASSERT_TRUE(res);
  585. std::string out;
  586. detail::read_file("./image.jpg", out);
  587. EXPECT_EQ(StatusCode::OK_200, res->status);
  588. EXPECT_EQ(out, res->body);
  589. }
  590. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  591. auto host = "www.httpwatch.com";
  592. auto ip = hosted_at(host);
  593. EXPECT_EQ("23.96.13.243", ip);
  594. std::vector<std::string> addrs;
  595. hosted_at(host, addrs);
  596. EXPECT_EQ(1u, addrs.size());
  597. }
  598. #if 0 // It depends on each test environment...
  599. TEST(HostnameToIPConversionTest, YouTube_Online) {
  600. auto host = "www.youtube.com";
  601. std::vector<std::string> addrs;
  602. hosted_at(host, addrs);
  603. EXPECT_EQ(20u, addrs.size());
  604. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  605. EXPECT_TRUE(it != addrs.end());
  606. }
  607. #endif
  608. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  609. auto host = "www.httpwatch.com";
  610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  611. auto port = 443;
  612. SSLClient cli(host, port);
  613. #else
  614. auto port = 80;
  615. Client cli(host, port);
  616. #endif
  617. cli.set_connection_timeout(2);
  618. std::string body;
  619. auto res =
  620. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  621. [&](const char *data, size_t data_length) {
  622. body.append(data, data_length);
  623. return true;
  624. });
  625. ASSERT_TRUE(res);
  626. std::string out;
  627. detail::read_file("./image.jpg", out);
  628. EXPECT_EQ(StatusCode::OK_200, res->status);
  629. EXPECT_EQ(out, body);
  630. }
  631. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  632. auto host = "www.httpwatch.com";
  633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  634. auto port = 443;
  635. SSLClient cli(host, port);
  636. #else
  637. auto port = 80;
  638. Client cli(host, port);
  639. #endif
  640. cli.set_connection_timeout(2);
  641. std::string body;
  642. auto res = cli.Get(
  643. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  644. [&](const Response &response) {
  645. EXPECT_EQ(StatusCode::OK_200, response.status);
  646. return true;
  647. },
  648. [&](const char *data, size_t data_length) {
  649. body.append(data, data_length);
  650. return true;
  651. });
  652. ASSERT_TRUE(res);
  653. std::string out;
  654. detail::read_file("./image.jpg", out);
  655. EXPECT_EQ(StatusCode::OK_200, res->status);
  656. EXPECT_EQ(out, body);
  657. }
  658. TEST(RangeTest, FromHTTPBin_Online) {
  659. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  660. auto host = "httpbin.org";
  661. auto path = std::string{"/range/32"};
  662. #else
  663. auto host = "nghttp2.org";
  664. auto path = std::string{"/httpbin/range/32"};
  665. #endif
  666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  667. auto port = 443;
  668. SSLClient cli(host, port);
  669. #else
  670. auto port = 80;
  671. Client cli(host, port);
  672. #endif
  673. cli.set_connection_timeout(5);
  674. {
  675. auto res = cli.Get(path);
  676. ASSERT_TRUE(res);
  677. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  678. EXPECT_EQ(StatusCode::OK_200, res->status);
  679. }
  680. {
  681. Headers headers = {make_range_header({{1, -1}})};
  682. auto res = cli.Get(path, headers);
  683. ASSERT_TRUE(res);
  684. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  686. }
  687. {
  688. Headers headers = {make_range_header({{1, 10}})};
  689. auto res = cli.Get(path, headers);
  690. ASSERT_TRUE(res);
  691. EXPECT_EQ("bcdefghijk", res->body);
  692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  693. }
  694. {
  695. Headers headers = {make_range_header({{0, 31}})};
  696. auto res = cli.Get(path, headers);
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  699. EXPECT_EQ(StatusCode::OK_200, res->status);
  700. }
  701. {
  702. Headers headers = {make_range_header({{0, -1}})};
  703. auto res = cli.Get(path, headers);
  704. ASSERT_TRUE(res);
  705. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  706. EXPECT_EQ(StatusCode::OK_200, res->status);
  707. }
  708. {
  709. Headers headers = {make_range_header({{0, 32}})};
  710. auto res = cli.Get(path, headers);
  711. ASSERT_TRUE(res);
  712. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  713. }
  714. }
  715. TEST(ConnectionErrorTest, InvalidHost) {
  716. auto host = "-abcde.com";
  717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  718. auto port = 443;
  719. SSLClient cli(host, port);
  720. #else
  721. auto port = 80;
  722. Client cli(host, port);
  723. #endif
  724. cli.set_connection_timeout(std::chrono::seconds(2));
  725. auto res = cli.Get("/");
  726. ASSERT_TRUE(!res);
  727. EXPECT_EQ(Error::Connection, res.error());
  728. }
  729. TEST(ConnectionErrorTest, InvalidHost2) {
  730. auto host = "httpbin.org/";
  731. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  732. SSLClient cli(host);
  733. #else
  734. Client cli(host);
  735. #endif
  736. cli.set_connection_timeout(std::chrono::seconds(2));
  737. auto res = cli.Get("/");
  738. ASSERT_TRUE(!res);
  739. EXPECT_EQ(Error::Connection, res.error());
  740. }
  741. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  742. auto host = "httpbin.org/";
  743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  744. SSLClient cli(host);
  745. #else
  746. Client cli(host);
  747. #endif
  748. cli.set_connection_timeout(std::chrono::seconds(2));
  749. auto res = cli.Get("/");
  750. ASSERT_TRUE(!res);
  751. stringstream s;
  752. s << "error code: " << res.error();
  753. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  754. }
  755. TEST(ConnectionErrorTest, InvalidPort) {
  756. auto host = "localhost";
  757. auto port = 44380;
  758. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  759. SSLClient cli(host, port);
  760. #else
  761. Client cli(host, port);
  762. #endif
  763. cli.set_connection_timeout(std::chrono::seconds(2));
  764. auto res = cli.Get("/");
  765. ASSERT_TRUE(!res);
  766. EXPECT_TRUE(Error::Connection == res.error() ||
  767. Error::ConnectionTimeout == res.error());
  768. }
  769. TEST(ConnectionErrorTest, Timeout_Online) {
  770. auto host = "google.com";
  771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  772. auto port = 44380;
  773. SSLClient cli(host, port);
  774. #else
  775. auto port = 8080;
  776. Client cli(host, port);
  777. #endif
  778. cli.set_connection_timeout(std::chrono::seconds(2));
  779. // only probe one address type so that the error reason
  780. // correlates to the timed-out IPv4, not the unsupported
  781. // IPv6 connection attempt
  782. cli.set_address_family(AF_INET);
  783. auto res = cli.Get("/");
  784. ASSERT_TRUE(!res);
  785. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  786. }
  787. TEST(CancelTest, NoCancel_Online) {
  788. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  789. auto host = "httpbin.org";
  790. auto path = std::string{"/range/32"};
  791. #else
  792. auto host = "nghttp2.org";
  793. auto path = std::string{"/httpbin/range/32"};
  794. #endif
  795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  796. auto port = 443;
  797. SSLClient cli(host, port);
  798. #else
  799. auto port = 80;
  800. Client cli(host, port);
  801. #endif
  802. cli.set_connection_timeout(std::chrono::seconds(5));
  803. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  804. ASSERT_TRUE(res);
  805. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  806. EXPECT_EQ(StatusCode::OK_200, res->status);
  807. }
  808. TEST(CancelTest, WithCancelSmallPayload_Online) {
  809. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  810. auto host = "httpbin.org";
  811. auto path = std::string{"/range/32"};
  812. #else
  813. auto host = "nghttp2.org";
  814. auto path = std::string{"/httpbin/range/32"};
  815. #endif
  816. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  817. auto port = 443;
  818. SSLClient cli(host, port);
  819. #else
  820. auto port = 80;
  821. Client cli(host, port);
  822. #endif
  823. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  824. cli.set_connection_timeout(std::chrono::seconds(5));
  825. ASSERT_TRUE(!res);
  826. EXPECT_EQ(Error::Canceled, res.error());
  827. }
  828. TEST(CancelTest, WithCancelLargePayload_Online) {
  829. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  830. auto host = "httpbin.org";
  831. auto path = std::string{"/range/65536"};
  832. #else
  833. auto host = "nghttp2.org";
  834. auto path = std::string{"/httpbin/range/65536"};
  835. #endif
  836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  837. auto port = 443;
  838. SSLClient cli(host, port);
  839. #else
  840. auto port = 80;
  841. Client cli(host, port);
  842. #endif
  843. cli.set_connection_timeout(std::chrono::seconds(5));
  844. uint32_t count = 0;
  845. auto res =
  846. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  847. ASSERT_TRUE(!res);
  848. EXPECT_EQ(Error::Canceled, res.error());
  849. }
  850. TEST(CancelTest, NoCancelPost) {
  851. Server svr;
  852. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  853. res.set_content("Hello World!", "text/plain");
  854. });
  855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  856. auto se = detail::scope_exit([&] {
  857. svr.stop();
  858. thread.join();
  859. ASSERT_FALSE(svr.is_running());
  860. });
  861. svr.wait_until_ready();
  862. Client cli(HOST, PORT);
  863. cli.set_connection_timeout(std::chrono::seconds(5));
  864. auto res =
  865. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  866. "application/json", [](uint64_t, uint64_t) { return true; });
  867. ASSERT_TRUE(res);
  868. EXPECT_EQ("Hello World!", res->body);
  869. EXPECT_EQ(StatusCode::OK_200, res->status);
  870. }
  871. TEST(CancelTest, WithCancelSmallPayloadPost) {
  872. Server svr;
  873. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  874. res.set_content("Hello World!", "text/plain");
  875. });
  876. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  877. auto se = detail::scope_exit([&] {
  878. svr.stop();
  879. thread.join();
  880. ASSERT_FALSE(svr.is_running());
  881. });
  882. svr.wait_until_ready();
  883. Client cli(HOST, PORT);
  884. cli.set_connection_timeout(std::chrono::seconds(5));
  885. auto res =
  886. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  887. "application/json", [](uint64_t, uint64_t) { return false; });
  888. ASSERT_TRUE(!res);
  889. EXPECT_EQ(Error::Canceled, res.error());
  890. }
  891. TEST(CancelTest, WithCancelLargePayloadPost) {
  892. Server svr;
  893. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  894. res.set_content(LARGE_DATA, "text/plain");
  895. });
  896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  897. auto se = detail::scope_exit([&] {
  898. svr.stop();
  899. thread.join();
  900. ASSERT_FALSE(svr.is_running());
  901. });
  902. svr.wait_until_ready();
  903. Client cli(HOST, PORT);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res =
  906. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  907. "application/json", [](uint64_t, uint64_t) { return false; });
  908. ASSERT_TRUE(!res);
  909. EXPECT_EQ(Error::Canceled, res.error());
  910. }
  911. TEST(CancelTest, NoCancelPut) {
  912. Server svr;
  913. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  914. res.set_content("Hello World!", "text/plain");
  915. });
  916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  917. auto se = detail::scope_exit([&] {
  918. svr.stop();
  919. thread.join();
  920. ASSERT_FALSE(svr.is_running());
  921. });
  922. svr.wait_until_ready();
  923. Client cli(HOST, PORT);
  924. cli.set_connection_timeout(std::chrono::seconds(5));
  925. auto res =
  926. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  927. "application/json", [](uint64_t, uint64_t) { return true; });
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ("Hello World!", res->body);
  930. EXPECT_EQ(StatusCode::OK_200, res->status);
  931. }
  932. TEST(CancelTest, WithCancelSmallPayloadPut) {
  933. Server svr;
  934. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  935. res.set_content("Hello World!", "text/plain");
  936. });
  937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  938. auto se = detail::scope_exit([&] {
  939. svr.stop();
  940. thread.join();
  941. ASSERT_FALSE(svr.is_running());
  942. });
  943. svr.wait_until_ready();
  944. Client cli(HOST, PORT);
  945. cli.set_connection_timeout(std::chrono::seconds(5));
  946. auto res =
  947. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  948. "application/json", [](uint64_t, uint64_t) { return false; });
  949. ASSERT_TRUE(!res);
  950. EXPECT_EQ(Error::Canceled, res.error());
  951. }
  952. TEST(CancelTest, WithCancelLargePayloadPut) {
  953. Server svr;
  954. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  955. res.set_content(LARGE_DATA, "text/plain");
  956. });
  957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  958. auto se = detail::scope_exit([&] {
  959. svr.stop();
  960. thread.join();
  961. ASSERT_FALSE(svr.is_running());
  962. });
  963. svr.wait_until_ready();
  964. Client cli(HOST, PORT);
  965. cli.set_connection_timeout(std::chrono::seconds(5));
  966. auto res =
  967. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  968. "application/json", [](uint64_t, uint64_t) { return false; });
  969. ASSERT_TRUE(!res);
  970. EXPECT_EQ(Error::Canceled, res.error());
  971. }
  972. TEST(CancelTest, NoCancelPatch) {
  973. Server svr;
  974. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  975. res.set_content("Hello World!", "text/plain");
  976. });
  977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  978. auto se = detail::scope_exit([&] {
  979. svr.stop();
  980. thread.join();
  981. ASSERT_FALSE(svr.is_running());
  982. });
  983. svr.wait_until_ready();
  984. Client cli(HOST, PORT);
  985. cli.set_connection_timeout(std::chrono::seconds(5));
  986. auto res =
  987. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  988. "application/json", [](uint64_t, uint64_t) { return true; });
  989. ASSERT_TRUE(res);
  990. EXPECT_EQ("Hello World!", res->body);
  991. EXPECT_EQ(StatusCode::OK_200, res->status);
  992. }
  993. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  994. Server svr;
  995. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  996. res.set_content("Hello World!", "text/plain");
  997. });
  998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  999. auto se = detail::scope_exit([&] {
  1000. svr.stop();
  1001. thread.join();
  1002. ASSERT_FALSE(svr.is_running());
  1003. });
  1004. svr.wait_until_ready();
  1005. Client cli(HOST, PORT);
  1006. cli.set_connection_timeout(std::chrono::seconds(5));
  1007. auto res =
  1008. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1009. "application/json", [](uint64_t, uint64_t) { return false; });
  1010. ASSERT_TRUE(!res);
  1011. EXPECT_EQ(Error::Canceled, res.error());
  1012. }
  1013. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1014. Server svr;
  1015. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1016. res.set_content(LARGE_DATA, "text/plain");
  1017. });
  1018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1019. auto se = detail::scope_exit([&] {
  1020. svr.stop();
  1021. thread.join();
  1022. ASSERT_FALSE(svr.is_running());
  1023. });
  1024. svr.wait_until_ready();
  1025. Client cli(HOST, PORT);
  1026. cli.set_connection_timeout(std::chrono::seconds(5));
  1027. auto res =
  1028. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1029. "application/json", [](uint64_t, uint64_t) { return false; });
  1030. ASSERT_TRUE(!res);
  1031. EXPECT_EQ(Error::Canceled, res.error());
  1032. }
  1033. TEST(CancelTest, NoCancelDelete) {
  1034. Server svr;
  1035. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1036. res.set_content("Hello World!", "text/plain");
  1037. });
  1038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1039. auto se = detail::scope_exit([&] {
  1040. svr.stop();
  1041. thread.join();
  1042. ASSERT_FALSE(svr.is_running());
  1043. });
  1044. svr.wait_until_ready();
  1045. Client cli(HOST, PORT);
  1046. cli.set_connection_timeout(std::chrono::seconds(5));
  1047. auto res =
  1048. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1049. "application/json", [](uint64_t, uint64_t) { return true; });
  1050. ASSERT_TRUE(res);
  1051. EXPECT_EQ("Hello World!", res->body);
  1052. EXPECT_EQ(StatusCode::OK_200, res->status);
  1053. }
  1054. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1055. Server svr;
  1056. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1057. res.set_content("Hello World!", "text/plain");
  1058. });
  1059. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1060. auto se = detail::scope_exit([&] {
  1061. svr.stop();
  1062. thread.join();
  1063. ASSERT_FALSE(svr.is_running());
  1064. });
  1065. svr.wait_until_ready();
  1066. Client cli(HOST, PORT);
  1067. cli.set_connection_timeout(std::chrono::seconds(5));
  1068. auto res =
  1069. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1070. "application/json", [](uint64_t, uint64_t) { return false; });
  1071. ASSERT_TRUE(!res);
  1072. EXPECT_EQ(Error::Canceled, res.error());
  1073. }
  1074. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1075. Server svr;
  1076. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1077. res.set_content(LARGE_DATA, "text/plain");
  1078. });
  1079. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1080. auto se = detail::scope_exit([&] {
  1081. svr.stop();
  1082. thread.join();
  1083. ASSERT_FALSE(svr.is_running());
  1084. });
  1085. svr.wait_until_ready();
  1086. Client cli(HOST, PORT);
  1087. cli.set_connection_timeout(std::chrono::seconds(5));
  1088. auto res =
  1089. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1090. "application/json", [](uint64_t, uint64_t) { return false; });
  1091. ASSERT_TRUE(!res);
  1092. EXPECT_EQ(Error::Canceled, res.error());
  1093. }
  1094. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1095. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1096. auto host = "httpbin.org";
  1097. auto path = std::string{"/basic-auth/hello/world"};
  1098. #else
  1099. auto host = "nghttp2.org";
  1100. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1101. #endif
  1102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1103. auto port = 443;
  1104. SSLClient cli(host, port);
  1105. #else
  1106. auto port = 80;
  1107. Client cli(host, port);
  1108. #endif
  1109. {
  1110. auto res = cli.Get(path);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1113. }
  1114. {
  1115. auto res =
  1116. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1117. ASSERT_TRUE(res);
  1118. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1119. res->body);
  1120. EXPECT_EQ(StatusCode::OK_200, res->status);
  1121. }
  1122. {
  1123. cli.set_basic_auth("hello", "world");
  1124. auto res = cli.Get(path);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1127. res->body);
  1128. EXPECT_EQ(StatusCode::OK_200, res->status);
  1129. }
  1130. {
  1131. cli.set_basic_auth("hello", "bad");
  1132. auto res = cli.Get(path);
  1133. ASSERT_TRUE(res);
  1134. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1135. }
  1136. {
  1137. cli.set_basic_auth("bad", "world");
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1141. }
  1142. }
  1143. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1144. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1145. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1146. auto host = "httpbin.org";
  1147. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1148. auto paths = std::vector<std::string>{
  1149. "/digest-auth/auth/hello/world/MD5",
  1150. "/digest-auth/auth/hello/world/SHA-256",
  1151. "/digest-auth/auth/hello/world/SHA-512",
  1152. "/digest-auth/auth-int/hello/world/MD5",
  1153. };
  1154. #else
  1155. auto host = "nghttp2.org";
  1156. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1157. auto paths = std::vector<std::string>{
  1158. "/httpbin/digest-auth/auth/hello/world/MD5",
  1159. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1160. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1161. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1162. };
  1163. #endif
  1164. auto port = 443;
  1165. SSLClient cli(host, port);
  1166. {
  1167. auto res = cli.Get(unauth_path);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1170. }
  1171. {
  1172. cli.set_digest_auth("hello", "world");
  1173. for (const auto &path : paths) {
  1174. auto res = cli.Get(path.c_str());
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1177. res->body);
  1178. EXPECT_EQ(StatusCode::OK_200, res->status);
  1179. }
  1180. cli.set_digest_auth("hello", "bad");
  1181. for (const auto &path : paths) {
  1182. auto res = cli.Get(path.c_str());
  1183. ASSERT_TRUE(res);
  1184. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1185. }
  1186. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1187. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1188. // cli.set_digest_auth("bad", "world");
  1189. // for (const auto& path : paths) {
  1190. // auto res = cli.Get(path.c_str());
  1191. // ASSERT_TRUE(res);
  1192. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1193. // }
  1194. }
  1195. }
  1196. #endif
  1197. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1198. auto host = "google.com";
  1199. auto another_host = "example.com";
  1200. auto wrong_ip = "0.0.0.0";
  1201. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1202. SSLClient cli(host);
  1203. #else
  1204. Client cli(host);
  1205. #endif
  1206. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1207. auto res = cli.Get("/");
  1208. ASSERT_TRUE(res);
  1209. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1210. }
  1211. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1212. auto host = "google.com";
  1213. auto wrong_ip = "0.0.0.0";
  1214. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1215. SSLClient cli(host);
  1216. #else
  1217. Client cli(host);
  1218. #endif
  1219. cli.set_hostname_addr_map({{host, wrong_ip}});
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1225. auto host = "nghttp2.org";
  1226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_follow_location(true);
  1232. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ(StatusCode::OK_200, res->status);
  1235. }
  1236. TEST(RedirectTest, Redirect_Online) {
  1237. auto host = "nghttp2.org";
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_follow_location(true);
  1244. auto res = cli.Get("/httpbin/redirect/3");
  1245. ASSERT_TRUE(res);
  1246. EXPECT_EQ(StatusCode::OK_200, res->status);
  1247. }
  1248. TEST(RelativeRedirectTest, Redirect_Online) {
  1249. auto host = "nghttp2.org";
  1250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1251. SSLClient cli(host);
  1252. #else
  1253. Client cli(host);
  1254. #endif
  1255. cli.set_follow_location(true);
  1256. auto res = cli.Get("/httpbin/relative-redirect/3");
  1257. ASSERT_TRUE(res);
  1258. EXPECT_EQ(StatusCode::OK_200, res->status);
  1259. }
  1260. TEST(TooManyRedirectTest, Redirect_Online) {
  1261. auto host = "nghttp2.org";
  1262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1263. SSLClient cli(host);
  1264. #else
  1265. Client cli(host);
  1266. #endif
  1267. cli.set_follow_location(true);
  1268. auto res = cli.Get("/httpbin/redirect/21");
  1269. ASSERT_TRUE(!res);
  1270. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1271. }
  1272. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1273. TEST(YahooRedirectTest, Redirect_Online) {
  1274. Client cli("yahoo.com");
  1275. auto res = cli.Get("/");
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1278. cli.set_follow_location(true);
  1279. res = cli.Get("/");
  1280. ASSERT_TRUE(res);
  1281. EXPECT_EQ(StatusCode::OK_200, res->status);
  1282. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1283. }
  1284. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1285. SSLClient cli("nghttp2.org");
  1286. cli.set_follow_location(true);
  1287. auto res = cli.Get(
  1288. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  1289. ASSERT_TRUE(res);
  1290. EXPECT_EQ(StatusCode::OK_200, res->status);
  1291. }
  1292. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1293. SSLClient cli("nghttp2.org");
  1294. cli.set_follow_location(true);
  1295. Params params;
  1296. params.emplace("url", "http://www.google.com");
  1297. params.emplace("status_code", "302");
  1298. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ(StatusCode::OK_200, res->status);
  1301. }
  1302. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1303. SSLClient cli("nghttp2.org");
  1304. cli.set_follow_location(true);
  1305. Params params;
  1306. params.emplace("url", "http://www.google.com");
  1307. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  1308. ASSERT_TRUE(res);
  1309. EXPECT_EQ(StatusCode::OK_200, res->status);
  1310. }
  1311. TEST(UrlWithSpace, Redirect_Online) {
  1312. SSLClient cli("edge.forgecdn.net");
  1313. cli.set_follow_location(true);
  1314. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ(StatusCode::OK_200, res->status);
  1317. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1318. }
  1319. #endif
  1320. #if !defined(_WIN32) && !defined(_WIN64)
  1321. TEST(ReceiveSignals, Signal) {
  1322. auto setupSignalHandlers = []() {
  1323. struct sigaction act;
  1324. sigemptyset(&act.sa_mask);
  1325. act.sa_flags = SA_SIGINFO;
  1326. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1327. switch (sig) {
  1328. case SIGINT:
  1329. default: break;
  1330. }
  1331. };
  1332. ::sigaction(SIGINT, &act, nullptr);
  1333. };
  1334. Server svr;
  1335. int port = 0;
  1336. auto thread = std::thread([&]() {
  1337. setupSignalHandlers();
  1338. port = svr.bind_to_any_port("localhost");
  1339. svr.listen_after_bind();
  1340. });
  1341. auto se = detail::scope_exit([&] {
  1342. svr.stop();
  1343. thread.join();
  1344. ASSERT_FALSE(svr.is_running());
  1345. });
  1346. svr.wait_until_ready();
  1347. ASSERT_TRUE(svr.is_running());
  1348. pthread_kill(thread.native_handle(), SIGINT);
  1349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1350. ASSERT_TRUE(svr.is_running());
  1351. }
  1352. #endif
  1353. TEST(RedirectToDifferentPort, Redirect) {
  1354. Server svr1;
  1355. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1356. res.set_content("Hello World!", "text/plain");
  1357. });
  1358. int svr1_port = 0;
  1359. auto thread1 = std::thread([&]() {
  1360. svr1_port = svr1.bind_to_any_port("localhost");
  1361. svr1.listen_after_bind();
  1362. });
  1363. Server svr2;
  1364. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1365. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1366. });
  1367. int svr2_port = 0;
  1368. auto thread2 = std::thread([&]() {
  1369. svr2_port = svr2.bind_to_any_port("localhost");
  1370. svr2.listen_after_bind();
  1371. });
  1372. auto se = detail::scope_exit([&] {
  1373. svr2.stop();
  1374. thread2.join();
  1375. svr1.stop();
  1376. thread1.join();
  1377. ASSERT_FALSE(svr2.is_running());
  1378. ASSERT_FALSE(svr1.is_running());
  1379. });
  1380. svr1.wait_until_ready();
  1381. svr2.wait_until_ready();
  1382. Client cli("localhost", svr2_port);
  1383. cli.set_follow_location(true);
  1384. auto res = cli.Get("/2");
  1385. ASSERT_TRUE(res);
  1386. EXPECT_EQ(StatusCode::OK_200, res->status);
  1387. EXPECT_EQ("Hello World!", res->body);
  1388. }
  1389. TEST(RedirectFromPageWithContent, Redirect) {
  1390. Server svr;
  1391. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1392. res.set_content("___", "text/plain");
  1393. res.set_redirect("/2");
  1394. });
  1395. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1396. res.set_content("Hello World!", "text/plain");
  1397. });
  1398. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1399. auto se = detail::scope_exit([&] {
  1400. svr.stop();
  1401. th.join();
  1402. ASSERT_FALSE(svr.is_running());
  1403. });
  1404. svr.wait_until_ready();
  1405. {
  1406. Client cli("localhost", PORT);
  1407. cli.set_follow_location(true);
  1408. std::string body;
  1409. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1410. body.append(data, data_length);
  1411. return true;
  1412. });
  1413. ASSERT_TRUE(res);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. EXPECT_EQ("Hello World!", body);
  1416. }
  1417. {
  1418. Client cli("localhost", PORT);
  1419. std::string body;
  1420. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1421. body.append(data, data_length);
  1422. return true;
  1423. });
  1424. ASSERT_TRUE(res);
  1425. EXPECT_EQ(StatusCode::Found_302, res->status);
  1426. EXPECT_EQ("___", body);
  1427. }
  1428. }
  1429. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1430. Server svr;
  1431. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("___", "text/plain");
  1433. // res.set_redirect("/2");
  1434. res.set_redirect("http://[::1]:1234/2");
  1435. });
  1436. svr.Get("/2", [&](const Request &req, Response &res) {
  1437. auto host_header = req.headers.find("Host");
  1438. ASSERT_TRUE(host_header != req.headers.end());
  1439. EXPECT_EQ("[::1]:1234", host_header->second);
  1440. res.set_content("Hello World!", "text/plain");
  1441. });
  1442. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. th.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1449. // actually starts anything, so the condition !svr.is_running() will
  1450. // always remain true, and the loop never stops.
  1451. // This basically counts how many milliseconds have passed since the
  1452. // call to svr.listen(), and if after 5 seconds nothing started yet
  1453. // aborts the test.
  1454. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1455. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1456. ASSERT_LT(milliseconds, 5000U);
  1457. }
  1458. {
  1459. Client cli("http://[::1]:1234");
  1460. cli.set_follow_location(true);
  1461. std::string body;
  1462. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1463. body.append(data, data_length);
  1464. return true;
  1465. });
  1466. ASSERT_TRUE(res);
  1467. EXPECT_EQ(StatusCode::OK_200, res->status);
  1468. EXPECT_EQ("Hello World!", body);
  1469. }
  1470. {
  1471. Client cli("http://[::1]:1234");
  1472. std::string body;
  1473. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1474. body.append(data, data_length);
  1475. return true;
  1476. });
  1477. ASSERT_TRUE(res);
  1478. EXPECT_EQ(StatusCode::Found_302, res->status);
  1479. EXPECT_EQ("___", body);
  1480. }
  1481. }
  1482. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1483. Server svr;
  1484. svr.Get("/foo", [](const Request &req, Response &res) {
  1485. auto a = req.params.find("a");
  1486. if (a != req.params.end()) {
  1487. res.set_content((*a).second, "text/plain");
  1488. res.status = StatusCode::OK_200;
  1489. } else {
  1490. res.status = StatusCode::BadRequest_400;
  1491. }
  1492. });
  1493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1494. auto se = detail::scope_exit([&] {
  1495. svr.stop();
  1496. thread.join();
  1497. ASSERT_FALSE(svr.is_running());
  1498. });
  1499. svr.wait_until_ready();
  1500. {
  1501. Client cli(HOST, PORT);
  1502. cli.set_url_encode(false);
  1503. auto res = cli.Get("/foo?a=explicitly+encoded");
  1504. ASSERT_TRUE(res);
  1505. EXPECT_EQ(StatusCode::OK_200, res->status);
  1506. // This expects it back with a space, as the `+` won't have been
  1507. // url-encoded, and server-side the params get decoded turning `+`
  1508. // into spaces.
  1509. EXPECT_EQ("explicitly encoded", res->body);
  1510. }
  1511. }
  1512. TEST(BindServerTest, DISABLED_BindDualStack) {
  1513. Server svr;
  1514. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1515. res.set_content("Hello World!", "text/plain");
  1516. });
  1517. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1518. auto se = detail::scope_exit([&] {
  1519. svr.stop();
  1520. thread.join();
  1521. ASSERT_FALSE(svr.is_running());
  1522. });
  1523. svr.wait_until_ready();
  1524. {
  1525. Client cli("127.0.0.1", PORT);
  1526. auto res = cli.Get("/1");
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. EXPECT_EQ("Hello World!", res->body);
  1530. }
  1531. {
  1532. Client cli("::1", PORT);
  1533. auto res = cli.Get("/1");
  1534. ASSERT_TRUE(res);
  1535. EXPECT_EQ(StatusCode::OK_200, res->status);
  1536. EXPECT_EQ("Hello World!", res->body);
  1537. }
  1538. }
  1539. TEST(BindServerTest, BindAndListenSeparately) {
  1540. Server svr;
  1541. int port = svr.bind_to_any_port("0.0.0.0");
  1542. ASSERT_TRUE(svr.is_valid());
  1543. ASSERT_TRUE(port > 0);
  1544. svr.stop();
  1545. }
  1546. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1547. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1549. CLIENT_CA_CERT_DIR);
  1550. int port = svr.bind_to_any_port("0.0.0.0");
  1551. ASSERT_TRUE(svr.is_valid());
  1552. ASSERT_TRUE(port > 0);
  1553. svr.stop();
  1554. }
  1555. #endif
  1556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1557. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1558. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1559. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1560. int port = svr.bind_to_any_port("0.0.0.0");
  1561. ASSERT_TRUE(svr.is_valid());
  1562. ASSERT_TRUE(port > 0);
  1563. svr.stop();
  1564. }
  1565. #endif
  1566. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1567. X509 *readCertificate(const std::string &strFileName) {
  1568. std::ifstream inStream(strFileName);
  1569. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1570. std::istreambuf_iterator<char>());
  1571. if (strCertPEM.empty()) return (nullptr);
  1572. BIO *pbCert = BIO_new(BIO_s_mem());
  1573. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1574. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1575. BIO_free(pbCert);
  1576. return (pCert);
  1577. }
  1578. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1579. std::ifstream inStream(strFileName);
  1580. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1581. std::istreambuf_iterator<char>());
  1582. if (strPrivateKeyPEM.empty()) return (nullptr);
  1583. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1584. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1585. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1586. BIO_free(pbPrivKey);
  1587. return (pPrivateKey);
  1588. }
  1589. TEST(BindServerTest, UpdateCerts) {
  1590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1591. int port = svr.bind_to_any_port("0.0.0.0");
  1592. ASSERT_TRUE(svr.is_valid());
  1593. ASSERT_TRUE(port > 0);
  1594. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1595. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1596. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1597. ASSERT_TRUE(cert != nullptr);
  1598. ASSERT_TRUE(ca_cert != nullptr);
  1599. ASSERT_TRUE(key != nullptr);
  1600. X509_STORE *cert_store = X509_STORE_new();
  1601. X509_STORE_add_cert(cert_store, ca_cert);
  1602. svr.update_certs(cert, key, cert_store);
  1603. ASSERT_TRUE(svr.is_valid());
  1604. svr.stop();
  1605. X509_free(cert);
  1606. X509_free(ca_cert);
  1607. EVP_PKEY_free(key);
  1608. }
  1609. #endif
  1610. TEST(ErrorHandlerTest, ContentLength) {
  1611. Server svr;
  1612. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1613. res.status = StatusCode::OK_200;
  1614. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1615. "text/html"); // <= Content-Length still 13
  1616. });
  1617. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1618. res.set_content("Hello World!\n", "text/plain");
  1619. res.status = 524;
  1620. });
  1621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1622. auto se = detail::scope_exit([&] {
  1623. svr.stop();
  1624. thread.join();
  1625. ASSERT_FALSE(svr.is_running());
  1626. });
  1627. svr.wait_until_ready();
  1628. {
  1629. Client cli(HOST, PORT);
  1630. auto res = cli.Get("/hi");
  1631. ASSERT_TRUE(res);
  1632. EXPECT_EQ(StatusCode::OK_200, res->status);
  1633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1634. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1635. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1636. }
  1637. }
  1638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1639. TEST(ExceptionHandlerTest, ContentLength) {
  1640. Server svr;
  1641. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1642. std::exception_ptr ep) {
  1643. EXPECT_FALSE(ep == nullptr);
  1644. try {
  1645. std::rethrow_exception(ep);
  1646. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1647. res.status = StatusCode::InternalServerError_500;
  1648. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1649. "text/html"); // <= Content-Length still 13 at this point
  1650. });
  1651. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1652. res.set_content("Hello World!\n", "text/plain");
  1653. throw std::runtime_error("abc");
  1654. });
  1655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1656. auto se = detail::scope_exit([&] {
  1657. svr.stop();
  1658. thread.join();
  1659. ASSERT_FALSE(svr.is_running());
  1660. });
  1661. svr.wait_until_ready();
  1662. for (size_t i = 0; i < 10; i++) {
  1663. Client cli(HOST, PORT);
  1664. for (size_t j = 0; j < 100; j++) {
  1665. auto res = cli.Get("/hi");
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1669. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1670. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1671. }
  1672. cli.set_keep_alive(true);
  1673. for (size_t j = 0; j < 100; j++) {
  1674. auto res = cli.Get("/hi");
  1675. ASSERT_TRUE(res);
  1676. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1677. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1678. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1679. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1680. }
  1681. }
  1682. }
  1683. #endif
  1684. TEST(NoContentTest, ContentLength) {
  1685. Server svr;
  1686. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1687. res.status = StatusCode::NoContent_204;
  1688. });
  1689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1690. auto se = detail::scope_exit([&] {
  1691. svr.stop();
  1692. thread.join();
  1693. ASSERT_FALSE(svr.is_running());
  1694. });
  1695. svr.wait_until_ready();
  1696. {
  1697. Client cli(HOST, PORT);
  1698. auto res = cli.Get("/hi");
  1699. ASSERT_TRUE(res);
  1700. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  1701. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1702. }
  1703. }
  1704. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1707. ASSERT_TRUE(svr.is_valid());
  1708. #else
  1709. Server svr;
  1710. #endif
  1711. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1712. if (req.path == "/routing_handler") {
  1713. res.set_header("PRE_ROUTING", "on");
  1714. res.set_content("Routing Handler", "text/plain");
  1715. return httplib::Server::HandlerResponse::Handled;
  1716. }
  1717. return httplib::Server::HandlerResponse::Unhandled;
  1718. });
  1719. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1720. res.set_content("Error", "text/html");
  1721. });
  1722. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1723. if (req.path == "/routing_handler") {
  1724. res.set_header("POST_ROUTING", "on");
  1725. }
  1726. });
  1727. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1728. res.set_content("Hello World!\n", "text/plain");
  1729. });
  1730. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1731. auto se = detail::scope_exit([&] {
  1732. svr.stop();
  1733. thread.join();
  1734. ASSERT_FALSE(svr.is_running());
  1735. });
  1736. svr.wait_until_ready();
  1737. {
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(HOST, PORT);
  1740. cli.enable_server_certificate_verification(false);
  1741. #else
  1742. Client cli(HOST, PORT);
  1743. #endif
  1744. auto res = cli.Get("/routing_handler");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. EXPECT_EQ("Routing Handler", res->body);
  1748. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1749. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1750. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1751. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1752. }
  1753. {
  1754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1755. SSLClient cli(HOST, PORT);
  1756. cli.enable_server_certificate_verification(false);
  1757. #else
  1758. Client cli(HOST, PORT);
  1759. #endif
  1760. auto res = cli.Get("/hi");
  1761. ASSERT_TRUE(res);
  1762. EXPECT_EQ(StatusCode::OK_200, res->status);
  1763. EXPECT_EQ("Hello World!\n", res->body);
  1764. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1765. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1766. }
  1767. {
  1768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1769. SSLClient cli(HOST, PORT);
  1770. cli.enable_server_certificate_verification(false);
  1771. #else
  1772. Client cli(HOST, PORT);
  1773. #endif
  1774. auto res = cli.Get("/aaa");
  1775. ASSERT_TRUE(res);
  1776. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1777. EXPECT_EQ("Error", res->body);
  1778. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1779. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1780. }
  1781. }
  1782. TEST(InvalidFormatTest, StatusCode) {
  1783. Server svr;
  1784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1785. res.set_content("Hello World!\n", "text/plain");
  1786. res.status = 9999; // Status should be a three-digit code...
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. {
  1796. Client cli(HOST, PORT);
  1797. auto res = cli.Get("/hi");
  1798. ASSERT_FALSE(res);
  1799. }
  1800. }
  1801. TEST(URLFragmentTest, WithFragment) {
  1802. Server svr;
  1803. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1804. EXPECT_TRUE(req.target == "/hi");
  1805. });
  1806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1807. auto se = detail::scope_exit([&] {
  1808. svr.stop();
  1809. thread.join();
  1810. ASSERT_FALSE(svr.is_running());
  1811. });
  1812. svr.wait_until_ready();
  1813. {
  1814. Client cli(HOST, PORT);
  1815. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1816. EXPECT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. res = cli.Get("/hi%23key1=val1=key2=val2");
  1819. EXPECT_TRUE(res);
  1820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1821. }
  1822. }
  1823. TEST(HeaderWriter, SetHeaderWriter) {
  1824. Server svr;
  1825. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1826. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1827. return detail::write_headers(strm, hdrs);
  1828. });
  1829. svr.Get("/hi", [](const Request &req, Response &res) {
  1830. auto it = req.headers.find("CustomClientHeader");
  1831. EXPECT_TRUE(it != req.headers.end());
  1832. EXPECT_EQ(it->second, "CustomClientValue");
  1833. res.set_content("Hello World!\n", "text/plain");
  1834. });
  1835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. thread.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. {
  1843. Client cli(HOST, PORT);
  1844. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1845. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1846. return detail::write_headers(strm, hdrs);
  1847. });
  1848. auto res = cli.Get("/hi");
  1849. EXPECT_TRUE(res);
  1850. EXPECT_EQ(StatusCode::OK_200, res->status);
  1851. auto it = res->headers.find("CustomServerHeader");
  1852. EXPECT_TRUE(it != res->headers.end());
  1853. EXPECT_EQ(it->second, "CustomServerValue");
  1854. }
  1855. }
  1856. class ServerTest : public ::testing::Test {
  1857. protected:
  1858. ServerTest()
  1859. : cli_(HOST, PORT)
  1860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1861. ,
  1862. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1863. #endif
  1864. {
  1865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1866. cli_.enable_server_certificate_verification(false);
  1867. #endif
  1868. }
  1869. virtual void SetUp() {
  1870. svr_.set_mount_point("/", "./www");
  1871. svr_.set_mount_point("/mount", "./www2");
  1872. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1873. svr_.Get("/hi",
  1874. [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("Hello World!", "text/plain");
  1876. })
  1877. .Get("/http_response_splitting",
  1878. [&](const Request & /*req*/, Response &res) {
  1879. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1880. EXPECT_EQ(0U, res.headers.size());
  1881. EXPECT_FALSE(res.has_header("a"));
  1882. res.set_header("a", "1\nSet-Cookie: a=1");
  1883. EXPECT_EQ(0U, res.headers.size());
  1884. EXPECT_FALSE(res.has_header("a"));
  1885. res.set_header("a", "1\rSet-Cookie: a=1");
  1886. EXPECT_EQ(0U, res.headers.size());
  1887. EXPECT_FALSE(res.has_header("a"));
  1888. res.set_header("a\r\nb", "0");
  1889. EXPECT_EQ(0U, res.headers.size());
  1890. EXPECT_FALSE(res.has_header("a"));
  1891. res.set_header("a\rb", "0");
  1892. EXPECT_EQ(0U, res.headers.size());
  1893. EXPECT_FALSE(res.has_header("a"));
  1894. res.set_header("a\nb", "0");
  1895. EXPECT_EQ(0U, res.headers.size());
  1896. EXPECT_FALSE(res.has_header("a"));
  1897. res.set_redirect("1\r\nSet-Cookie: a=1");
  1898. EXPECT_EQ(0U, res.headers.size());
  1899. EXPECT_FALSE(res.has_header("Location"));
  1900. })
  1901. .Get("/slow",
  1902. [&](const Request & /*req*/, Response &res) {
  1903. std::this_thread::sleep_for(std::chrono::seconds(2));
  1904. res.set_content("slow", "text/plain");
  1905. })
  1906. #if 0
  1907. .Post("/slowpost",
  1908. [&](const Request & /*req*/, Response &res) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(2));
  1910. res.set_content("slow", "text/plain");
  1911. })
  1912. #endif
  1913. .Get("/remote_addr",
  1914. [&](const Request &req, Response &res) {
  1915. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1916. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1917. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1918. EXPECT_EQ(req.remote_port,
  1919. std::stoi(req.get_header_value("REMOTE_PORT")));
  1920. res.set_content(remote_addr.c_str(), "text/plain");
  1921. })
  1922. .Get("/local_addr",
  1923. [&](const Request &req, Response &res) {
  1924. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1925. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1926. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1927. auto local_port = req.get_header_value("LOCAL_PORT");
  1928. EXPECT_EQ(req.local_addr, local_addr);
  1929. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1930. res.set_content(local_addr.append(":").append(local_port),
  1931. "text/plain");
  1932. })
  1933. .Get("/endwith%",
  1934. [&](const Request & /*req*/, Response &res) {
  1935. res.set_content("Hello World!", "text/plain");
  1936. })
  1937. .Get("/a\\+\\+b",
  1938. [&](const Request &req, Response &res) {
  1939. ASSERT_TRUE(req.has_param("a +b"));
  1940. auto val = req.get_param_value("a +b");
  1941. res.set_content(val, "text/plain");
  1942. })
  1943. .Get("/", [&](const Request & /*req*/,
  1944. Response &res) { res.set_redirect("/hi"); })
  1945. .Post("/1",
  1946. [](const Request & /*req*/, Response &res) {
  1947. res.set_redirect("/2", StatusCode::SeeOther_303);
  1948. })
  1949. .Get("/2",
  1950. [](const Request & /*req*/, Response &res) {
  1951. res.set_content("redirected.", "text/plain");
  1952. res.status = StatusCode::OK_200;
  1953. })
  1954. .Post("/person",
  1955. [&](const Request &req, Response &res) {
  1956. if (req.has_param("name") && req.has_param("note")) {
  1957. persons_[req.get_param_value("name")] =
  1958. req.get_param_value("note");
  1959. } else {
  1960. res.status = StatusCode::BadRequest_400;
  1961. }
  1962. })
  1963. .Put("/person",
  1964. [&](const Request &req, Response &res) {
  1965. if (req.has_param("name") && req.has_param("note")) {
  1966. persons_[req.get_param_value("name")] =
  1967. req.get_param_value("note");
  1968. } else {
  1969. res.status = StatusCode::BadRequest_400;
  1970. }
  1971. })
  1972. .Get("/person/(.*)",
  1973. [&](const Request &req, Response &res) {
  1974. string name = req.matches[1];
  1975. if (persons_.find(name) != persons_.end()) {
  1976. auto note = persons_[name];
  1977. res.set_content(note, "text/plain");
  1978. } else {
  1979. res.status = StatusCode::NotFound_404;
  1980. }
  1981. })
  1982. .Post("/x-www-form-urlencoded-json",
  1983. [&](const Request &req, Response &res) {
  1984. auto json = req.get_param_value("json");
  1985. ASSERT_EQ(JSON_DATA, json);
  1986. res.set_content(json, "appliation/json");
  1987. res.status = StatusCode::OK_200;
  1988. })
  1989. .Get("/streamed-chunked",
  1990. [&](const Request & /*req*/, Response &res) {
  1991. res.set_chunked_content_provider(
  1992. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1993. sink.os << "123";
  1994. sink.os << "456";
  1995. sink.os << "789";
  1996. sink.done();
  1997. return true;
  1998. });
  1999. })
  2000. .Get("/streamed-chunked2",
  2001. [&](const Request & /*req*/, Response &res) {
  2002. auto i = new int(0);
  2003. res.set_chunked_content_provider(
  2004. "text/plain",
  2005. [i](size_t /*offset*/, DataSink &sink) {
  2006. switch (*i) {
  2007. case 0: sink.os << "123"; break;
  2008. case 1: sink.os << "456"; break;
  2009. case 2: sink.os << "789"; break;
  2010. case 3: sink.done(); break;
  2011. }
  2012. (*i)++;
  2013. return true;
  2014. },
  2015. [i](bool success) {
  2016. EXPECT_TRUE(success);
  2017. delete i;
  2018. });
  2019. })
  2020. .Get("/streamed-chunked-with-trailer",
  2021. [&](const Request & /*req*/, Response &res) {
  2022. auto i = new int(0);
  2023. res.set_header("Trailer", "Dummy1, Dummy2");
  2024. res.set_chunked_content_provider(
  2025. "text/plain",
  2026. [i](size_t /*offset*/, DataSink &sink) {
  2027. switch (*i) {
  2028. case 0: sink.os << "123"; break;
  2029. case 1: sink.os << "456"; break;
  2030. case 2: sink.os << "789"; break;
  2031. case 3: {
  2032. sink.done_with_trailer(
  2033. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2034. } break;
  2035. }
  2036. (*i)++;
  2037. return true;
  2038. },
  2039. [i](bool success) {
  2040. EXPECT_TRUE(success);
  2041. delete i;
  2042. });
  2043. })
  2044. .Get("/streamed",
  2045. [&](const Request & /*req*/, Response &res) {
  2046. res.set_content_provider(
  2047. 6, "text/plain",
  2048. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2049. sink.os << (offset < 3 ? "a" : "b");
  2050. return true;
  2051. });
  2052. })
  2053. .Get("/streamed-with-range",
  2054. [&](const Request &req, Response &res) {
  2055. auto data = new std::string("abcdefg");
  2056. res.set_content_provider(
  2057. data->size(), "text/plain",
  2058. [data](size_t offset, size_t length, DataSink &sink) {
  2059. size_t DATA_CHUNK_SIZE = 4;
  2060. const auto &d = *data;
  2061. auto out_len =
  2062. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2063. auto ret =
  2064. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2065. EXPECT_TRUE(ret);
  2066. return true;
  2067. },
  2068. [data, &req](bool success) {
  2069. EXPECT_EQ(success, !req.has_param("error"));
  2070. delete data;
  2071. });
  2072. })
  2073. .Get("/streamed-cancel",
  2074. [&](const Request & /*req*/, Response &res) {
  2075. res.set_content_provider(
  2076. size_t(-1), "text/plain",
  2077. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2078. sink.os << "data_chunk";
  2079. return true;
  2080. });
  2081. })
  2082. .Get("/regex-with-delimiter",
  2083. [&](const Request &req, Response & /*res*/) {
  2084. ASSERT_TRUE(req.has_param("key"));
  2085. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2086. })
  2087. .Get("/with-range",
  2088. [&](const Request & /*req*/, Response &res) {
  2089. res.set_content("abcdefg", "text/plain");
  2090. })
  2091. .Get("/with-range-customized-response",
  2092. [&](const Request & /*req*/, Response &res) {
  2093. res.status = StatusCode::BadRequest_400;
  2094. res.set_content(JSON_DATA, "application/json");
  2095. })
  2096. .Post("/chunked",
  2097. [&](const Request &req, Response & /*res*/) {
  2098. EXPECT_EQ(req.body, "dechunked post body");
  2099. })
  2100. .Post("/large-chunked",
  2101. [&](const Request &req, Response & /*res*/) {
  2102. std::string expected(6 * 30 * 1024u, 'a');
  2103. EXPECT_EQ(req.body, expected);
  2104. })
  2105. .Post("/multipart",
  2106. [&](const Request &req, Response & /*res*/) {
  2107. EXPECT_EQ(6u, req.files.size());
  2108. ASSERT_TRUE(!req.has_file("???"));
  2109. ASSERT_TRUE(req.body.empty());
  2110. {
  2111. const auto &file = req.get_file_value("text1");
  2112. EXPECT_TRUE(file.filename.empty());
  2113. EXPECT_EQ("text default", file.content);
  2114. }
  2115. {
  2116. const auto &file = req.get_file_value("text2");
  2117. EXPECT_TRUE(file.filename.empty());
  2118. EXPECT_EQ("aωb", file.content);
  2119. }
  2120. {
  2121. const auto &file = req.get_file_value("file1");
  2122. EXPECT_EQ("hello.txt", file.filename);
  2123. EXPECT_EQ("text/plain", file.content_type);
  2124. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2125. }
  2126. {
  2127. const auto &file = req.get_file_value("file3");
  2128. EXPECT_TRUE(file.filename.empty());
  2129. EXPECT_EQ("application/octet-stream", file.content_type);
  2130. EXPECT_EQ(0u, file.content.size());
  2131. }
  2132. {
  2133. const auto &file = req.get_file_value("file4");
  2134. EXPECT_TRUE(file.filename.empty());
  2135. EXPECT_EQ(0u, file.content.size());
  2136. EXPECT_EQ("application/json tmp-string", file.content_type);
  2137. }
  2138. })
  2139. .Post("/multipart/multi_file_values",
  2140. [&](const Request &req, Response & /*res*/) {
  2141. EXPECT_EQ(5u, req.files.size());
  2142. ASSERT_TRUE(!req.has_file("???"));
  2143. ASSERT_TRUE(req.body.empty());
  2144. {
  2145. const auto &text_value = req.get_file_values("text");
  2146. EXPECT_EQ(1u, text_value.size());
  2147. auto &text = text_value[0];
  2148. EXPECT_TRUE(text.filename.empty());
  2149. EXPECT_EQ("default text", text.content);
  2150. }
  2151. {
  2152. const auto &text1_values = req.get_file_values("multi_text1");
  2153. EXPECT_EQ(2u, text1_values.size());
  2154. EXPECT_EQ("aaaaa", text1_values[0].content);
  2155. EXPECT_EQ("bbbbb", text1_values[1].content);
  2156. }
  2157. {
  2158. const auto &file1_values = req.get_file_values("multi_file1");
  2159. EXPECT_EQ(2u, file1_values.size());
  2160. auto file1 = file1_values[0];
  2161. EXPECT_EQ(file1.filename, "hello.txt");
  2162. EXPECT_EQ(file1.content_type, "text/plain");
  2163. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2164. auto file2 = file1_values[1];
  2165. EXPECT_EQ(file2.filename, "world.json");
  2166. EXPECT_EQ(file2.content_type, "application/json");
  2167. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2168. }
  2169. })
  2170. .Post("/empty",
  2171. [&](const Request &req, Response &res) {
  2172. EXPECT_EQ(req.body, "");
  2173. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2174. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2175. res.set_content("empty", "text/plain");
  2176. })
  2177. .Post("/empty-no-content-type",
  2178. [&](const Request &req, Response &res) {
  2179. EXPECT_EQ(req.body, "");
  2180. EXPECT_FALSE(req.has_header("Content-Type"));
  2181. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2182. res.set_content("empty-no-content-type", "text/plain");
  2183. })
  2184. .Post("/path-only",
  2185. [&](const Request &req, Response &res) {
  2186. EXPECT_EQ(req.body, "");
  2187. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2188. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2189. res.set_content("path-only", "text/plain");
  2190. })
  2191. .Post("/path-headers-only",
  2192. [&](const Request &req, Response &res) {
  2193. EXPECT_EQ(req.body, "");
  2194. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2195. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2196. EXPECT_EQ("world", req.get_header_value("hello"));
  2197. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2198. res.set_content("path-headers-only", "text/plain");
  2199. })
  2200. .Post("/post-large",
  2201. [&](const Request &req, Response &res) {
  2202. EXPECT_EQ(req.body, LARGE_DATA);
  2203. res.set_content(req.body, "text/plain");
  2204. })
  2205. .Put("/empty-no-content-type",
  2206. [&](const Request &req, Response &res) {
  2207. EXPECT_EQ(req.body, "");
  2208. EXPECT_FALSE(req.has_header("Content-Type"));
  2209. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2210. res.set_content("empty-no-content-type", "text/plain");
  2211. })
  2212. .Put("/put",
  2213. [&](const Request &req, Response &res) {
  2214. EXPECT_EQ(req.body, "PUT");
  2215. res.set_content(req.body, "text/plain");
  2216. })
  2217. .Put("/put-large",
  2218. [&](const Request &req, Response &res) {
  2219. EXPECT_EQ(req.body, LARGE_DATA);
  2220. res.set_content(req.body, "text/plain");
  2221. })
  2222. .Patch("/patch",
  2223. [&](const Request &req, Response &res) {
  2224. EXPECT_EQ(req.body, "PATCH");
  2225. res.set_content(req.body, "text/plain");
  2226. })
  2227. .Delete("/delete",
  2228. [&](const Request & /*req*/, Response &res) {
  2229. res.set_content("DELETE", "text/plain");
  2230. })
  2231. .Delete("/delete-body",
  2232. [&](const Request &req, Response &res) {
  2233. EXPECT_EQ(req.body, "content");
  2234. res.set_content(req.body, "text/plain");
  2235. })
  2236. .Options(R"(\*)",
  2237. [&](const Request & /*req*/, Response &res) {
  2238. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2239. })
  2240. .Get("/request-target",
  2241. [&](const Request &req, Response & /*res*/) {
  2242. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2243. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2244. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2245. })
  2246. .Get("/long-query-value",
  2247. [&](const Request &req, Response & /*res*/) {
  2248. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2249. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2250. })
  2251. .Get("/array-param",
  2252. [&](const Request &req, Response & /*res*/) {
  2253. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2254. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2255. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2256. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2257. })
  2258. .Post("/validate-no-multiple-headers",
  2259. [&](const Request &req, Response & /*res*/) {
  2260. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2261. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2262. })
  2263. .Post("/content_receiver",
  2264. [&](const Request &req, Response &res,
  2265. const ContentReader &content_reader) {
  2266. if (req.is_multipart_form_data()) {
  2267. MultipartFormDataItems files;
  2268. content_reader(
  2269. [&](const MultipartFormData &file) {
  2270. files.push_back(file);
  2271. return true;
  2272. },
  2273. [&](const char *data, size_t data_length) {
  2274. files.back().content.append(data, data_length);
  2275. return true;
  2276. });
  2277. EXPECT_EQ(5u, files.size());
  2278. {
  2279. const auto &file = get_file_value(files, "text1");
  2280. EXPECT_TRUE(file.filename.empty());
  2281. EXPECT_EQ("text default", file.content);
  2282. }
  2283. {
  2284. const auto &file = get_file_value(files, "text2");
  2285. EXPECT_TRUE(file.filename.empty());
  2286. EXPECT_EQ("aωb", file.content);
  2287. }
  2288. {
  2289. const auto &file = get_file_value(files, "file1");
  2290. EXPECT_EQ("hello.txt", file.filename);
  2291. EXPECT_EQ("text/plain", file.content_type);
  2292. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2293. }
  2294. {
  2295. const auto &file = get_file_value(files, "file3");
  2296. EXPECT_TRUE(file.filename.empty());
  2297. EXPECT_EQ("application/octet-stream", file.content_type);
  2298. EXPECT_EQ(0u, file.content.size());
  2299. }
  2300. } else {
  2301. std::string body;
  2302. content_reader([&](const char *data, size_t data_length) {
  2303. EXPECT_EQ(7U, data_length);
  2304. body.append(data, data_length);
  2305. return true;
  2306. });
  2307. EXPECT_EQ(body, "content");
  2308. res.set_content(body, "text/plain");
  2309. }
  2310. })
  2311. .Put("/content_receiver",
  2312. [&](const Request & /*req*/, Response &res,
  2313. const ContentReader &content_reader) {
  2314. std::string body;
  2315. content_reader([&](const char *data, size_t data_length) {
  2316. body.append(data, data_length);
  2317. return true;
  2318. });
  2319. EXPECT_EQ(body, "content");
  2320. res.set_content(body, "text/plain");
  2321. })
  2322. .Patch("/content_receiver",
  2323. [&](const Request & /*req*/, Response &res,
  2324. const ContentReader &content_reader) {
  2325. std::string body;
  2326. content_reader([&](const char *data, size_t data_length) {
  2327. body.append(data, data_length);
  2328. return true;
  2329. });
  2330. EXPECT_EQ(body, "content");
  2331. res.set_content(body, "text/plain");
  2332. })
  2333. .Post("/query-string-and-body",
  2334. [&](const Request &req, Response & /*res*/) {
  2335. ASSERT_TRUE(req.has_param("key"));
  2336. EXPECT_EQ(req.get_param_value("key"), "value");
  2337. EXPECT_EQ(req.body, "content");
  2338. })
  2339. .Get("/last-request",
  2340. [&](const Request &req, Response & /*res*/) {
  2341. EXPECT_EQ("close", req.get_header_value("Connection"));
  2342. })
  2343. .Get(R"(/redirect/(\d+))",
  2344. [&](const Request &req, Response &res) {
  2345. auto num = std::stoi(req.matches[1]) + 1;
  2346. std::string url = "/redirect/" + std::to_string(num);
  2347. res.set_redirect(url);
  2348. })
  2349. .Post("/binary",
  2350. [&](const Request &req, Response &res) {
  2351. EXPECT_EQ(4U, req.body.size());
  2352. EXPECT_EQ("application/octet-stream",
  2353. req.get_header_value("Content-Type"));
  2354. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2355. res.set_content(req.body, "application/octet-stream");
  2356. })
  2357. .Put("/binary",
  2358. [&](const Request &req, Response &res) {
  2359. EXPECT_EQ(4U, req.body.size());
  2360. EXPECT_EQ("application/octet-stream",
  2361. req.get_header_value("Content-Type"));
  2362. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2363. res.set_content(req.body, "application/octet-stream");
  2364. })
  2365. .Patch("/binary",
  2366. [&](const Request &req, Response &res) {
  2367. EXPECT_EQ(4U, req.body.size());
  2368. EXPECT_EQ("application/octet-stream",
  2369. req.get_header_value("Content-Type"));
  2370. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2371. res.set_content(req.body, "application/octet-stream");
  2372. })
  2373. .Delete("/binary",
  2374. [&](const Request &req, Response &res) {
  2375. EXPECT_EQ(4U, req.body.size());
  2376. EXPECT_EQ("application/octet-stream",
  2377. req.get_header_value("Content-Type"));
  2378. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2379. res.set_content(req.body, "application/octet-stream");
  2380. })
  2381. .Get("/issue1772",
  2382. [&](const Request & /*req*/, Response &res) {
  2383. res.status = 401;
  2384. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2385. })
  2386. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  2387. .Get("/compress",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. res.set_content(
  2390. "12345678901234567890123456789012345678901234567890123456789"
  2391. "01234567890123456789012345678901234567890",
  2392. "text/plain");
  2393. })
  2394. .Get("/nocompress",
  2395. [&](const Request & /*req*/, Response &res) {
  2396. res.set_content(
  2397. "12345678901234567890123456789012345678901234567890123456789"
  2398. "01234567890123456789012345678901234567890",
  2399. "application/octet-stream");
  2400. })
  2401. .Post("/compress-multipart",
  2402. [&](const Request &req, Response & /*res*/) {
  2403. EXPECT_EQ(2u, req.files.size());
  2404. ASSERT_TRUE(!req.has_file("???"));
  2405. {
  2406. const auto &file = req.get_file_value("key1");
  2407. EXPECT_TRUE(file.filename.empty());
  2408. EXPECT_EQ("test", file.content);
  2409. }
  2410. {
  2411. const auto &file = req.get_file_value("key2");
  2412. EXPECT_TRUE(file.filename.empty());
  2413. EXPECT_EQ("--abcdefg123", file.content);
  2414. }
  2415. })
  2416. #endif
  2417. ;
  2418. persons_["john"] = "programmer";
  2419. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2420. svr_.wait_until_ready();
  2421. }
  2422. virtual void TearDown() {
  2423. svr_.stop();
  2424. if (!request_threads_.empty()) {
  2425. std::this_thread::sleep_for(std::chrono::seconds(1));
  2426. for (auto &t : request_threads_) {
  2427. t.join();
  2428. }
  2429. }
  2430. t_.join();
  2431. }
  2432. map<string, string> persons_;
  2433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2434. SSLClient cli_;
  2435. SSLServer svr_;
  2436. #else
  2437. Client cli_;
  2438. Server svr_;
  2439. #endif
  2440. thread t_;
  2441. std::vector<thread> request_threads_;
  2442. };
  2443. TEST_F(ServerTest, GetMethod200) {
  2444. auto res = cli_.Get("/hi");
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ("HTTP/1.1", res->version);
  2447. EXPECT_EQ(StatusCode::OK_200, res->status);
  2448. EXPECT_EQ("OK", res->reason);
  2449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2450. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. }
  2453. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2454. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2455. ASSERT_TRUE(res);
  2456. EXPECT_EQ("HTTP/1.1", res->version);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2459. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2460. EXPECT_EQ("Hello World!", res->body);
  2461. }
  2462. TEST_F(ServerTest, GetMethod302) {
  2463. auto res = cli_.Get("/");
  2464. ASSERT_TRUE(res);
  2465. EXPECT_EQ(StatusCode::Found_302, res->status);
  2466. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2467. }
  2468. TEST_F(ServerTest, GetMethod302Redirect) {
  2469. cli_.set_follow_location(true);
  2470. auto res = cli_.Get("/");
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::OK_200, res->status);
  2473. EXPECT_EQ("Hello World!", res->body);
  2474. EXPECT_EQ("/hi", res->location);
  2475. }
  2476. TEST_F(ServerTest, GetMethod404) {
  2477. auto res = cli_.Get("/invalid");
  2478. ASSERT_TRUE(res);
  2479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2480. }
  2481. TEST_F(ServerTest, HeadMethod200) {
  2482. auto res = cli_.Head("/hi");
  2483. ASSERT_TRUE(res);
  2484. EXPECT_EQ(StatusCode::OK_200, res->status);
  2485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2486. EXPECT_TRUE(res->body.empty());
  2487. }
  2488. TEST_F(ServerTest, HeadMethod200Static) {
  2489. auto res = cli_.Head("/mount/dir/index.html");
  2490. ASSERT_TRUE(res);
  2491. EXPECT_EQ(StatusCode::OK_200, res->status);
  2492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2493. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2494. EXPECT_TRUE(res->body.empty());
  2495. }
  2496. TEST_F(ServerTest, HeadMethod404) {
  2497. auto res = cli_.Head("/invalid");
  2498. ASSERT_TRUE(res);
  2499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2500. EXPECT_TRUE(res->body.empty());
  2501. }
  2502. TEST_F(ServerTest, GetMethodPersonJohn) {
  2503. auto res = cli_.Get("/person/john");
  2504. ASSERT_TRUE(res);
  2505. EXPECT_EQ(StatusCode::OK_200, res->status);
  2506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2507. EXPECT_EQ("programmer", res->body);
  2508. }
  2509. TEST_F(ServerTest, PostMethod1) {
  2510. auto res = cli_.Get("/person/john1");
  2511. ASSERT_TRUE(res);
  2512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2513. res = cli_.Post("/person", "name=john1&note=coder",
  2514. "application/x-www-form-urlencoded");
  2515. ASSERT_TRUE(res);
  2516. ASSERT_EQ(StatusCode::OK_200, res->status);
  2517. res = cli_.Get("/person/john1");
  2518. ASSERT_TRUE(res);
  2519. ASSERT_EQ(StatusCode::OK_200, res->status);
  2520. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2521. ASSERT_EQ("coder", res->body);
  2522. }
  2523. TEST_F(ServerTest, PostMethod2) {
  2524. auto res = cli_.Get("/person/john2");
  2525. ASSERT_TRUE(res);
  2526. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2527. Params params;
  2528. params.emplace("name", "john2");
  2529. params.emplace("note", "coder");
  2530. res = cli_.Post("/person", params);
  2531. ASSERT_TRUE(res);
  2532. ASSERT_EQ(StatusCode::OK_200, res->status);
  2533. res = cli_.Get("/person/john2");
  2534. ASSERT_TRUE(res);
  2535. ASSERT_EQ(StatusCode::OK_200, res->status);
  2536. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2537. ASSERT_EQ("coder", res->body);
  2538. }
  2539. TEST_F(ServerTest, PutMethod3) {
  2540. auto res = cli_.Get("/person/john3");
  2541. ASSERT_TRUE(res);
  2542. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2543. Params params;
  2544. params.emplace("name", "john3");
  2545. params.emplace("note", "coder");
  2546. res = cli_.Put("/person", params);
  2547. ASSERT_TRUE(res);
  2548. ASSERT_EQ(StatusCode::OK_200, res->status);
  2549. res = cli_.Get("/person/john3");
  2550. ASSERT_TRUE(res);
  2551. ASSERT_EQ(StatusCode::OK_200, res->status);
  2552. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2553. ASSERT_EQ("coder", res->body);
  2554. }
  2555. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2556. Params params;
  2557. params.emplace("json", JSON_DATA);
  2558. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2559. ASSERT_TRUE(res);
  2560. ASSERT_EQ(StatusCode::OK_200, res->status);
  2561. ASSERT_EQ(JSON_DATA, res->body);
  2562. }
  2563. TEST_F(ServerTest, PostEmptyContent) {
  2564. auto res = cli_.Post("/empty", "", "text/plain");
  2565. ASSERT_TRUE(res);
  2566. ASSERT_EQ(StatusCode::OK_200, res->status);
  2567. ASSERT_EQ("empty", res->body);
  2568. }
  2569. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2570. auto res = cli_.Post("/empty-no-content-type");
  2571. ASSERT_TRUE(res);
  2572. ASSERT_EQ(StatusCode::OK_200, res->status);
  2573. ASSERT_EQ("empty-no-content-type", res->body);
  2574. }
  2575. TEST_F(ServerTest, PostPathOnly) {
  2576. auto res = cli_.Post("/path-only");
  2577. ASSERT_TRUE(res);
  2578. ASSERT_EQ(StatusCode::OK_200, res->status);
  2579. ASSERT_EQ("path-only", res->body);
  2580. }
  2581. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2582. auto res = cli_.Post("/path-headers-only",
  2583. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2584. ASSERT_TRUE(res);
  2585. ASSERT_EQ(StatusCode::OK_200, res->status);
  2586. ASSERT_EQ("path-headers-only", res->body);
  2587. }
  2588. TEST_F(ServerTest, PostLarge) {
  2589. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2590. ASSERT_TRUE(res);
  2591. ASSERT_EQ(StatusCode::OK_200, res->status);
  2592. EXPECT_EQ(LARGE_DATA, res->body);
  2593. }
  2594. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2595. auto res = cli_.Put("/empty-no-content-type");
  2596. ASSERT_TRUE(res);
  2597. ASSERT_EQ(StatusCode::OK_200, res->status);
  2598. ASSERT_EQ("empty-no-content-type", res->body);
  2599. }
  2600. TEST_F(ServerTest, GetMethodDir) {
  2601. auto res = cli_.Get("/dir/");
  2602. ASSERT_TRUE(res);
  2603. EXPECT_EQ(StatusCode::OK_200, res->status);
  2604. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2605. auto body = R"(<html>
  2606. <head>
  2607. </head>
  2608. <body>
  2609. <a href="/dir/test.html">Test</a>
  2610. <a href="/hi">hi</a>
  2611. </body>
  2612. </html>
  2613. )";
  2614. EXPECT_EQ(body, res->body);
  2615. }
  2616. TEST_F(ServerTest, GetMethodDirTest) {
  2617. auto res = cli_.Get("/dir/test.html");
  2618. ASSERT_TRUE(res);
  2619. EXPECT_EQ(StatusCode::OK_200, res->status);
  2620. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2621. EXPECT_EQ("test.html", res->body);
  2622. }
  2623. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2624. auto res = cli_.Get("/dir/../dir/test.html");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2628. EXPECT_EQ("test.html", res->body);
  2629. }
  2630. TEST_F(ServerTest, GetMethodInvalidPath) {
  2631. auto res = cli_.Get("/dir/../test.html");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2634. }
  2635. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2636. auto res = cli_.Get("/../www/dir/test.html");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2639. }
  2640. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2641. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2642. ASSERT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2644. }
  2645. TEST_F(ServerTest, GetMethodDirMountTest) {
  2646. auto res = cli_.Get("/mount/dir/test.html");
  2647. ASSERT_TRUE(res);
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2650. EXPECT_EQ("test.html", res->body);
  2651. }
  2652. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2653. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2657. EXPECT_EQ("test.html", res->body);
  2658. }
  2659. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2660. auto res = cli_.Get("/mount/dir/../test.html");
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2663. }
  2664. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2665. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2668. }
  2669. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2670. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2671. ASSERT_TRUE(res);
  2672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2673. }
  2674. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2675. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2676. ASSERT_TRUE(res);
  2677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2678. }
  2679. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2680. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2681. ASSERT_TRUE(res);
  2682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2683. }
  2684. TEST_F(ServerTest, PostMethod303) {
  2685. auto res = cli_.Post("/1", "body", "text/plain");
  2686. ASSERT_TRUE(res);
  2687. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2688. EXPECT_EQ("/2", res->get_header_value("Location"));
  2689. }
  2690. TEST_F(ServerTest, PostMethod303Redirect) {
  2691. cli_.set_follow_location(true);
  2692. auto res = cli_.Post("/1", "body", "text/plain");
  2693. ASSERT_TRUE(res);
  2694. EXPECT_EQ(StatusCode::OK_200, res->status);
  2695. EXPECT_EQ("redirected.", res->body);
  2696. EXPECT_EQ("/2", res->location);
  2697. }
  2698. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2699. auto res = cli_.Get("/dir/test.abcde");
  2700. ASSERT_TRUE(res);
  2701. EXPECT_EQ(StatusCode::OK_200, res->status);
  2702. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2703. EXPECT_EQ("abcde", res->body);
  2704. }
  2705. TEST_F(ServerTest, StaticFileRange) {
  2706. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2707. ASSERT_TRUE(res);
  2708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2709. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2710. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2711. EXPECT_EQ(true, res->has_header("Content-Range"));
  2712. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2713. EXPECT_EQ(std::string("cd"), res->body);
  2714. }
  2715. TEST_F(ServerTest, StaticFileRanges) {
  2716. auto res =
  2717. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2718. ASSERT_TRUE(res);
  2719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2720. EXPECT_TRUE(
  2721. res->get_header_value("Content-Type")
  2722. .find(
  2723. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2724. 0);
  2725. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2726. }
  2727. TEST_F(ServerTest, StaticFileRangeHead) {
  2728. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2729. ASSERT_TRUE(res);
  2730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2731. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2732. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2733. EXPECT_EQ(true, res->has_header("Content-Range"));
  2734. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2735. }
  2736. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2737. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2738. ASSERT_TRUE(res);
  2739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2741. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2742. EXPECT_EQ(true, res->has_header("Content-Range"));
  2743. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2744. res->get_header_value("Content-Range"));
  2745. EXPECT_EQ("LAST\n", res->body);
  2746. }
  2747. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2748. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2749. ASSERT_TRUE(res);
  2750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2752. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2753. EXPECT_EQ(true, res->has_header("Content-Range"));
  2754. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2755. }
  2756. TEST_F(ServerTest, StaticFileBigFile) {
  2757. auto res = cli_.Get("/dir/1MB.txt");
  2758. ASSERT_TRUE(res);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2761. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2762. }
  2763. TEST_F(ServerTest, InvalidBaseDirMount) {
  2764. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2765. }
  2766. TEST_F(ServerTest, Binary) {
  2767. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2768. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2769. "application/octet-stream");
  2770. ASSERT_TRUE(res);
  2771. ASSERT_EQ(StatusCode::OK_200, res->status);
  2772. ASSERT_EQ(4U, res->body.size());
  2773. res = cli_.Put("/binary", binary.data(), binary.size(),
  2774. "application/octet-stream");
  2775. ASSERT_TRUE(res);
  2776. ASSERT_EQ(StatusCode::OK_200, res->status);
  2777. ASSERT_EQ(4U, res->body.size());
  2778. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2779. "application/octet-stream");
  2780. ASSERT_TRUE(res);
  2781. ASSERT_EQ(StatusCode::OK_200, res->status);
  2782. ASSERT_EQ(4U, res->body.size());
  2783. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2784. "application/octet-stream");
  2785. ASSERT_TRUE(res);
  2786. ASSERT_EQ(StatusCode::OK_200, res->status);
  2787. ASSERT_EQ(4U, res->body.size());
  2788. }
  2789. TEST_F(ServerTest, BinaryString) {
  2790. auto binary = std::string("\x00\x01\x02\x03", 4);
  2791. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2792. ASSERT_TRUE(res);
  2793. ASSERT_EQ(StatusCode::OK_200, res->status);
  2794. ASSERT_EQ(4U, res->body.size());
  2795. res = cli_.Put("/binary", binary, "application/octet-stream");
  2796. ASSERT_TRUE(res);
  2797. ASSERT_EQ(StatusCode::OK_200, res->status);
  2798. ASSERT_EQ(4U, res->body.size());
  2799. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2800. ASSERT_TRUE(res);
  2801. ASSERT_EQ(StatusCode::OK_200, res->status);
  2802. ASSERT_EQ(4U, res->body.size());
  2803. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2804. ASSERT_TRUE(res);
  2805. ASSERT_EQ(StatusCode::OK_200, res->status);
  2806. ASSERT_EQ(4U, res->body.size());
  2807. }
  2808. TEST_F(ServerTest, EmptyRequest) {
  2809. auto res = cli_.Get("");
  2810. ASSERT_TRUE(!res);
  2811. EXPECT_EQ(Error::Connection, res.error());
  2812. }
  2813. TEST_F(ServerTest, LongRequest) {
  2814. std::string request;
  2815. for (size_t i = 0; i < 545; i++) {
  2816. request += "/TooLongRequest";
  2817. }
  2818. request += "OK";
  2819. auto res = cli_.Get(request.c_str());
  2820. ASSERT_TRUE(res);
  2821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2822. }
  2823. TEST_F(ServerTest, TooLongRequest) {
  2824. std::string request;
  2825. for (size_t i = 0; i < 545; i++) {
  2826. request += "/TooLongRequest";
  2827. }
  2828. request += "_NG";
  2829. auto res = cli_.Get(request.c_str());
  2830. ASSERT_TRUE(res);
  2831. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2832. }
  2833. TEST_F(ServerTest, LongHeader) {
  2834. Request req;
  2835. req.method = "GET";
  2836. req.path = "/hi";
  2837. std::string host_and_port;
  2838. host_and_port += HOST;
  2839. host_and_port += ":";
  2840. host_and_port += std::to_string(PORT);
  2841. req.headers.emplace("Host", host_and_port.c_str());
  2842. req.headers.emplace("Accept", "*/*");
  2843. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2844. req.headers.emplace(
  2845. "Header-Name",
  2846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2874. "@@@@@@@@@@@@@@@@");
  2875. auto res = std::make_shared<Response>();
  2876. auto error = Error::Success;
  2877. auto ret = cli_.send(req, *res, error);
  2878. ASSERT_TRUE(ret);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. TEST_F(ServerTest, LongQueryValue) {
  2882. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2883. ASSERT_TRUE(res);
  2884. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2885. }
  2886. TEST_F(ServerTest, TooLongHeader) {
  2887. Request req;
  2888. req.method = "GET";
  2889. req.path = "/hi";
  2890. std::string host_and_port;
  2891. host_and_port += HOST;
  2892. host_and_port += ":";
  2893. host_and_port += std::to_string(PORT);
  2894. req.headers.emplace("Host", host_and_port.c_str());
  2895. req.headers.emplace("Accept", "*/*");
  2896. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2897. req.headers.emplace(
  2898. "Header-Name",
  2899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2927. "@@@@@@@@@@@@@@@@@");
  2928. auto res = std::make_shared<Response>();
  2929. auto error = Error::Success;
  2930. auto ret = cli_.send(req, *res, error);
  2931. ASSERT_TRUE(ret);
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. TEST_F(ServerTest, PercentEncoding) {
  2935. auto res = cli_.Get("/e%6edwith%");
  2936. ASSERT_TRUE(res);
  2937. EXPECT_EQ(StatusCode::OK_200, res->status);
  2938. }
  2939. TEST_F(ServerTest, PercentEncodingUnicode) {
  2940. auto res = cli_.Get("/e%u006edwith%");
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST_F(ServerTest, InvalidPercentEncoding) {
  2945. auto res = cli_.Get("/%endwith%");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2948. }
  2949. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2950. auto res = cli_.Get("/%uendwith%");
  2951. ASSERT_TRUE(res);
  2952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2953. }
  2954. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2955. auto res = cli_.Get("/hello?aaa=bbb%");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2958. }
  2959. TEST_F(ServerTest, PlusSignEncoding) {
  2960. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2961. ASSERT_TRUE(res);
  2962. EXPECT_EQ(StatusCode::OK_200, res->status);
  2963. EXPECT_EQ("a +b", res->body);
  2964. }
  2965. TEST_F(ServerTest, MultipartFormData) {
  2966. MultipartFormDataItems items = {
  2967. {"text1", "text default", "", ""},
  2968. {"text2", "aωb", "", ""},
  2969. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2970. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2971. {"file3", "", "", "application/octet-stream"},
  2972. {"file4", "", "", " application/json tmp-string "}};
  2973. auto res = cli_.Post("/multipart", items);
  2974. ASSERT_TRUE(res);
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. }
  2977. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2978. MultipartFormDataItems items = {
  2979. {"text", "default text", "", ""},
  2980. {"multi_text1", "aaaaa", "", ""},
  2981. {"multi_text1", "bbbbb", "", ""},
  2982. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2983. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2984. "application/json"},
  2985. };
  2986. auto res = cli_.Post("/multipart/multi_file_values", items);
  2987. ASSERT_TRUE(res);
  2988. EXPECT_EQ(StatusCode::OK_200, res->status);
  2989. }
  2990. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2991. auto res = cli_.Get("/hi");
  2992. ASSERT_TRUE(res);
  2993. EXPECT_EQ(StatusCode::OK_200, res->status);
  2994. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2995. EXPECT_EQ("Hello World!", res->body);
  2996. }
  2997. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2998. Request req;
  2999. req.method = "POST";
  3000. req.path = "/chunked";
  3001. std::string host_and_port;
  3002. host_and_port += HOST;
  3003. host_and_port += ":";
  3004. host_and_port += std::to_string(PORT);
  3005. req.headers.emplace("Host", host_and_port.c_str());
  3006. req.headers.emplace("Accept", "*/*");
  3007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3008. req.headers.emplace("Content-Type", "text/plain");
  3009. req.headers.emplace("Content-Length", "0");
  3010. req.headers.emplace(
  3011. "Transfer-Encoding",
  3012. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3013. // Client does not chunk, so make a chunked body manually.
  3014. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3015. auto res = std::make_shared<Response>();
  3016. auto error = Error::Success;
  3017. auto ret = cli_.send(req, *res, error);
  3018. ASSERT_TRUE(ret);
  3019. EXPECT_EQ(StatusCode::OK_200, res->status);
  3020. }
  3021. TEST_F(ServerTest, GetStreamed2) {
  3022. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3023. ASSERT_TRUE(res);
  3024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3025. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3026. EXPECT_EQ(true, res->has_header("Content-Range"));
  3027. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3028. EXPECT_EQ(std::string("ab"), res->body);
  3029. }
  3030. TEST_F(ServerTest, GetStreamed) {
  3031. auto res = cli_.Get("/streamed");
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3035. EXPECT_EQ(std::string("aaabbb"), res->body);
  3036. }
  3037. TEST_F(ServerTest, GetStreamedWithRange1) {
  3038. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3041. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3042. EXPECT_EQ(true, res->has_header("Content-Range"));
  3043. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3044. EXPECT_EQ(std::string("def"), res->body);
  3045. }
  3046. TEST_F(ServerTest, GetStreamedWithRange2) {
  3047. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3048. ASSERT_TRUE(res);
  3049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3050. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3051. EXPECT_EQ(true, res->has_header("Content-Range"));
  3052. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3053. EXPECT_EQ(std::string("bcdefg"), res->body);
  3054. }
  3055. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3056. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3057. ASSERT_TRUE(res);
  3058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3059. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3060. EXPECT_EQ(true, res->has_header("Content-Range"));
  3061. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3062. EXPECT_EQ(std::string("efg"), res->body);
  3063. }
  3064. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3065. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3066. ASSERT_TRUE(res);
  3067. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3068. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3069. EXPECT_EQ(false, res->has_header("Content-Range"));
  3070. EXPECT_EQ(0U, res->body.size());
  3071. }
  3072. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3073. auto res = cli_.Get("/streamed-with-range",
  3074. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3075. "92233720368547758079223372036854775807"}});
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3078. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3079. EXPECT_EQ(false, res->has_header("Content-Range"));
  3080. EXPECT_EQ(0U, res->body.size());
  3081. }
  3082. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3083. auto res = cli_.Get(
  3084. "/with-range",
  3085. {{"Range",
  3086. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())}});
  3087. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3088. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3089. EXPECT_EQ(false, res->has_header("Content-Range"));
  3090. EXPECT_EQ(0U, res->body.size());
  3091. }
  3092. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3093. auto res =
  3094. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3095. ASSERT_TRUE(res);
  3096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3097. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3098. EXPECT_EQ(false, res->has_header("Content-Range"));
  3099. EXPECT_EQ(267U, res->body.size());
  3100. }
  3101. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3102. Ranges ranges;
  3103. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3104. ranges.emplace_back(0, -1);
  3105. }
  3106. auto res =
  3107. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3108. ASSERT_TRUE(res);
  3109. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3110. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3111. EXPECT_EQ(false, res->has_header("Content-Range"));
  3112. EXPECT_EQ(0U, res->body.size());
  3113. }
  3114. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3115. auto res = cli_.Get("/streamed-with-range?error",
  3116. {{make_range_header({{0, -1}, {0, -1}})}});
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3119. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3120. EXPECT_EQ(false, res->has_header("Content-Range"));
  3121. EXPECT_EQ(0U, res->body.size());
  3122. }
  3123. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3124. auto res = cli_.Get("/streamed-with-range?error",
  3125. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3129. EXPECT_EQ(false, res->has_header("Content-Range"));
  3130. EXPECT_EQ(0U, res->body.size());
  3131. }
  3132. TEST_F(ServerTest, GetStreamedEndless) {
  3133. uint64_t offset = 0;
  3134. auto res = cli_.Get("/streamed-cancel",
  3135. [&](const char * /*data*/, uint64_t data_length) {
  3136. if (offset < 100) {
  3137. offset += data_length;
  3138. return true;
  3139. }
  3140. return false;
  3141. });
  3142. ASSERT_TRUE(!res);
  3143. EXPECT_EQ(Error::Canceled, res.error());
  3144. }
  3145. TEST_F(ServerTest, ClientStop) {
  3146. std::atomic_size_t count{4};
  3147. std::vector<std::thread> threads;
  3148. for (auto i = count.load(); i != 0; --i) {
  3149. threads.emplace_back([&]() {
  3150. auto res = cli_.Get("/streamed-cancel",
  3151. [&](const char *, uint64_t) { return true; });
  3152. --count;
  3153. ASSERT_TRUE(!res);
  3154. EXPECT_TRUE(res.error() == Error::Canceled ||
  3155. res.error() == Error::Read || res.error() == Error::Write);
  3156. });
  3157. }
  3158. std::this_thread::sleep_for(std::chrono::seconds(2));
  3159. while (count != 0) {
  3160. cli_.stop();
  3161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3162. }
  3163. for (auto &t : threads) {
  3164. t.join();
  3165. }
  3166. }
  3167. TEST_F(ServerTest, GetWithRange1) {
  3168. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  3169. ASSERT_TRUE(res);
  3170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3171. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3172. EXPECT_EQ(true, res->has_header("Content-Range"));
  3173. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3174. EXPECT_EQ(std::string("def"), res->body);
  3175. }
  3176. TEST_F(ServerTest, GetWithRange2) {
  3177. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3180. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3181. EXPECT_EQ(true, res->has_header("Content-Range"));
  3182. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3183. EXPECT_EQ(std::string("bcdefg"), res->body);
  3184. }
  3185. TEST_F(ServerTest, GetWithRange3) {
  3186. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  3187. ASSERT_TRUE(res);
  3188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3189. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3190. EXPECT_EQ(true, res->has_header("Content-Range"));
  3191. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3192. EXPECT_EQ(std::string("a"), res->body);
  3193. }
  3194. TEST_F(ServerTest, GetWithRange4) {
  3195. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3198. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3199. EXPECT_EQ(true, res->has_header("Content-Range"));
  3200. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3201. EXPECT_EQ(std::string("fg"), res->body);
  3202. }
  3203. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3204. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3205. ASSERT_TRUE(res);
  3206. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3207. }
  3208. TEST_F(ServerTest, GetWithRangeMultipart) {
  3209. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3213. EXPECT_EQ(false, res->has_header("Content-Range"));
  3214. EXPECT_EQ(267U, res->body.size());
  3215. }
  3216. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3217. auto res =
  3218. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3221. }
  3222. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3223. auto res = cli_.Get("/with-range-customized-response",
  3224. {{make_range_header({{1, 2}})}});
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3227. EXPECT_EQ(true, res->has_header("Content-Length"));
  3228. EXPECT_EQ(false, res->has_header("Content-Range"));
  3229. EXPECT_EQ(JSON_DATA, res->body);
  3230. }
  3231. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3232. auto res = cli_.Get("/with-range-customized-response",
  3233. {{make_range_header({{1, 2}, {4, 5}})}});
  3234. ASSERT_TRUE(res);
  3235. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3236. EXPECT_EQ(true, res->has_header("Content-Length"));
  3237. EXPECT_EQ(false, res->has_header("Content-Range"));
  3238. EXPECT_EQ(JSON_DATA, res->body);
  3239. }
  3240. TEST_F(ServerTest, Issue1772) {
  3241. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetStreamedChunked) {
  3246. auto res = cli_.Get("/streamed-chunked");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::OK_200, res->status);
  3249. EXPECT_EQ(std::string("123456789"), res->body);
  3250. }
  3251. TEST_F(ServerTest, GetStreamedChunked2) {
  3252. auto res = cli_.Get("/streamed-chunked2");
  3253. ASSERT_TRUE(res);
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. EXPECT_EQ(std::string("123456789"), res->body);
  3256. }
  3257. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3258. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::OK_200, res->status);
  3261. EXPECT_EQ(std::string("123456789"), res->body);
  3262. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3263. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3264. }
  3265. TEST_F(ServerTest, LargeChunkedPost) {
  3266. Request req;
  3267. req.method = "POST";
  3268. req.path = "/large-chunked";
  3269. std::string host_and_port;
  3270. host_and_port += HOST;
  3271. host_and_port += ":";
  3272. host_and_port += std::to_string(PORT);
  3273. req.headers.emplace("Host", host_and_port.c_str());
  3274. req.headers.emplace("Accept", "*/*");
  3275. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3276. req.headers.emplace("Content-Type", "text/plain");
  3277. req.headers.emplace("Content-Length", "0");
  3278. req.headers.emplace("Transfer-Encoding", "chunked");
  3279. std::string long_string(30 * 1024u, 'a');
  3280. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3281. // Attempt to make a large enough post to exceed OS buffers, to test that
  3282. // the server handles short reads if the full chunk data isn't available.
  3283. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3284. auto res = std::make_shared<Response>();
  3285. auto error = Error::Success;
  3286. auto ret = cli_.send(req, *res, error);
  3287. ASSERT_TRUE(ret);
  3288. EXPECT_EQ(StatusCode::OK_200, res->status);
  3289. }
  3290. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3291. auto res = cli_.Get("/remote_addr");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3295. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3296. }
  3297. TEST_F(ServerTest, GetMethodLocalAddr) {
  3298. auto res = cli_.Get("/local_addr");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3302. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3303. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3304. }
  3305. TEST_F(ServerTest, HTTPResponseSplitting) {
  3306. auto res = cli_.Get("/http_response_splitting");
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(StatusCode::OK_200, res->status);
  3309. }
  3310. TEST_F(ServerTest, SlowRequest) {
  3311. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3312. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3313. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3314. }
  3315. #if 0
  3316. TEST_F(ServerTest, SlowPost) {
  3317. char buffer[64 * 1024];
  3318. memset(buffer, 0x42, sizeof(buffer));
  3319. auto res = cli_.Post(
  3320. "/slowpost", 64 * 1024 * 1024,
  3321. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3322. auto ret = sink.write(buffer, sizeof(buffer));
  3323. EXPECT_TRUE(ret);
  3324. return true;
  3325. },
  3326. "text/plain");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::OK_200, res->status);
  3329. }
  3330. TEST_F(ServerTest, SlowPostFail) {
  3331. char buffer[64 * 1024];
  3332. memset(buffer, 0x42, sizeof(buffer));
  3333. cli_.set_write_timeout(std::chrono::seconds(0));
  3334. auto res = cli_.Post(
  3335. "/slowpost", 64 * 1024 * 1024,
  3336. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3337. sink.write(buffer, sizeof(buffer));
  3338. return true;
  3339. },
  3340. "text/plain");
  3341. ASSERT_TRUE(!res);
  3342. EXPECT_EQ(Error::Write, res.error());
  3343. }
  3344. #endif
  3345. TEST_F(ServerTest, Put) {
  3346. auto res = cli_.Put("/put", "PUT", "text/plain");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::OK_200, res->status);
  3349. EXPECT_EQ("PUT", res->body);
  3350. }
  3351. TEST_F(ServerTest, PutWithContentProvider) {
  3352. auto res = cli_.Put(
  3353. "/put", 3,
  3354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3355. sink.os << "PUT";
  3356. return true;
  3357. },
  3358. "text/plain");
  3359. ASSERT_TRUE(res);
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("PUT", res->body);
  3362. }
  3363. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3364. auto res = cli_.Post(
  3365. "/post", 42,
  3366. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3367. return false;
  3368. },
  3369. "text/plain");
  3370. ASSERT_TRUE(!res);
  3371. EXPECT_EQ(Error::Canceled, res.error());
  3372. }
  3373. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3374. auto res = cli_.Put(
  3375. "/put",
  3376. [](size_t /*offset*/, DataSink &sink) {
  3377. sink.os << "PUT";
  3378. sink.done();
  3379. return true;
  3380. },
  3381. "text/plain");
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(StatusCode::OK_200, res->status);
  3384. EXPECT_EQ("PUT", res->body);
  3385. }
  3386. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3387. auto res = cli_.Post(
  3388. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3389. "text/plain");
  3390. ASSERT_TRUE(!res);
  3391. EXPECT_EQ(Error::Canceled, res.error());
  3392. }
  3393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3394. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3395. cli_.set_compress(true);
  3396. auto res = cli_.Put(
  3397. "/put", 3,
  3398. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3399. sink.os << "PUT";
  3400. return true;
  3401. },
  3402. "text/plain");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("PUT", res->body);
  3406. }
  3407. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3408. cli_.set_compress(true);
  3409. auto res = cli_.Post(
  3410. "/post", 42,
  3411. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3412. return false;
  3413. },
  3414. "text/plain");
  3415. ASSERT_TRUE(!res);
  3416. EXPECT_EQ(Error::Canceled, res.error());
  3417. }
  3418. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3419. cli_.set_compress(true);
  3420. auto res = cli_.Put(
  3421. "/put",
  3422. [](size_t /*offset*/, DataSink &sink) {
  3423. sink.os << "PUT";
  3424. sink.done();
  3425. return true;
  3426. },
  3427. "text/plain");
  3428. ASSERT_TRUE(res);
  3429. EXPECT_EQ(StatusCode::OK_200, res->status);
  3430. EXPECT_EQ("PUT", res->body);
  3431. }
  3432. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3433. cli_.set_compress(true);
  3434. auto res = cli_.Post(
  3435. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3436. "text/plain");
  3437. ASSERT_TRUE(!res);
  3438. EXPECT_EQ(Error::Canceled, res.error());
  3439. }
  3440. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3441. cli_.set_compress(true);
  3442. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3443. ASSERT_TRUE(res);
  3444. EXPECT_EQ(StatusCode::OK_200, res->status);
  3445. EXPECT_EQ(LARGE_DATA, res->body);
  3446. }
  3447. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3448. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3449. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3450. Client cli(s.c_str());
  3451. cli.enable_server_certificate_verification(false);
  3452. #else
  3453. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3454. Client cli(s.c_str());
  3455. #endif
  3456. cli.set_compress(true);
  3457. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ(LARGE_DATA, res->body);
  3461. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  3462. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3463. }
  3464. TEST_F(ServerTest, PutContentWithDeflate) {
  3465. cli_.set_compress(false);
  3466. Headers headers;
  3467. headers.emplace("Content-Encoding", "deflate");
  3468. // PUT in deflate format:
  3469. auto res = cli_.Put("/put", headers,
  3470. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3471. ASSERT_TRUE(res);
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("PUT", res->body);
  3474. }
  3475. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3476. Headers headers;
  3477. headers.emplace("Accept-Encoding", "gzip, deflate");
  3478. auto res = cli_.Get("/streamed-chunked", headers);
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ(StatusCode::OK_200, res->status);
  3481. EXPECT_EQ(std::string("123456789"), res->body);
  3482. }
  3483. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3484. Headers headers;
  3485. headers.emplace("Accept-Encoding", "gzip, deflate");
  3486. auto res = cli_.Get("/streamed-chunked2", headers);
  3487. ASSERT_TRUE(res);
  3488. EXPECT_EQ(StatusCode::OK_200, res->status);
  3489. EXPECT_EQ(std::string("123456789"), res->body);
  3490. }
  3491. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3492. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. }
  3496. TEST(GzipDecompressor, ChunkedDecompression) {
  3497. std::string data;
  3498. for (size_t i = 0; i < 32 * 1024; ++i) {
  3499. data.push_back(static_cast<char>('a' + i % 26));
  3500. }
  3501. std::string compressed_data;
  3502. {
  3503. httplib::detail::gzip_compressor compressor;
  3504. bool result = compressor.compress(
  3505. data.data(), data.size(),
  3506. /*last=*/true,
  3507. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3508. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3509. compressed_data_size);
  3510. return true;
  3511. });
  3512. ASSERT_TRUE(result);
  3513. }
  3514. std::string decompressed_data;
  3515. {
  3516. httplib::detail::gzip_decompressor decompressor;
  3517. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3518. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3519. size_t chunk_size = 130;
  3520. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3521. chunk_begin += chunk_size) {
  3522. size_t current_chunk_size =
  3523. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3524. bool result = decompressor.decompress(
  3525. compressed_data.data() + chunk_begin, current_chunk_size,
  3526. [&](const char *decompressed_data_chunk,
  3527. size_t decompressed_data_chunk_size) {
  3528. decompressed_data.insert(decompressed_data.size(),
  3529. decompressed_data_chunk,
  3530. decompressed_data_chunk_size);
  3531. return true;
  3532. });
  3533. ASSERT_TRUE(result);
  3534. }
  3535. }
  3536. ASSERT_EQ(data, decompressed_data);
  3537. }
  3538. TEST(GzipDecompressor, DeflateDecompression) {
  3539. std::string original_text = "Raw deflate without gzip";
  3540. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3541. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3542. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3543. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3544. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3545. std::string decompressed_data;
  3546. {
  3547. httplib::detail::gzip_decompressor decompressor;
  3548. bool result = decompressor.decompress(
  3549. compressed_data.data(), compressed_data.size(),
  3550. [&](const char *decompressed_data_chunk,
  3551. size_t decompressed_data_chunk_size) {
  3552. decompressed_data.insert(decompressed_data.size(),
  3553. decompressed_data_chunk,
  3554. decompressed_data_chunk_size);
  3555. return true;
  3556. });
  3557. ASSERT_TRUE(result);
  3558. }
  3559. ASSERT_EQ(original_text, decompressed_data);
  3560. }
  3561. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3562. std::string original_text = "Raw deflate without gzip";
  3563. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3564. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3565. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3566. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3567. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3568. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3569. std::string decompressed_data;
  3570. {
  3571. httplib::detail::gzip_decompressor decompressor;
  3572. bool result = decompressor.decompress(
  3573. compressed_data.data(), compressed_data.size(),
  3574. [&](const char *decompressed_data_chunk,
  3575. size_t decompressed_data_chunk_size) {
  3576. decompressed_data.insert(decompressed_data.size(),
  3577. decompressed_data_chunk,
  3578. decompressed_data_chunk_size);
  3579. return true;
  3580. });
  3581. ASSERT_TRUE(result);
  3582. }
  3583. ASSERT_EQ(original_text, decompressed_data);
  3584. }
  3585. #ifdef _WIN32
  3586. TEST(GzipDecompressor, LargeRandomData) {
  3587. // prepare large random data that is difficult to be compressed and is
  3588. // expected to have large size even when compressed
  3589. std::random_device seed_gen;
  3590. std::mt19937 random(seed_gen());
  3591. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3592. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3593. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3594. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3595. // compress data over 4GiB
  3596. std::string compressed_data;
  3597. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3598. httplib::detail::gzip_compressor compressor;
  3599. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3600. data.size() * sizeof(std::uint32_t), true,
  3601. [&](const char *data, size_t size) {
  3602. compressed_data.insert(
  3603. compressed_data.size(), data, size);
  3604. return true;
  3605. });
  3606. ASSERT_TRUE(result);
  3607. // FIXME: compressed data size is expected to be greater than 4GiB,
  3608. // but there is no guarantee
  3609. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3610. // decompress data over 4GiB
  3611. std::string decompressed_data;
  3612. decompressed_data.reserve(data_size);
  3613. httplib::detail::gzip_decompressor decompressor;
  3614. result = decompressor.decompress(
  3615. compressed_data.data(), compressed_data.size(),
  3616. [&](const char *data, size_t size) {
  3617. decompressed_data.insert(decompressed_data.size(), data, size);
  3618. return true;
  3619. });
  3620. ASSERT_TRUE(result);
  3621. // compare
  3622. ASSERT_EQ(data_size, decompressed_data.size());
  3623. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3624. 0);
  3625. }
  3626. #endif
  3627. #endif
  3628. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3629. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3630. Headers headers;
  3631. headers.emplace("Accept-Encoding", "br");
  3632. auto res = cli_.Get("/streamed-chunked", headers);
  3633. ASSERT_TRUE(res);
  3634. EXPECT_EQ(StatusCode::OK_200, res->status);
  3635. EXPECT_EQ(std::string("123456789"), res->body);
  3636. }
  3637. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3638. Headers headers;
  3639. headers.emplace("Accept-Encoding", "br");
  3640. auto res = cli_.Get("/streamed-chunked2", headers);
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ(std::string("123456789"), res->body);
  3644. }
  3645. #endif
  3646. TEST_F(ServerTest, Patch) {
  3647. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3648. ASSERT_TRUE(res);
  3649. EXPECT_EQ(StatusCode::OK_200, res->status);
  3650. EXPECT_EQ("PATCH", res->body);
  3651. }
  3652. TEST_F(ServerTest, Delete) {
  3653. auto res = cli_.Delete("/delete");
  3654. ASSERT_TRUE(res);
  3655. EXPECT_EQ(StatusCode::OK_200, res->status);
  3656. EXPECT_EQ("DELETE", res->body);
  3657. }
  3658. TEST_F(ServerTest, DeleteContentReceiver) {
  3659. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(StatusCode::OK_200, res->status);
  3662. EXPECT_EQ("content", res->body);
  3663. }
  3664. TEST_F(ServerTest, Options) {
  3665. auto res = cli_.Options("*");
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3669. EXPECT_TRUE(res->body.empty());
  3670. }
  3671. TEST_F(ServerTest, URL) {
  3672. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3673. ASSERT_TRUE(res);
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. }
  3676. TEST_F(ServerTest, ArrayParam) {
  3677. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST_F(ServerTest, NoMultipleHeaders) {
  3682. Headers headers = {{"Content-Length", "5"}};
  3683. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3684. "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::OK_200, res->status);
  3687. }
  3688. TEST_F(ServerTest, PostContentReceiver) {
  3689. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3690. ASSERT_TRUE(res);
  3691. ASSERT_EQ(StatusCode::OK_200, res->status);
  3692. ASSERT_EQ("content", res->body);
  3693. }
  3694. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3695. MultipartFormDataItems items = {
  3696. {"text1", "text default", "", ""},
  3697. {"text2", "aωb", "", ""},
  3698. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3699. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3700. {"file3", "", "", "application/octet-stream"},
  3701. };
  3702. auto res = cli_.Post("/content_receiver", items);
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. }
  3706. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3707. MultipartFormDataItems items = {
  3708. {"text1", "text default", "", ""},
  3709. {"text2", "aωb", "", ""},
  3710. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3711. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3712. {"file3", "", "", "application/octet-stream"},
  3713. };
  3714. auto boundary = std::string("+++++");
  3715. std::string body;
  3716. for (const auto &item : items) {
  3717. body += "--" + boundary + "\r\n";
  3718. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3719. if (!item.filename.empty()) {
  3720. body += "; filename=\"" + item.filename + "\"";
  3721. }
  3722. body += "\r\n";
  3723. if (!item.content_type.empty()) {
  3724. body += "Content-Type: " + item.content_type + "\r\n";
  3725. }
  3726. body += "\r\n";
  3727. body += item.content + "\r\n";
  3728. }
  3729. body += "--" + boundary + "--\r\n";
  3730. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3731. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. }
  3735. TEST_F(ServerTest, PostContentReceiverGzip) {
  3736. cli_.set_compress(true);
  3737. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3738. ASSERT_TRUE(res);
  3739. ASSERT_EQ(StatusCode::OK_200, res->status);
  3740. ASSERT_EQ("content", res->body);
  3741. }
  3742. TEST_F(ServerTest, PutContentReceiver) {
  3743. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3744. ASSERT_TRUE(res);
  3745. ASSERT_EQ(StatusCode::OK_200, res->status);
  3746. ASSERT_EQ("content", res->body);
  3747. }
  3748. TEST_F(ServerTest, PatchContentReceiver) {
  3749. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3750. ASSERT_TRUE(res);
  3751. ASSERT_EQ(StatusCode::OK_200, res->status);
  3752. ASSERT_EQ("content", res->body);
  3753. }
  3754. TEST_F(ServerTest, PostQueryStringAndBody) {
  3755. auto res =
  3756. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. }
  3760. TEST_F(ServerTest, HTTP2Magic) {
  3761. Request req;
  3762. req.method = "PRI";
  3763. req.path = "*";
  3764. req.body = "SM";
  3765. auto res = std::make_shared<Response>();
  3766. auto error = Error::Success;
  3767. auto ret = cli_.send(req, *res, error);
  3768. ASSERT_TRUE(ret);
  3769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3770. }
  3771. TEST_F(ServerTest, KeepAlive) {
  3772. auto res = cli_.Get("/hi");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::OK_200, res->status);
  3775. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3776. EXPECT_EQ("Hello World!", res->body);
  3777. res = cli_.Get("/hi");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3781. EXPECT_EQ("Hello World!", res->body);
  3782. res = cli_.Get("/hi");
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3786. EXPECT_EQ("Hello World!", res->body);
  3787. res = cli_.Get("/not-exist");
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3790. res = cli_.Post("/empty", "", "text/plain");
  3791. ASSERT_TRUE(res);
  3792. EXPECT_EQ(StatusCode::OK_200, res->status);
  3793. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3794. EXPECT_EQ("empty", res->body);
  3795. EXPECT_EQ("close", res->get_header_value("Connection"));
  3796. res = cli_.Post(
  3797. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3798. "text/plain");
  3799. ASSERT_TRUE(res);
  3800. EXPECT_EQ(StatusCode::OK_200, res->status);
  3801. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3802. EXPECT_EQ("empty", res->body);
  3803. cli_.set_keep_alive(false);
  3804. res = cli_.Get("/last-request");
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::OK_200, res->status);
  3807. EXPECT_EQ("close", res->get_header_value("Connection"));
  3808. }
  3809. TEST_F(ServerTest, TooManyRedirect) {
  3810. cli_.set_follow_location(true);
  3811. auto res = cli_.Get("/redirect/0");
  3812. ASSERT_TRUE(!res);
  3813. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3814. }
  3815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3816. TEST_F(ServerTest, Gzip) {
  3817. Headers headers;
  3818. headers.emplace("Accept-Encoding", "gzip, deflate");
  3819. auto res = cli_.Get("/compress", headers);
  3820. ASSERT_TRUE(res);
  3821. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3823. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3824. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3825. "7890123456789012345678901234567890",
  3826. res->body);
  3827. EXPECT_EQ(StatusCode::OK_200, res->status);
  3828. }
  3829. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3830. auto res = cli_.Get("/compress");
  3831. ASSERT_TRUE(res);
  3832. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3834. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3835. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3836. "7890123456789012345678901234567890",
  3837. res->body);
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. }
  3840. TEST_F(ServerTest, GzipWithContentReceiver) {
  3841. Headers headers;
  3842. headers.emplace("Accept-Encoding", "gzip, deflate");
  3843. std::string body;
  3844. auto res = cli_.Get("/compress", headers,
  3845. [&](const char *data, uint64_t data_length) {
  3846. EXPECT_EQ(100U, data_length);
  3847. body.append(data, data_length);
  3848. return true;
  3849. });
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3853. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3855. "7890123456789012345678901234567890",
  3856. body);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. }
  3859. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3860. Headers headers;
  3861. headers.emplace("Accept-Encoding", "gzip, deflate");
  3862. cli_.set_decompress(false);
  3863. auto res = cli_.Get("/compress", headers);
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3867. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3868. EXPECT_EQ(33U, res->body.size());
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3872. std::string body;
  3873. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3874. EXPECT_EQ(100U, data_length);
  3875. body.append(data, data_length);
  3876. return true;
  3877. });
  3878. ASSERT_TRUE(res);
  3879. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3880. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3881. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3882. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3883. "7890123456789012345678901234567890",
  3884. body);
  3885. EXPECT_EQ(StatusCode::OK_200, res->status);
  3886. }
  3887. TEST_F(ServerTest, NoGzip) {
  3888. Headers headers;
  3889. headers.emplace("Accept-Encoding", "gzip, deflate");
  3890. auto res = cli_.Get("/nocompress", headers);
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3893. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3894. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3895. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3896. "7890123456789012345678901234567890",
  3897. res->body);
  3898. EXPECT_EQ(StatusCode::OK_200, res->status);
  3899. }
  3900. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3901. Headers headers;
  3902. headers.emplace("Accept-Encoding", "gzip, deflate");
  3903. std::string body;
  3904. auto res = cli_.Get("/nocompress", headers,
  3905. [&](const char *data, uint64_t data_length) {
  3906. EXPECT_EQ(100U, data_length);
  3907. body.append(data, data_length);
  3908. return true;
  3909. });
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3912. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3913. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3914. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3915. "7890123456789012345678901234567890",
  3916. body);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, MultipartFormDataGzip) {
  3920. MultipartFormDataItems items = {
  3921. {"key1", "test", "", ""},
  3922. {"key2", "--abcdefg123", "", ""},
  3923. };
  3924. cli_.set_compress(true);
  3925. auto res = cli_.Post("/compress-multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. #endif
  3930. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3931. TEST_F(ServerTest, Brotli) {
  3932. Headers headers;
  3933. headers.emplace("Accept-Encoding", "br");
  3934. auto res = cli_.Get("/compress", headers);
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3938. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3940. "7890123456789012345678901234567890",
  3941. res->body);
  3942. EXPECT_EQ(StatusCode::OK_200, res->status);
  3943. }
  3944. #endif
  3945. // Sends a raw request to a server listening at HOST:PORT.
  3946. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3947. std::string *resp = nullptr) {
  3948. auto error = Error::Success;
  3949. auto client_sock = detail::create_client_socket(
  3950. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3951. /*connection_timeout_sec=*/5, 0,
  3952. /*read_timeout_sec=*/5, 0,
  3953. /*write_timeout_sec=*/5, 0, std::string(), error);
  3954. if (client_sock == INVALID_SOCKET) { return false; }
  3955. auto ret = detail::process_client_socket(
  3956. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3957. if (req.size() !=
  3958. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3959. return false;
  3960. }
  3961. char buf[512];
  3962. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3963. while (line_reader.getline()) {
  3964. if (resp) { *resp += line_reader.ptr(); }
  3965. }
  3966. return true;
  3967. });
  3968. detail::close_socket(client_sock);
  3969. return ret;
  3970. }
  3971. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3972. Server svr;
  3973. std::string header_value;
  3974. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3975. header_value = req.get_header_value("foo");
  3976. res.set_content("ok", "text/plain");
  3977. });
  3978. thread t = thread([&] { svr.listen(HOST, PORT); });
  3979. auto se = detail::scope_exit([&] {
  3980. svr.stop();
  3981. t.join();
  3982. ASSERT_FALSE(svr.is_running());
  3983. });
  3984. svr.wait_until_ready();
  3985. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3986. // like characters are not treated the same - use vertical tab and escape.
  3987. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3988. "foo: \t \v bar \x1B\t \r\n"
  3989. "Connection: close\r\n"
  3990. "\r\n";
  3991. ASSERT_TRUE(send_request(5, req));
  3992. EXPECT_EQ(header_value, "\v bar \x1B");
  3993. }
  3994. // Sends a raw request and verifies that there isn't a crash or exception.
  3995. static void test_raw_request(const std::string &req,
  3996. std::string *out = nullptr) {
  3997. Server svr;
  3998. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3999. res.set_content("ok", "text/plain");
  4000. });
  4001. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4002. res.set_content("ok", "text/plain");
  4003. });
  4004. svr.Get("/header_field_value_check", [&](const Request &req, Response &res) {
  4005. auto val = req.get_header_value("Test");
  4006. EXPECT_EQ("[ ]", val);
  4007. res.set_content("ok", "text/plain");
  4008. });
  4009. // Server read timeout must be longer than the client read timeout for the
  4010. // bug to reproduce, probably to force the server to process a request
  4011. // without a trailing blank line.
  4012. const time_t client_read_timeout_sec = 1;
  4013. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4014. bool listen_thread_ok = false;
  4015. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. EXPECT_TRUE(listen_thread_ok);
  4021. });
  4022. svr.wait_until_ready();
  4023. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4024. }
  4025. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4026. // A certain header line causes an exception if the header property is parsed
  4027. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4028. test_raw_request(
  4029. "GET /hi HTTP/1.1\r\n"
  4030. " : "
  4031. " "
  4032. " ");
  4033. }
  4034. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4035. // A certain header line causes an exception if the header property *name* is
  4036. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4037. // greedy matcher and requires backtracking when there are a lot of ":"
  4038. // characters.
  4039. // This occurs with libc++ but not libstdc++.
  4040. test_raw_request(
  4041. "GET /hi HTTP/1.1\r\n"
  4042. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4043. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4044. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4045. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4046. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4047. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4048. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4049. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4050. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4051. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4052. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4053. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4054. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4055. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4056. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4057. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4058. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4059. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4060. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4061. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4062. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4063. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4064. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4065. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4066. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4067. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4068. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4069. "&&&%%%");
  4070. }
  4071. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4072. // Make sure this doesn't crash the server.
  4073. // In a previous version of the header line regex, the "\r" rendered the line
  4074. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4075. // a new position where the leading white space ended and the field value
  4076. // began.
  4077. // The crash occurs with libc++ but not libstdc++.
  4078. test_raw_request("GET /hi HTTP/1.1\r\n"
  4079. "a:" +
  4080. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4081. "\r\n"
  4082. "\r\n");
  4083. }
  4084. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4085. std::string out;
  4086. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4087. "Content-Type: text/plain\r\n"
  4088. "Transfer-Encoding: chunked\r\n"
  4089. "\r\n"
  4090. "nothex\r\n",
  4091. &out);
  4092. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4093. }
  4094. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4095. std::string out;
  4096. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4097. "Content-Type: text/plain\r\n"
  4098. "Transfer-Encoding: chunked\r\n"
  4099. "\r\n"
  4100. "3\r\n"
  4101. "xyz\r\n"
  4102. "NaN\r\n",
  4103. &out);
  4104. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4105. }
  4106. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4107. std::string out;
  4108. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4109. "Content-Type: text/plain\r\n"
  4110. "Transfer-Encoding: chunked\r\n"
  4111. "\r\n"
  4112. // Length is too large for 64 bits.
  4113. "1ffffffffffffffff\r\n"
  4114. "xyz\r\n",
  4115. &out);
  4116. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4117. }
  4118. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4119. test_raw_request("GET /hi HTTP/1.1\r\n"
  4120. "Content-Type: text/plain\r\n\r");
  4121. }
  4122. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4123. std::string out;
  4124. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4125. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4126. }
  4127. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4128. std::string request(
  4129. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4130. test_raw_request(request);
  4131. }
  4132. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4133. Server svr;
  4134. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4135. res.set_header("Cache-Control", "no-cache");
  4136. res.set_chunked_content_provider(
  4137. "text/event-stream", [](size_t offset, DataSink &sink) {
  4138. std::string s = "data:";
  4139. s += std::to_string(offset);
  4140. s += "\n\n";
  4141. auto ret = sink.write(s.data(), s.size());
  4142. EXPECT_TRUE(ret);
  4143. std::this_thread::sleep_for(std::chrono::seconds(1));
  4144. return true;
  4145. });
  4146. });
  4147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4148. svr.wait_until_ready();
  4149. Client client(HOST, PORT);
  4150. const Headers headers = {{"Accept", "text/event-stream"}};
  4151. auto get_thread = std::thread([&client, &headers]() {
  4152. auto res = client.Get(
  4153. "/events", headers,
  4154. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4155. });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. get_thread.join();
  4159. listen_thread.join();
  4160. ASSERT_FALSE(svr.is_running());
  4161. });
  4162. // Give GET time to get a few messages.
  4163. std::this_thread::sleep_for(std::chrono::seconds(2));
  4164. }
  4165. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4166. httplib::Server svr;
  4167. svr.Post("/hi",
  4168. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4169. res.status = StatusCode::OK_200;
  4170. });
  4171. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4172. svr.wait_until_ready();
  4173. Client cli(HOST, PORT);
  4174. auto res = cli.Post("/hi", "data", "text/plain");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. svr.stop();
  4178. thread.join();
  4179. ASSERT_FALSE(svr.is_running());
  4180. res = cli.Post("/hi", "data", "text/plain");
  4181. ASSERT_FALSE(res);
  4182. }
  4183. TEST(ServerStopTest, ListenFailure) {
  4184. Server svr;
  4185. auto t = thread([&]() {
  4186. auto ret = svr.listen("????", PORT);
  4187. EXPECT_FALSE(ret);
  4188. });
  4189. svr.wait_until_ready();
  4190. svr.stop();
  4191. t.join();
  4192. }
  4193. TEST(ServerStopTest, Decommision) {
  4194. Server svr;
  4195. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4196. for (int i = 0; i < 4; i++) {
  4197. auto is_even = !(i % 2);
  4198. std::thread t{[&] {
  4199. try {
  4200. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4201. if (is_even) {
  4202. throw std::runtime_error("Some thing that happens to go wrong.");
  4203. }
  4204. svr.listen(HOST, PORT);
  4205. } catch (...) { svr.decommission(); }
  4206. }};
  4207. svr.wait_until_ready();
  4208. // Server is up
  4209. {
  4210. Client cli(HOST, PORT);
  4211. auto res = cli.Get("/hi");
  4212. if (is_even) {
  4213. EXPECT_FALSE(res);
  4214. } else {
  4215. EXPECT_TRUE(res);
  4216. EXPECT_EQ("hi...", res->body);
  4217. }
  4218. }
  4219. svr.stop();
  4220. t.join();
  4221. // Server is down...
  4222. {
  4223. Client cli(HOST, PORT);
  4224. auto res = cli.Get("/hi");
  4225. EXPECT_FALSE(res);
  4226. }
  4227. }
  4228. }
  4229. TEST(StreamingTest, NoContentLengthStreaming) {
  4230. Server svr;
  4231. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4232. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4233. if (offset < 6) {
  4234. sink.os << (offset < 3 ? "a" : "b");
  4235. } else {
  4236. sink.done();
  4237. }
  4238. return true;
  4239. });
  4240. });
  4241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4242. auto listen_se = detail::scope_exit([&] {
  4243. svr.stop();
  4244. listen_thread.join();
  4245. ASSERT_FALSE(svr.is_running());
  4246. });
  4247. svr.wait_until_ready();
  4248. Client client(HOST, PORT);
  4249. auto get_thread = std::thread([&client]() {
  4250. std::string s;
  4251. auto res =
  4252. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4253. s += std::string(data, len);
  4254. return true;
  4255. });
  4256. EXPECT_EQ("aaabbb", s);
  4257. });
  4258. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4259. // Give GET time to get a few messages.
  4260. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4261. }
  4262. TEST(MountTest, Unmount) {
  4263. Server svr;
  4264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4265. auto se = detail::scope_exit([&] {
  4266. svr.stop();
  4267. listen_thread.join();
  4268. ASSERT_FALSE(svr.is_running());
  4269. });
  4270. svr.wait_until_ready();
  4271. Client cli("localhost", PORT);
  4272. svr.set_mount_point("/mount2", "./www2");
  4273. auto res = cli.Get("/");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. res = cli.Get("/mount2/dir/test.html");
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::OK_200, res->status);
  4279. svr.set_mount_point("/", "./www");
  4280. res = cli.Get("/dir/");
  4281. ASSERT_TRUE(res);
  4282. EXPECT_EQ(StatusCode::OK_200, res->status);
  4283. svr.remove_mount_point("/");
  4284. res = cli.Get("/dir/");
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4287. svr.remove_mount_point("/mount2");
  4288. res = cli.Get("/mount2/dir/test.html");
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4293. TEST(ExceptionTest, ThrowExceptionInHandler) {
  4294. Server svr;
  4295. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4296. throw std::runtime_error("exception...");
  4297. });
  4298. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4299. throw std::runtime_error("exception\r\n...");
  4300. });
  4301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4302. auto se = detail::scope_exit([&] {
  4303. svr.stop();
  4304. listen_thread.join();
  4305. ASSERT_FALSE(svr.is_running());
  4306. });
  4307. svr.wait_until_ready();
  4308. Client cli("localhost", PORT);
  4309. {
  4310. auto res = cli.Get("/exception");
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4313. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4314. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  4315. }
  4316. {
  4317. auto res = cli.Get("/unknown");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4320. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4321. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  4322. }
  4323. }
  4324. #endif
  4325. TEST(KeepAliveTest, ReadTimeout) {
  4326. Server svr;
  4327. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4328. std::this_thread::sleep_for(std::chrono::seconds(2));
  4329. res.set_content("a", "text/plain");
  4330. });
  4331. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4332. res.set_content("b", "text/plain");
  4333. });
  4334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4335. auto se = detail::scope_exit([&] {
  4336. svr.stop();
  4337. listen_thread.join();
  4338. ASSERT_FALSE(svr.is_running());
  4339. });
  4340. svr.wait_until_ready();
  4341. Client cli("localhost", PORT);
  4342. cli.set_keep_alive(true);
  4343. cli.set_read_timeout(std::chrono::seconds(1));
  4344. auto resa = cli.Get("/a");
  4345. ASSERT_FALSE(resa);
  4346. EXPECT_EQ(Error::Read, resa.error());
  4347. auto resb = cli.Get("/b");
  4348. ASSERT_TRUE(resb);
  4349. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4350. EXPECT_EQ("b", resb->body);
  4351. }
  4352. TEST(KeepAliveTest, Issue1041) {
  4353. Server svr;
  4354. svr.set_keep_alive_timeout(3);
  4355. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4356. res.set_content("Hello World!", "text/plain");
  4357. });
  4358. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. listen_thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. Client cli(HOST, PORT);
  4366. cli.set_keep_alive(true);
  4367. auto result = cli.Get("/hi");
  4368. ASSERT_TRUE(result);
  4369. EXPECT_EQ(StatusCode::OK_200, result->status);
  4370. std::this_thread::sleep_for(std::chrono::seconds(5));
  4371. result = cli.Get("/hi");
  4372. ASSERT_TRUE(result);
  4373. EXPECT_EQ(StatusCode::OK_200, result->status);
  4374. }
  4375. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4376. TEST(KeepAliveTest, SSLClientReconnection) {
  4377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4378. ASSERT_TRUE(svr.is_valid());
  4379. svr.set_keep_alive_timeout(1);
  4380. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4381. res.set_content("Hello World!", "text/plain");
  4382. });
  4383. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4384. auto se = detail::scope_exit([&] {
  4385. svr.stop();
  4386. listen_thread.join();
  4387. ASSERT_FALSE(svr.is_running());
  4388. });
  4389. svr.wait_until_ready();
  4390. SSLClient cli(HOST, PORT);
  4391. cli.enable_server_certificate_verification(false);
  4392. cli.set_keep_alive(true);
  4393. auto result = cli.Get("/hi");
  4394. ASSERT_TRUE(result);
  4395. EXPECT_EQ(StatusCode::OK_200, result->status);
  4396. result = cli.Get("/hi");
  4397. ASSERT_TRUE(result);
  4398. EXPECT_EQ(StatusCode::OK_200, result->status);
  4399. std::this_thread::sleep_for(std::chrono::seconds(2));
  4400. // Recoonect
  4401. result = cli.Get("/hi");
  4402. ASSERT_TRUE(result);
  4403. EXPECT_EQ(StatusCode::OK_200, result->status);
  4404. result = cli.Get("/hi");
  4405. ASSERT_TRUE(result);
  4406. EXPECT_EQ(StatusCode::OK_200, result->status);
  4407. }
  4408. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4410. ASSERT_TRUE(svr.is_valid());
  4411. svr.set_keep_alive_timeout(1);
  4412. std::string content = "reconnect";
  4413. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4414. res.set_content("Hello World!", "text/plain");
  4415. });
  4416. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4417. auto se = detail::scope_exit([&] {
  4418. svr.stop();
  4419. listen_thread.join();
  4420. ASSERT_FALSE(svr.is_running());
  4421. });
  4422. svr.wait_until_ready();
  4423. SSLClient cli(HOST, PORT);
  4424. cli.enable_server_certificate_verification(false);
  4425. cli.set_keep_alive(true);
  4426. auto result = cli.Post(
  4427. "/hi", content.size(),
  4428. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4429. sink.write(content.c_str(), content.size());
  4430. return true;
  4431. },
  4432. "text/plain");
  4433. ASSERT_TRUE(result);
  4434. EXPECT_EQ(200, result->status);
  4435. std::this_thread::sleep_for(std::chrono::seconds(2));
  4436. // Recoonect
  4437. result = cli.Post(
  4438. "/hi", content.size(),
  4439. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4440. sink.write(content.c_str(), content.size());
  4441. return true;
  4442. },
  4443. "text/plain");
  4444. ASSERT_TRUE(result);
  4445. EXPECT_EQ(200, result->status);
  4446. result = cli.Post(
  4447. "/hi", content.size(),
  4448. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4449. sink.write(content.c_str(), content.size());
  4450. return true;
  4451. },
  4452. "text/plain");
  4453. ASSERT_TRUE(result);
  4454. EXPECT_EQ(200, result->status);
  4455. }
  4456. #endif
  4457. TEST(ClientProblemDetectionTest, ContentProvider) {
  4458. Server svr;
  4459. size_t content_length = 1024 * 1024;
  4460. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4461. res.set_content_provider(
  4462. content_length, "text/plain",
  4463. [&](size_t offset, size_t length, DataSink &sink) {
  4464. auto out_len = std::min(length, static_cast<size_t>(1024));
  4465. std::string out(out_len, '@');
  4466. sink.write(out.data(), out_len);
  4467. return offset < 4096;
  4468. },
  4469. [](bool success) { ASSERT_FALSE(success); });
  4470. });
  4471. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4472. res.set_content_provider(
  4473. 0, "text/plain",
  4474. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4475. EXPECT_TRUE(false);
  4476. return true;
  4477. },
  4478. [](bool success) { ASSERT_FALSE(success); });
  4479. });
  4480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. listen_thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli("localhost", PORT);
  4488. {
  4489. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4490. size_t /*data_length*/) { return false; });
  4491. ASSERT_FALSE(res);
  4492. }
  4493. {
  4494. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4495. size_t /*data_length*/) { return false; });
  4496. ASSERT_TRUE(res);
  4497. }
  4498. }
  4499. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4500. Server svr;
  4501. svr.set_error_handler([](Request const &, Response &res) -> void {
  4502. res.set_chunked_content_provider(
  4503. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4504. sink.os << "hello";
  4505. sink.os << "world";
  4506. sink.done();
  4507. return true;
  4508. });
  4509. });
  4510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4511. auto se = detail::scope_exit([&] {
  4512. svr.stop();
  4513. listen_thread.join();
  4514. ASSERT_FALSE(svr.is_running());
  4515. });
  4516. svr.wait_until_ready();
  4517. Client cli("localhost", PORT);
  4518. auto res = cli.Get("/");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4521. EXPECT_EQ("helloworld", res->body);
  4522. }
  4523. TEST(LongPollingTest, ClientCloseDetection) {
  4524. Server svr;
  4525. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4526. res.set_chunked_content_provider(
  4527. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4528. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4529. sink.os << "hello";
  4530. auto count = 10;
  4531. while (count > 0 && sink.is_writable()) {
  4532. this_thread::sleep_for(chrono::milliseconds(10));
  4533. }
  4534. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4535. return true;
  4536. });
  4537. });
  4538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4539. auto se = detail::scope_exit([&] {
  4540. svr.stop();
  4541. listen_thread.join();
  4542. ASSERT_FALSE(svr.is_running());
  4543. });
  4544. svr.wait_until_ready();
  4545. Client cli("localhost", PORT);
  4546. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4547. EXPECT_EQ("hello", string(data, data_length));
  4548. return false; // close the socket immediately.
  4549. });
  4550. ASSERT_FALSE(res);
  4551. }
  4552. TEST(GetWithParametersTest, GetWithParameters) {
  4553. Server svr;
  4554. svr.Get("/", [&](const Request &req, Response &) {
  4555. EXPECT_EQ("world", req.get_param_value("hello"));
  4556. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4557. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4558. });
  4559. svr.Get("/params", [&](const Request &req, Response &) {
  4560. EXPECT_EQ("world", req.get_param_value("hello"));
  4561. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4562. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4563. });
  4564. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4565. EXPECT_EQ("resource-id", req.matches[1]);
  4566. EXPECT_EQ("foo", req.get_param_value("param1"));
  4567. EXPECT_EQ("bar", req.get_param_value("param2"));
  4568. });
  4569. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4570. EXPECT_EQ("user-id", req.path_params.at("id"));
  4571. EXPECT_EQ("foo", req.get_param_value("param1"));
  4572. EXPECT_EQ("bar", req.get_param_value("param2"));
  4573. });
  4574. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4575. auto se = detail::scope_exit([&] {
  4576. svr.stop();
  4577. listen_thread.join();
  4578. ASSERT_FALSE(svr.is_running());
  4579. });
  4580. svr.wait_until_ready();
  4581. {
  4582. Client cli(HOST, PORT);
  4583. Params params;
  4584. params.emplace("hello", "world");
  4585. params.emplace("hello2", "world2");
  4586. params.emplace("hello3", "world3");
  4587. auto res = cli.Get("/", params, Headers{});
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. }
  4591. {
  4592. Client cli(HOST, PORT);
  4593. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4594. ASSERT_TRUE(res);
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. }
  4597. {
  4598. Client cli(HOST, PORT);
  4599. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. {
  4604. Client cli(HOST, PORT);
  4605. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. }
  4609. }
  4610. TEST(GetWithParametersTest, GetWithParameters2) {
  4611. Server svr;
  4612. svr.Get("/", [&](const Request &req, Response &res) {
  4613. auto text = req.get_param_value("hello");
  4614. res.set_content(text, "text/plain");
  4615. });
  4616. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4617. auto se = detail::scope_exit([&] {
  4618. svr.stop();
  4619. listen_thread.join();
  4620. ASSERT_FALSE(svr.is_running());
  4621. });
  4622. svr.wait_until_ready();
  4623. Client cli("localhost", PORT);
  4624. Params params;
  4625. params.emplace("hello", "world");
  4626. std::string body;
  4627. auto res = cli.Get("/", params, Headers{},
  4628. [&](const char *data, size_t data_length) {
  4629. body.append(data, data_length);
  4630. return true;
  4631. });
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("world", body);
  4635. }
  4636. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4637. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4638. auto host = "httpbin.org";
  4639. auto path = std::string{"/range/32"};
  4640. #else
  4641. auto host = "nghttp2.org";
  4642. auto path = std::string{"/httpbin/range/32"};
  4643. #endif
  4644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4645. SSLClient cli(host);
  4646. #else
  4647. Client cli(host);
  4648. #endif
  4649. cli.set_default_headers({make_range_header({{1, 10}})});
  4650. cli.set_connection_timeout(5);
  4651. {
  4652. auto res = cli.Get(path);
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ("bcdefghijk", res->body);
  4655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4656. }
  4657. {
  4658. auto res = cli.Get(path);
  4659. ASSERT_TRUE(res);
  4660. EXPECT_EQ("bcdefghijk", res->body);
  4661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4662. }
  4663. }
  4664. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4665. Server svr;
  4666. svr.set_default_headers({{"Hello", "World"}});
  4667. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4668. res.set_content("ok", "text/plain");
  4669. });
  4670. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. listen_thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. Client cli("localhost", PORT);
  4678. auto res = cli.Get("/");
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::OK_200, res->status);
  4681. EXPECT_EQ("ok", res->body);
  4682. EXPECT_EQ("World", res->get_header_value("Hello"));
  4683. }
  4684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4685. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4687. ASSERT_TRUE(svr.is_valid());
  4688. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4689. std::this_thread::sleep_for(std::chrono::seconds(2));
  4690. res.set_content("a", "text/plain");
  4691. });
  4692. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4693. res.set_content("b", "text/plain");
  4694. });
  4695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4696. auto se = detail::scope_exit([&] {
  4697. svr.stop();
  4698. listen_thread.join();
  4699. ASSERT_FALSE(svr.is_running());
  4700. });
  4701. svr.wait_until_ready();
  4702. SSLClient cli("localhost", PORT);
  4703. cli.enable_server_certificate_verification(false);
  4704. cli.set_keep_alive(true);
  4705. cli.set_read_timeout(std::chrono::seconds(1));
  4706. auto resa = cli.Get("/a");
  4707. ASSERT_TRUE(!resa);
  4708. EXPECT_EQ(Error::Read, resa.error());
  4709. auto resb = cli.Get("/b");
  4710. ASSERT_TRUE(resb);
  4711. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4712. EXPECT_EQ("b", resb->body);
  4713. }
  4714. #endif
  4715. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4716. protected:
  4717. ServerTestWithAI_PASSIVE()
  4718. : cli_(HOST, PORT)
  4719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4720. ,
  4721. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4722. #endif
  4723. {
  4724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4725. cli_.enable_server_certificate_verification(false);
  4726. #endif
  4727. }
  4728. virtual void SetUp() {
  4729. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4730. res.set_content("Hello World!", "text/plain");
  4731. });
  4732. t_ = thread(
  4733. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4734. svr_.wait_until_ready();
  4735. }
  4736. virtual void TearDown() {
  4737. svr_.stop();
  4738. t_.join();
  4739. }
  4740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4741. SSLClient cli_;
  4742. SSLServer svr_;
  4743. #else
  4744. Client cli_;
  4745. Server svr_;
  4746. #endif
  4747. thread t_;
  4748. };
  4749. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4750. auto res = cli_.Get("/hi");
  4751. ASSERT_TRUE(res);
  4752. EXPECT_EQ(StatusCode::OK_200, res->status);
  4753. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4754. EXPECT_EQ("Hello World!", res->body);
  4755. }
  4756. class ServerUpDownTest : public ::testing::Test {
  4757. protected:
  4758. ServerUpDownTest() : cli_(HOST, PORT) {}
  4759. virtual void SetUp() {
  4760. t_ = thread([&]() {
  4761. svr_.bind_to_any_port(HOST);
  4762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4763. ASSERT_TRUE(svr_.listen_after_bind());
  4764. });
  4765. svr_.wait_until_ready();
  4766. }
  4767. virtual void TearDown() {
  4768. svr_.stop();
  4769. t_.join();
  4770. }
  4771. Client cli_;
  4772. Server svr_;
  4773. thread t_;
  4774. };
  4775. TEST_F(ServerUpDownTest, QuickStartStop) {
  4776. // Should not crash, especially when run with
  4777. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4778. }
  4779. class PayloadMaxLengthTest : public ::testing::Test {
  4780. protected:
  4781. PayloadMaxLengthTest()
  4782. : cli_(HOST, PORT)
  4783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4784. ,
  4785. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4786. #endif
  4787. {
  4788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4789. cli_.enable_server_certificate_verification(false);
  4790. #endif
  4791. }
  4792. virtual void SetUp() {
  4793. svr_.set_payload_max_length(8);
  4794. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4795. res.set_content("test", "text/plain");
  4796. });
  4797. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4798. svr_.wait_until_ready();
  4799. }
  4800. virtual void TearDown() {
  4801. svr_.stop();
  4802. t_.join();
  4803. }
  4804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4805. SSLClient cli_;
  4806. SSLServer svr_;
  4807. #else
  4808. Client cli_;
  4809. Server svr_;
  4810. #endif
  4811. thread t_;
  4812. };
  4813. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4814. auto res = cli_.Post("/test", "123456789", "text/plain");
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4817. res = cli_.Post("/test", "12345678", "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. }
  4821. TEST(HostAndPortPropertiesTest, NoSSL) {
  4822. httplib::Client cli("www.google.com", 1234);
  4823. ASSERT_EQ("www.google.com", cli.host());
  4824. ASSERT_EQ(1234, cli.port());
  4825. }
  4826. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4827. httplib::Client cli("www.google.com:1234");
  4828. ASSERT_EQ("www.google.com", cli.host());
  4829. ASSERT_EQ(1234, cli.port());
  4830. }
  4831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4832. TEST(HostAndPortPropertiesTest, SSL) {
  4833. httplib::SSLClient cli("www.google.com");
  4834. ASSERT_EQ("www.google.com", cli.host());
  4835. ASSERT_EQ(443, cli.port());
  4836. }
  4837. #endif
  4838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4839. TEST(SSLClientTest, UpdateCAStore) {
  4840. httplib::SSLClient httplib_client("www.google.com");
  4841. auto ca_store_1 = X509_STORE_new();
  4842. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4843. nullptr);
  4844. httplib_client.set_ca_cert_store(ca_store_1);
  4845. auto ca_store_2 = X509_STORE_new();
  4846. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4847. nullptr);
  4848. httplib_client.set_ca_cert_store(ca_store_2);
  4849. }
  4850. TEST(SSLClientTest, ServerNameIndication_Online) {
  4851. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4852. auto host = "httpbin.org";
  4853. auto path = std::string{"/get"};
  4854. #else
  4855. auto host = "nghttp2.org";
  4856. auto path = std::string{"/httpbin/get"};
  4857. #endif
  4858. SSLClient cli(host, 443);
  4859. auto res = cli.Get(path);
  4860. ASSERT_TRUE(res);
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. }
  4863. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4864. Client cli("https://google.com");
  4865. auto res = cli.Get("/");
  4866. ASSERT_TRUE(res);
  4867. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4868. }
  4869. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4870. SSLClient cli("google.com");
  4871. cli.enable_server_certificate_verification(true);
  4872. cli.set_ca_cert_path("hello");
  4873. auto res = cli.Get("/");
  4874. ASSERT_TRUE(!res);
  4875. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4876. }
  4877. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4878. SSLClient cli("google.com");
  4879. cli.set_ca_cert_path(CA_CERT_FILE);
  4880. auto res = cli.Get("/");
  4881. ASSERT_TRUE(res);
  4882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4883. }
  4884. TEST(SSLClientTest, ServerCertificateVerification4) {
  4885. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4886. ASSERT_TRUE(svr.is_valid());
  4887. svr.Get("/test", [&](const Request &, Response &res) {
  4888. res.set_content("test", "text/plain");
  4889. svr.stop();
  4890. ASSERT_TRUE(true);
  4891. });
  4892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4893. auto se = detail::scope_exit([&] {
  4894. t.join();
  4895. ASSERT_FALSE(svr.is_running());
  4896. });
  4897. svr.wait_until_ready();
  4898. SSLClient cli("127.0.0.1", PORT);
  4899. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4900. cli.enable_server_certificate_verification(true);
  4901. cli.set_connection_timeout(30);
  4902. auto res = cli.Get("/test");
  4903. ASSERT_TRUE(res);
  4904. ASSERT_EQ(StatusCode::OK_200, res->status);
  4905. }
  4906. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4907. std::string cert;
  4908. detail::read_file(CA_CERT_FILE, cert);
  4909. SSLClient cli("google.com");
  4910. cli.load_ca_cert_store(cert.data(), cert.size());
  4911. const auto res = cli.Get("/");
  4912. ASSERT_TRUE(res);
  4913. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4914. }
  4915. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4916. // clang-format off
  4917. static constexpr char cert[] =
  4918. "GlobalSign Root CA\n"
  4919. "==================\n"
  4920. "-----BEGIN CERTIFICATE-----\n"
  4921. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4922. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4923. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4924. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4925. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4926. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4927. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4928. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4929. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4930. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4931. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4932. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4933. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4934. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4935. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4936. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4937. "-----END CERTIFICATE-----\n";
  4938. // clang-format on
  4939. SSLClient cli("google.com");
  4940. cli.load_ca_cert_store(cert, sizeof(cert));
  4941. const auto res = cli.Get("/");
  4942. ASSERT_TRUE(res);
  4943. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4944. }
  4945. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4946. SSLClient cli("www.youtube.com");
  4947. cli.set_ca_cert_path(CA_CERT_FILE);
  4948. cli.enable_server_certificate_verification(true);
  4949. cli.set_follow_location(true);
  4950. auto res = cli.Get("/");
  4951. ASSERT_TRUE(res);
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. }
  4954. #if 0
  4955. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4956. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4957. ASSERT_TRUE(cli != nullptr);
  4958. cli->set_address_family(AF_INET6);
  4959. cli->set_interface("en0");
  4960. auto res = cli->Get("/get");
  4961. ASSERT_TRUE(res);
  4962. ASSERT_EQ(StatusCode::OK_200, res->status);
  4963. }
  4964. #endif
  4965. void ClientCertPresent(
  4966. const std::string &client_cert_file,
  4967. const std::string &client_private_key_file,
  4968. const std::string &client_encrypted_private_key_pass = std::string()) {
  4969. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4970. CLIENT_CA_CERT_DIR);
  4971. ASSERT_TRUE(svr.is_valid());
  4972. svr.Get("/test", [&](const Request &req, Response &res) {
  4973. res.set_content("test", "text/plain");
  4974. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4975. ASSERT_TRUE(peer_cert != nullptr);
  4976. auto subject_name = X509_get_subject_name(peer_cert);
  4977. ASSERT_TRUE(subject_name != nullptr);
  4978. std::string common_name;
  4979. {
  4980. char name[BUFSIZ];
  4981. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4982. name, sizeof(name));
  4983. common_name.assign(name, static_cast<size_t>(name_len));
  4984. }
  4985. EXPECT_EQ("Common Name", common_name);
  4986. X509_free(peer_cert);
  4987. });
  4988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4989. auto se = detail::scope_exit([&] {
  4990. svr.stop();
  4991. t.join();
  4992. ASSERT_FALSE(svr.is_running());
  4993. });
  4994. svr.wait_until_ready();
  4995. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  4996. client_encrypted_private_key_pass);
  4997. cli.enable_server_certificate_verification(false);
  4998. cli.set_connection_timeout(30);
  4999. auto res = cli.Get("/test");
  5000. ASSERT_TRUE(res);
  5001. ASSERT_EQ(StatusCode::OK_200, res->status);
  5002. }
  5003. TEST(SSLClientServerTest, ClientCertPresent) {
  5004. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5005. }
  5006. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5007. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5008. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5009. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5010. }
  5011. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5012. void MemoryClientCertPresent(
  5013. const std::string &client_cert_file,
  5014. const std::string &client_private_key_file,
  5015. const std::string &client_encrypted_private_key_pass = std::string()) {
  5016. auto f = fopen(SERVER_CERT_FILE, "r+");
  5017. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5018. fclose(f);
  5019. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5020. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5021. fclose(f);
  5022. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5023. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5024. auto client_ca_cert_store = X509_STORE_new();
  5025. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5026. X509_free(client_cert);
  5027. fclose(f);
  5028. f = fopen(client_cert_file.c_str(), "r+");
  5029. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5030. fclose(f);
  5031. f = fopen(client_private_key_file.c_str(), "r+");
  5032. auto client_private_key = PEM_read_PrivateKey(
  5033. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5034. fclose(f);
  5035. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5036. ASSERT_TRUE(svr.is_valid());
  5037. svr.Get("/test", [&](const Request &req, Response &res) {
  5038. res.set_content("test", "text/plain");
  5039. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5040. ASSERT_TRUE(peer_cert != nullptr);
  5041. auto subject_name = X509_get_subject_name(peer_cert);
  5042. ASSERT_TRUE(subject_name != nullptr);
  5043. std::string common_name;
  5044. {
  5045. char name[BUFSIZ];
  5046. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5047. name, sizeof(name));
  5048. common_name.assign(name, static_cast<size_t>(name_len));
  5049. }
  5050. EXPECT_EQ("Common Name", common_name);
  5051. X509_free(peer_cert);
  5052. });
  5053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5054. auto se = detail::scope_exit([&] {
  5055. svr.stop();
  5056. t.join();
  5057. ASSERT_FALSE(svr.is_running());
  5058. });
  5059. svr.wait_until_ready();
  5060. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5061. client_encrypted_private_key_pass);
  5062. cli.enable_server_certificate_verification(false);
  5063. cli.set_connection_timeout(30);
  5064. auto res = cli.Get("/test");
  5065. ASSERT_TRUE(res);
  5066. ASSERT_EQ(StatusCode::OK_200, res->status);
  5067. X509_free(server_cert);
  5068. EVP_PKEY_free(server_private_key);
  5069. X509_free(client_cert);
  5070. EVP_PKEY_free(client_private_key);
  5071. }
  5072. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5073. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5074. }
  5075. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5076. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5077. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5078. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5079. }
  5080. #endif
  5081. TEST(SSLClientServerTest, ClientCertMissing) {
  5082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5083. CLIENT_CA_CERT_DIR);
  5084. ASSERT_TRUE(svr.is_valid());
  5085. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5086. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5087. auto se = detail::scope_exit([&] {
  5088. svr.stop();
  5089. t.join();
  5090. ASSERT_FALSE(svr.is_running());
  5091. });
  5092. svr.wait_until_ready();
  5093. SSLClient cli(HOST, PORT);
  5094. auto res = cli.Get("/test");
  5095. cli.set_connection_timeout(30);
  5096. ASSERT_TRUE(!res);
  5097. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5098. }
  5099. TEST(SSLClientServerTest, TrustDirOptional) {
  5100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5101. ASSERT_TRUE(svr.is_valid());
  5102. svr.Get("/test", [&](const Request &, Response &res) {
  5103. res.set_content("test", "text/plain");
  5104. });
  5105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5106. auto se = detail::scope_exit([&] {
  5107. svr.stop();
  5108. t.join();
  5109. ASSERT_FALSE(svr.is_running());
  5110. });
  5111. svr.wait_until_ready();
  5112. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5113. cli.enable_server_certificate_verification(false);
  5114. cli.set_connection_timeout(30);
  5115. auto res = cli.Get("/test");
  5116. ASSERT_TRUE(res);
  5117. ASSERT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5120. class NoListenSSLServer : public SSLServer {
  5121. public:
  5122. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5123. const char *client_ca_cert_file_path,
  5124. const char *client_ca_cert_dir_path = nullptr)
  5125. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5126. client_ca_cert_dir_path),
  5127. stop_(false) {}
  5128. std::atomic_bool stop_;
  5129. private:
  5130. bool process_and_close_socket(socket_t /*sock*/) override {
  5131. // Don't create SSL context
  5132. while (!stop_.load()) {
  5133. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5134. }
  5135. return true;
  5136. }
  5137. };
  5138. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5139. CLIENT_CA_CERT_FILE);
  5140. ASSERT_TRUE(svr.is_valid());
  5141. svr.Get("/test", [&](const Request &, Response &res) {
  5142. res.set_content("test", "text/plain");
  5143. });
  5144. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5145. auto se = detail::scope_exit([&] {
  5146. svr.stop_ = true;
  5147. svr.stop();
  5148. t.join();
  5149. ASSERT_FALSE(svr.is_running());
  5150. });
  5151. svr.wait_until_ready();
  5152. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5153. cli.enable_server_certificate_verification(false);
  5154. cli.set_connection_timeout(1);
  5155. auto res = cli.Get("/test");
  5156. ASSERT_TRUE(!res);
  5157. EXPECT_EQ(Error::SSLConnection, res.error());
  5158. }
  5159. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5160. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5161. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5162. SSL_CTX_set_options(&ssl_ctx,
  5163. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5164. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5165. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5166. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5167. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5168. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5169. "ECDHE-DSS-AES128-SHA256:"
  5170. "ECDHE-RSA-AES256-SHA256:"
  5171. "ECDHE-DSS-AES256-SHA256:";
  5172. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5173. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5174. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5175. SSL_FILETYPE_PEM) != 1) {
  5176. return false;
  5177. }
  5178. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5179. CLIENT_CA_CERT_DIR);
  5180. SSL_CTX_set_verify(
  5181. &ssl_ctx,
  5182. SSL_VERIFY_PEER |
  5183. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5184. nullptr);
  5185. return true;
  5186. };
  5187. SSLServer svr(setup_ssl_ctx_callback);
  5188. ASSERT_TRUE(svr.is_valid());
  5189. svr.Get("/test", [&](const Request &req, Response &res) {
  5190. res.set_content("test", "text/plain");
  5191. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5192. ASSERT_TRUE(peer_cert != nullptr);
  5193. auto subject_name = X509_get_subject_name(peer_cert);
  5194. ASSERT_TRUE(subject_name != nullptr);
  5195. std::string common_name;
  5196. {
  5197. char name[BUFSIZ];
  5198. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5199. name, sizeof(name));
  5200. common_name.assign(name, static_cast<size_t>(name_len));
  5201. }
  5202. EXPECT_EQ("Common Name", common_name);
  5203. X509_free(peer_cert);
  5204. });
  5205. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5206. auto se = detail::scope_exit([&] {
  5207. svr.stop();
  5208. t.join();
  5209. ASSERT_FALSE(svr.is_running());
  5210. });
  5211. svr.wait_until_ready();
  5212. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5213. cli.enable_server_certificate_verification(false);
  5214. cli.set_connection_timeout(30);
  5215. auto res = cli.Get("/test");
  5216. ASSERT_TRUE(res);
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. }
  5219. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5220. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5221. // prepare large data
  5222. std::random_device seed_gen;
  5223. std::mt19937 random(seed_gen());
  5224. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5225. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5226. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5227. // server
  5228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5229. ASSERT_TRUE(svr.is_valid());
  5230. svr.Post("/binary", [&](const Request &req, Response &res) {
  5231. EXPECT_EQ(large_size_byte, req.body.size());
  5232. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5233. res.set_content(req.body, "application/octet-stream");
  5234. });
  5235. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5236. auto se = detail::scope_exit([&] {
  5237. svr.stop();
  5238. listen_thread.join();
  5239. ASSERT_FALSE(svr.is_running());
  5240. });
  5241. svr.wait_until_ready();
  5242. // client POST
  5243. SSLClient cli("localhost", PORT);
  5244. cli.enable_server_certificate_verification(false);
  5245. cli.set_read_timeout(std::chrono::seconds(100));
  5246. cli.set_write_timeout(std::chrono::seconds(100));
  5247. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5248. large_size_byte, "application/octet-stream");
  5249. // compare
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. EXPECT_EQ(large_size_byte, res->body.size());
  5252. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5253. }
  5254. #endif
  5255. #ifdef _WIN32
  5256. TEST(CleanupTest, WSACleanup) {
  5257. int ret = WSACleanup();
  5258. ASSERT_EQ(0, ret);
  5259. }
  5260. #endif
  5261. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5262. TEST(NoSSLSupport, SimpleInterface) {
  5263. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5264. }
  5265. #endif
  5266. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5267. TEST(InvalidScheme, SimpleInterface) {
  5268. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5269. }
  5270. #endif
  5271. TEST(NoScheme, SimpleInterface) {
  5272. Client cli("yahoo.com:80");
  5273. ASSERT_TRUE(cli.is_valid());
  5274. }
  5275. TEST(SendAPI, SimpleInterface_Online) {
  5276. Client cli("http://yahoo.com");
  5277. Request req;
  5278. req.method = "GET";
  5279. req.path = "/";
  5280. auto res = cli.send(req);
  5281. ASSERT_TRUE(res);
  5282. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5283. }
  5284. TEST(ClientImplMethods, GetSocketTest) {
  5285. httplib::Server svr;
  5286. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5287. res.status = StatusCode::OK_200;
  5288. });
  5289. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5290. auto se = detail::scope_exit([&] {
  5291. svr.stop();
  5292. thread.join();
  5293. ASSERT_FALSE(svr.is_running());
  5294. });
  5295. svr.wait_until_ready();
  5296. {
  5297. httplib::Client cli("http://127.0.0.1:3333");
  5298. cli.set_keep_alive(true);
  5299. // Use the behavior of cpp-httplib of opening the connection
  5300. // only when the first request happens. If that changes,
  5301. // this test would be obsolete.
  5302. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5303. // This also implicitly tests the server. But other tests would fail much
  5304. // earlier than this one to be considered.
  5305. auto res = cli.Get("/");
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5309. }
  5310. }
  5311. // Disabled due to out-of-memory problem on GitHub Actions
  5312. #ifdef _WIN64
  5313. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5314. // allocate content size larger than 2GB in memory
  5315. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5316. char *content = (char *)malloc(content_size);
  5317. ASSERT_TRUE(content);
  5318. Server svr;
  5319. svr.Get("/foo",
  5320. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5321. res.set_content(content, content_size, "application/octet-stream");
  5322. });
  5323. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5324. auto se = detail::scope_exit([&] {
  5325. svr.stop();
  5326. listen_thread.join();
  5327. if (content) free(content);
  5328. ASSERT_FALSE(svr.is_running());
  5329. });
  5330. svr.wait_until_ready();
  5331. Client cli(HOST, PORT);
  5332. auto res = cli.Get("/foo");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ(content_size, res->body.length());
  5336. }
  5337. #endif
  5338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5339. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5340. Client cli("http://yahoo.com");
  5341. auto res = cli.Get("/");
  5342. ASSERT_TRUE(res);
  5343. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5344. cli.set_follow_location(true);
  5345. res = cli.Get("/");
  5346. ASSERT_TRUE(res);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5349. }
  5350. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5351. Client cli("https://yahoo.com");
  5352. auto res = cli.Get("/");
  5353. ASSERT_TRUE(res);
  5354. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5355. cli.set_follow_location(true);
  5356. res = cli.Get("/");
  5357. ASSERT_TRUE(res);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5360. }
  5361. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5362. Client cli("https://yahoo.com");
  5363. auto res = cli.Get("/");
  5364. ASSERT_TRUE(res);
  5365. ASSERT_FALSE(!res);
  5366. ASSERT_TRUE(res);
  5367. ASSERT_FALSE(res == nullptr);
  5368. ASSERT_TRUE(res != nullptr);
  5369. EXPECT_EQ(Error::Success, res.error());
  5370. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5371. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5372. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5373. cli.set_follow_location(true);
  5374. res = cli.Get("/");
  5375. ASSERT_TRUE(res);
  5376. EXPECT_EQ(Error::Success, res.error());
  5377. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5378. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5379. EXPECT_EQ(StatusCode::OK_200, res->status);
  5380. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5381. }
  5382. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5383. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5384. Client cli("https://cdnjs.cloudflare.com");
  5385. auto res =
  5386. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. EXPECT_EQ(287630U, res->body.size());
  5390. EXPECT_EQ("application/javascript; charset=utf-8",
  5391. res->get_header_value("Content-Type"));
  5392. }
  5393. #endif
  5394. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5395. Client cli("https://nghttp2.org");
  5396. cli.set_follow_location(true);
  5397. auto res =
  5398. cli.Get("/httpbin/"
  5399. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5400. ASSERT_TRUE(res);
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5404. Client cli("https://nghttp2.org");
  5405. cli.set_follow_location(true);
  5406. Params params;
  5407. params.emplace("url", "http://www.google.com");
  5408. params.emplace("status_code", "302");
  5409. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. }
  5413. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5414. Client cli("https://nghttp2.org");
  5415. cli.set_follow_location(true);
  5416. Params params;
  5417. params.emplace("url", "http://www.google.com");
  5418. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. }
  5422. TEST(HttpToHttpsRedirectTest, CertFile) {
  5423. Server svr;
  5424. ASSERT_TRUE(svr.is_valid());
  5425. svr.Get("/index", [&](const Request &, Response &res) {
  5426. res.set_redirect("https://127.0.0.1:1235/index");
  5427. svr.stop();
  5428. });
  5429. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5430. ASSERT_TRUE(ssl_svr.is_valid());
  5431. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5432. res.set_content("test", "text/plain");
  5433. ssl_svr.stop();
  5434. });
  5435. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5436. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5437. auto se = detail::scope_exit([&] {
  5438. t2.join();
  5439. t.join();
  5440. ASSERT_FALSE(svr.is_running());
  5441. });
  5442. svr.wait_until_ready();
  5443. ssl_svr.wait_until_ready();
  5444. Client cli("127.0.0.1", PORT);
  5445. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5446. cli.enable_server_certificate_verification(true);
  5447. cli.set_follow_location(true);
  5448. cli.set_connection_timeout(30);
  5449. auto res = cli.Get("/index");
  5450. ASSERT_TRUE(res);
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST(MultipartFormDataTest, LargeData) {
  5454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5455. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5456. const ContentReader &content_reader) {
  5457. if (req.is_multipart_form_data()) {
  5458. MultipartFormDataItems files;
  5459. content_reader(
  5460. [&](const MultipartFormData &file) {
  5461. files.push_back(file);
  5462. return true;
  5463. },
  5464. [&](const char *data, size_t data_length) {
  5465. files.back().content.append(data, data_length);
  5466. return true;
  5467. });
  5468. EXPECT_TRUE(std::string(files[0].name) == "document");
  5469. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5470. EXPECT_TRUE(files[0].filename == "2MB_data");
  5471. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5472. EXPECT_TRUE(files[1].name == "hello");
  5473. EXPECT_TRUE(files[1].content == "world");
  5474. EXPECT_TRUE(files[1].filename == "");
  5475. EXPECT_TRUE(files[1].content_type == "");
  5476. } else {
  5477. std::string body;
  5478. content_reader([&](const char *data, size_t data_length) {
  5479. body.append(data, data_length);
  5480. return true;
  5481. });
  5482. }
  5483. });
  5484. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. t.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. });
  5490. svr.wait_until_ready();
  5491. {
  5492. std::string data(1024 * 1024 * 2, '.');
  5493. std::stringstream buffer;
  5494. buffer << data;
  5495. Client cli("https://localhost:8080");
  5496. cli.enable_server_certificate_verification(false);
  5497. MultipartFormDataItems items{
  5498. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5499. {"hello", "world", "", ""},
  5500. };
  5501. auto res = cli.Post("/post", items);
  5502. ASSERT_TRUE(res);
  5503. ASSERT_EQ(StatusCode::OK_200, res->status);
  5504. }
  5505. }
  5506. TEST(MultipartFormDataTest, DataProviderItems) {
  5507. std::random_device seed_gen;
  5508. std::mt19937 random(seed_gen());
  5509. std::string rand1;
  5510. rand1.resize(1000);
  5511. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5512. std::string rand2;
  5513. rand2.resize(3000);
  5514. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5516. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5517. const ContentReader &content_reader) {
  5518. ASSERT_FALSE(req.is_multipart_form_data());
  5519. std::string body;
  5520. content_reader([&](const char *data, size_t data_length) {
  5521. body.append(data, data_length);
  5522. return true;
  5523. });
  5524. EXPECT_EQ(body, "");
  5525. });
  5526. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5527. const ContentReader &content_reader) {
  5528. ASSERT_TRUE(req.is_multipart_form_data());
  5529. MultipartFormDataItems files;
  5530. content_reader(
  5531. [&](const MultipartFormData &file) {
  5532. files.push_back(file);
  5533. return true;
  5534. },
  5535. [&](const char *data, size_t data_length) {
  5536. files.back().content.append(data, data_length);
  5537. return true;
  5538. });
  5539. ASSERT_TRUE(files.size() == 2);
  5540. EXPECT_EQ(std::string(files[0].name), "name1");
  5541. EXPECT_EQ(files[0].content, "Testing123");
  5542. EXPECT_EQ(files[0].filename, "filename1");
  5543. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5544. EXPECT_EQ(files[1].name, "name2");
  5545. EXPECT_EQ(files[1].content, "Testing456");
  5546. EXPECT_EQ(files[1].filename, "");
  5547. EXPECT_EQ(files[1].content_type, "");
  5548. });
  5549. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5550. const ContentReader &content_reader) {
  5551. ASSERT_TRUE(req.is_multipart_form_data());
  5552. MultipartFormDataItems files;
  5553. content_reader(
  5554. [&](const MultipartFormData &file) {
  5555. files.push_back(file);
  5556. return true;
  5557. },
  5558. [&](const char *data, size_t data_length) {
  5559. files.back().content.append(data, data_length);
  5560. return true;
  5561. });
  5562. ASSERT_TRUE(files.size() == 2);
  5563. EXPECT_EQ(files[0].name, "name3");
  5564. EXPECT_EQ(files[0].content, rand1);
  5565. EXPECT_EQ(files[0].filename, "filename3");
  5566. EXPECT_EQ(files[0].content_type, "");
  5567. EXPECT_EQ(files[1].name, "name4");
  5568. EXPECT_EQ(files[1].content, rand2);
  5569. EXPECT_EQ(files[1].filename, "filename4");
  5570. EXPECT_EQ(files[1].content_type, "");
  5571. });
  5572. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5573. const ContentReader &content_reader) {
  5574. ASSERT_TRUE(req.is_multipart_form_data());
  5575. MultipartFormDataItems files;
  5576. content_reader(
  5577. [&](const MultipartFormData &file) {
  5578. files.push_back(file);
  5579. return true;
  5580. },
  5581. [&](const char *data, size_t data_length) {
  5582. files.back().content.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(files.size() == 4);
  5586. EXPECT_EQ(std::string(files[0].name), "name1");
  5587. EXPECT_EQ(files[0].content, "Testing123");
  5588. EXPECT_EQ(files[0].filename, "filename1");
  5589. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5590. EXPECT_EQ(files[1].name, "name2");
  5591. EXPECT_EQ(files[1].content, "Testing456");
  5592. EXPECT_EQ(files[1].filename, "");
  5593. EXPECT_EQ(files[1].content_type, "");
  5594. EXPECT_EQ(files[2].name, "name3");
  5595. EXPECT_EQ(files[2].content, rand1);
  5596. EXPECT_EQ(files[2].filename, "filename3");
  5597. EXPECT_EQ(files[2].content_type, "");
  5598. EXPECT_EQ(files[3].name, "name4");
  5599. EXPECT_EQ(files[3].content, rand2);
  5600. EXPECT_EQ(files[3].filename, "filename4");
  5601. EXPECT_EQ(files[3].content_type, "");
  5602. });
  5603. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5604. auto se = detail::scope_exit([&] {
  5605. svr.stop();
  5606. t.join();
  5607. ASSERT_FALSE(svr.is_running());
  5608. });
  5609. svr.wait_until_ready();
  5610. {
  5611. Client cli("https://localhost:8080");
  5612. cli.enable_server_certificate_verification(false);
  5613. MultipartFormDataItems items{
  5614. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5615. {"name2", "Testing456", "", ""}, // not a file
  5616. };
  5617. {
  5618. auto res = cli.Post("/post-none", {}, {}, {});
  5619. ASSERT_TRUE(res);
  5620. ASSERT_EQ(StatusCode::OK_200, res->status);
  5621. }
  5622. MultipartFormDataProviderItems providers;
  5623. {
  5624. auto res =
  5625. cli.Post("/post-items", {}, items, providers); // empty providers
  5626. ASSERT_TRUE(res);
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. providers.push_back({"name3",
  5630. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5631. // test the offset is given correctly at each step
  5632. if (!offset)
  5633. sink.os.write(rand1.data(), 30);
  5634. else if (offset == 30)
  5635. sink.os.write(rand1.data() + 30, 300);
  5636. else if (offset == 330)
  5637. sink.os.write(rand1.data() + 330, 670);
  5638. else if (offset == rand1.size())
  5639. sink.done();
  5640. return true;
  5641. },
  5642. "filename3",
  5643. {}});
  5644. providers.push_back({"name4",
  5645. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5646. // test the offset is given correctly at each step
  5647. if (!offset)
  5648. sink.os.write(rand2.data(), 2000);
  5649. else if (offset == 2000)
  5650. sink.os.write(rand2.data() + 2000, 1);
  5651. else if (offset == 2001)
  5652. sink.os.write(rand2.data() + 2001, 999);
  5653. else if (offset == rand2.size())
  5654. sink.done();
  5655. return true;
  5656. },
  5657. "filename4",
  5658. {}});
  5659. {
  5660. auto res = cli.Post("/post-providers", {}, {}, providers);
  5661. ASSERT_TRUE(res);
  5662. ASSERT_EQ(StatusCode::OK_200, res->status);
  5663. }
  5664. {
  5665. auto res = cli.Post("/post-both", {}, items, providers);
  5666. ASSERT_TRUE(res);
  5667. ASSERT_EQ(StatusCode::OK_200, res->status);
  5668. }
  5669. }
  5670. }
  5671. TEST(MultipartFormDataTest, BadHeader) {
  5672. Server svr;
  5673. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5674. res.set_content("ok", "text/plain");
  5675. });
  5676. thread t = thread([&] { svr.listen(HOST, PORT); });
  5677. auto se = detail::scope_exit([&] {
  5678. svr.stop();
  5679. t.join();
  5680. ASSERT_FALSE(svr.is_running());
  5681. });
  5682. svr.wait_until_ready();
  5683. const std::string body =
  5684. "This is the preamble. It is to be ignored, though it\r\n"
  5685. "is a handy place for composition agents to include an\r\n"
  5686. "explanatory note to non-MIME conformant readers.\r\n"
  5687. "\r\n"
  5688. "\r\n"
  5689. "--simple boundary\r\n"
  5690. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5691. ": BAD...\r\n"
  5692. "\r\n"
  5693. "value1\r\n"
  5694. "--simple boundary\r\n"
  5695. "Content-Disposition: form-data; name=\"field2\"; "
  5696. "filename=\"example.txt\"\r\n"
  5697. "\r\n"
  5698. "value2\r\n"
  5699. "--simple boundary--\r\n"
  5700. "This is the epilogue. It is also to be ignored.\r\n";
  5701. std::string content_type =
  5702. R"(multipart/form-data; boundary="simple boundary")";
  5703. Client cli(HOST, PORT);
  5704. auto res = cli.Post("/post", body, content_type.c_str());
  5705. ASSERT_TRUE(res);
  5706. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5707. }
  5708. TEST(MultipartFormDataTest, WithPreamble) {
  5709. Server svr;
  5710. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5711. res.set_content("ok", "text/plain");
  5712. });
  5713. thread t = thread([&] { svr.listen(HOST, PORT); });
  5714. auto se = detail::scope_exit([&] {
  5715. svr.stop();
  5716. t.join();
  5717. ASSERT_FALSE(svr.is_running());
  5718. });
  5719. svr.wait_until_ready();
  5720. const std::string body =
  5721. "This is the preamble. It is to be ignored, though it\r\n"
  5722. "is a handy place for composition agents to include an\r\n"
  5723. "explanatory note to non-MIME conformant readers.\r\n"
  5724. "\r\n"
  5725. "\r\n"
  5726. "--simple boundary\r\n"
  5727. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5728. "\r\n"
  5729. "value1\r\n"
  5730. "--simple boundary\r\n"
  5731. "Content-Disposition: form-data; name=\"field2\"; "
  5732. "filename=\"example.txt\"\r\n"
  5733. "\r\n"
  5734. "value2\r\n"
  5735. "--simple boundary--\r\n"
  5736. "This is the epilogue. It is also to be ignored.\r\n";
  5737. std::string content_type =
  5738. R"(multipart/form-data; boundary="simple boundary")";
  5739. Client cli(HOST, PORT);
  5740. auto res = cli.Post("/post", body, content_type.c_str());
  5741. ASSERT_TRUE(res);
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. }
  5744. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5746. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5747. const ContentReader &content_reader) {
  5748. if (req.is_multipart_form_data()) {
  5749. MultipartFormDataItems files;
  5750. content_reader(
  5751. [&](const MultipartFormData &file) {
  5752. files.push_back(file);
  5753. return true;
  5754. },
  5755. [&](const char *data, size_t data_length) {
  5756. files.back().content.append(data, data_length);
  5757. return true;
  5758. });
  5759. EXPECT_TRUE(std::string(files[0].name) == "document");
  5760. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5761. EXPECT_TRUE(files[0].filename == "2MB_data");
  5762. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5763. EXPECT_TRUE(files[1].name == "hello");
  5764. EXPECT_TRUE(files[1].content == "world");
  5765. EXPECT_TRUE(files[1].filename == "");
  5766. EXPECT_TRUE(files[1].content_type == "");
  5767. } else {
  5768. std::string body;
  5769. content_reader([&](const char *data, size_t data_length) {
  5770. body.append(data, data_length);
  5771. return true;
  5772. });
  5773. }
  5774. });
  5775. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5776. auto se = detail::scope_exit([&] {
  5777. svr.stop();
  5778. t.join();
  5779. ASSERT_FALSE(svr.is_running());
  5780. });
  5781. svr.wait_until_ready();
  5782. {
  5783. std::string data(1024 * 1024 * 2, '.');
  5784. std::stringstream buffer;
  5785. buffer << data;
  5786. Client cli("https://localhost:8080");
  5787. cli.enable_server_certificate_verification(false);
  5788. MultipartFormDataItems items{
  5789. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5790. {"hello", "world", "", ""},
  5791. };
  5792. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5793. ASSERT_TRUE(res);
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. }
  5796. }
  5797. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5798. std::string data(1024 * 1024 * 2, '&');
  5799. std::stringstream buffer;
  5800. buffer << data;
  5801. Client cli("https://localhost:8080");
  5802. MultipartFormDataItems items{
  5803. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5804. {"hello", "world", "", ""},
  5805. };
  5806. for (const char &c : " \t\r\n") {
  5807. auto res =
  5808. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5809. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5810. ASSERT_FALSE(res);
  5811. }
  5812. }
  5813. TEST(MultipartFormDataTest, PutFormData) {
  5814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5815. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5816. const ContentReader &content_reader) {
  5817. if (req.is_multipart_form_data()) {
  5818. MultipartFormDataItems files;
  5819. content_reader(
  5820. [&](const MultipartFormData &file) {
  5821. files.push_back(file);
  5822. return true;
  5823. },
  5824. [&](const char *data, size_t data_length) {
  5825. files.back().content.append(data, data_length);
  5826. return true;
  5827. });
  5828. EXPECT_TRUE(std::string(files[0].name) == "document");
  5829. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5830. EXPECT_TRUE(files[0].filename == "2MB_data");
  5831. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5832. EXPECT_TRUE(files[1].name == "hello");
  5833. EXPECT_TRUE(files[1].content == "world");
  5834. EXPECT_TRUE(files[1].filename == "");
  5835. EXPECT_TRUE(files[1].content_type == "");
  5836. } else {
  5837. std::string body;
  5838. content_reader([&](const char *data, size_t data_length) {
  5839. body.append(data, data_length);
  5840. return true;
  5841. });
  5842. }
  5843. });
  5844. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5845. auto se = detail::scope_exit([&] {
  5846. svr.stop();
  5847. t.join();
  5848. ASSERT_FALSE(svr.is_running());
  5849. });
  5850. svr.wait_until_ready();
  5851. {
  5852. std::string data(1024 * 1024 * 2, '&');
  5853. std::stringstream buffer;
  5854. buffer << data;
  5855. Client cli("https://localhost:8080");
  5856. cli.enable_server_certificate_verification(false);
  5857. MultipartFormDataItems items{
  5858. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5859. {"hello", "world", "", ""},
  5860. };
  5861. auto res = cli.Put("/put", items);
  5862. ASSERT_TRUE(res);
  5863. ASSERT_EQ(StatusCode::OK_200, res->status);
  5864. }
  5865. }
  5866. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5868. svr.Put("/put_customboundary",
  5869. [&](const Request &req, const Response & /*res*/,
  5870. const ContentReader &content_reader) {
  5871. if (req.is_multipart_form_data()) {
  5872. MultipartFormDataItems files;
  5873. content_reader(
  5874. [&](const MultipartFormData &file) {
  5875. files.push_back(file);
  5876. return true;
  5877. },
  5878. [&](const char *data, size_t data_length) {
  5879. files.back().content.append(data, data_length);
  5880. return true;
  5881. });
  5882. EXPECT_TRUE(std::string(files[0].name) == "document");
  5883. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5884. EXPECT_TRUE(files[0].filename == "2MB_data");
  5885. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5886. EXPECT_TRUE(files[1].name == "hello");
  5887. EXPECT_TRUE(files[1].content == "world");
  5888. EXPECT_TRUE(files[1].filename == "");
  5889. EXPECT_TRUE(files[1].content_type == "");
  5890. } else {
  5891. std::string body;
  5892. content_reader([&](const char *data, size_t data_length) {
  5893. body.append(data, data_length);
  5894. return true;
  5895. });
  5896. }
  5897. });
  5898. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5899. auto se = detail::scope_exit([&] {
  5900. svr.stop();
  5901. t.join();
  5902. ASSERT_FALSE(svr.is_running());
  5903. });
  5904. svr.wait_until_ready();
  5905. {
  5906. std::string data(1024 * 1024 * 2, '&');
  5907. std::stringstream buffer;
  5908. buffer << data;
  5909. Client cli("https://localhost:8080");
  5910. cli.enable_server_certificate_verification(false);
  5911. MultipartFormDataItems items{
  5912. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5913. {"hello", "world", "", ""},
  5914. };
  5915. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5916. ASSERT_TRUE(res);
  5917. ASSERT_EQ(StatusCode::OK_200, res->status);
  5918. }
  5919. }
  5920. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5921. std::string data(1024 * 1024 * 2, '&');
  5922. std::stringstream buffer;
  5923. buffer << data;
  5924. Client cli("https://localhost:8080");
  5925. cli.enable_server_certificate_verification(false);
  5926. MultipartFormDataItems items{
  5927. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5928. {"hello", "world", "", ""},
  5929. };
  5930. for (const char &c : " \t\r\n") {
  5931. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5932. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5933. ASSERT_FALSE(res);
  5934. }
  5935. }
  5936. TEST(MultipartFormDataTest, AlternateFilename) {
  5937. auto handled = false;
  5938. Server svr;
  5939. svr.Post("/test", [&](const Request &req, Response &res) {
  5940. ASSERT_EQ(3u, req.files.size());
  5941. auto it = req.files.begin();
  5942. ASSERT_EQ("file1", it->second.name);
  5943. ASSERT_EQ("A.txt", it->second.filename);
  5944. ASSERT_EQ("text/plain", it->second.content_type);
  5945. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5946. ++it;
  5947. ASSERT_EQ("file2", it->second.name);
  5948. ASSERT_EQ("a.html", it->second.filename);
  5949. ASSERT_EQ("text/html", it->second.content_type);
  5950. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5951. it->second.content);
  5952. ++it;
  5953. ASSERT_EQ("text", it->second.name);
  5954. ASSERT_EQ("", it->second.filename);
  5955. ASSERT_EQ("", it->second.content_type);
  5956. ASSERT_EQ("text default", it->second.content);
  5957. res.set_content("ok", "text/plain");
  5958. handled = true;
  5959. });
  5960. thread t = thread([&] { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. ASSERT_TRUE(handled);
  5966. });
  5967. svr.wait_until_ready();
  5968. auto req = "POST /test HTTP/1.1\r\n"
  5969. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5970. "Content-Length: 399\r\n"
  5971. "\r\n"
  5972. "----------\r\n"
  5973. "Content-Disposition: form-data; name=\"text\"\r\n"
  5974. "\r\n"
  5975. "text default\r\n"
  5976. "----------\r\n"
  5977. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  5978. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5979. "Content-Type: text/plain\r\n"
  5980. "\r\n"
  5981. "Content of a.txt.\r\n"
  5982. "\r\n"
  5983. "----------\r\n"
  5984. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5985. "\"a.html\"\r\n"
  5986. "Content-Type: text/html\r\n"
  5987. "\r\n"
  5988. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5989. "\r\n"
  5990. "------------\r\n";
  5991. ASSERT_TRUE(send_request(1, req));
  5992. }
  5993. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5994. auto handled = false;
  5995. Server svr;
  5996. svr.Post("/test", [&](const Request &req, Response &) {
  5997. ASSERT_EQ(2u, req.files.size());
  5998. auto it = req.files.begin();
  5999. ASSERT_EQ("text1", it->second.name);
  6000. ASSERT_EQ("text1", it->second.content);
  6001. ++it;
  6002. ASSERT_EQ("text2", it->second.name);
  6003. ASSERT_EQ("text2", it->second.content);
  6004. handled = true;
  6005. });
  6006. thread t = thread([&] { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. ASSERT_FALSE(svr.is_running());
  6011. ASSERT_TRUE(handled);
  6012. });
  6013. svr.wait_until_ready();
  6014. auto req = "POST /test HTTP/1.1\r\n"
  6015. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6016. "Content-Length: 146\r\n"
  6017. "\r\n----------\r\n"
  6018. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6019. "\r\n"
  6020. "text1"
  6021. "\r\n----------\r\n"
  6022. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6023. "\r\n"
  6024. "text2"
  6025. "\r\n------------";
  6026. std::string resonse;
  6027. ASSERT_TRUE(send_request(1, req, &resonse));
  6028. ASSERT_EQ("200", resonse.substr(9, 3));
  6029. }
  6030. TEST(MultipartFormDataTest, ContentLength) {
  6031. auto handled = false;
  6032. Server svr;
  6033. svr.Post("/test", [&](const Request &req, Response &) {
  6034. ASSERT_EQ(2u, req.files.size());
  6035. auto it = req.files.begin();
  6036. ASSERT_EQ("text1", it->second.name);
  6037. ASSERT_EQ("text1", it->second.content);
  6038. ++it;
  6039. ASSERT_EQ("text2", it->second.name);
  6040. ASSERT_EQ("text2", it->second.content);
  6041. handled = true;
  6042. });
  6043. thread t = thread([&] { svr.listen(HOST, PORT); });
  6044. auto se = detail::scope_exit([&] {
  6045. svr.stop();
  6046. t.join();
  6047. ASSERT_FALSE(svr.is_running());
  6048. ASSERT_TRUE(handled);
  6049. });
  6050. svr.wait_until_ready();
  6051. auto req = "POST /test HTTP/1.1\r\n"
  6052. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6053. "Content-Length: 167\r\n"
  6054. "\r\n----------\r\n"
  6055. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6056. "Content-Length: 5\r\n"
  6057. "\r\n"
  6058. "text1"
  6059. "\r\n----------\r\n"
  6060. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6061. "\r\n"
  6062. "text2"
  6063. "\r\n------------\r\n";
  6064. std::string resonse;
  6065. ASSERT_TRUE(send_request(1, req, &resonse));
  6066. ASSERT_EQ("200", resonse.substr(9, 3));
  6067. }
  6068. #endif
  6069. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6070. static constexpr unsigned int number_of_tasks{1000000};
  6071. std::atomic_uint count{0};
  6072. std::unique_ptr<TaskQueue> task_queue{
  6073. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6074. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6075. auto queued = task_queue->enqueue(
  6076. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6077. EXPECT_TRUE(queued);
  6078. }
  6079. EXPECT_NO_THROW(task_queue->shutdown());
  6080. EXPECT_EQ(number_of_tasks, count.load());
  6081. }
  6082. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6083. static constexpr unsigned int number_of_tasks{1000000};
  6084. static constexpr unsigned int qlimit{2};
  6085. unsigned int queued_count{0};
  6086. std::atomic_uint count{0};
  6087. std::unique_ptr<TaskQueue> task_queue{
  6088. new ThreadPool{/*num_threads=*/1, qlimit}};
  6089. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6090. if (task_queue->enqueue(
  6091. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6092. queued_count++;
  6093. }
  6094. }
  6095. EXPECT_NO_THROW(task_queue->shutdown());
  6096. EXPECT_EQ(queued_count, count.load());
  6097. EXPECT_TRUE(queued_count <= number_of_tasks);
  6098. EXPECT_TRUE(queued_count >= qlimit);
  6099. }
  6100. TEST(TaskQueueTest, MaxQueuedRequests) {
  6101. static constexpr unsigned int qlimit{3};
  6102. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6103. std::condition_variable sem_cv;
  6104. std::mutex sem_mtx;
  6105. int credits = 0;
  6106. bool queued;
  6107. /* Fill up the queue with tasks that will block until we give them credits to
  6108. * complete. */
  6109. for (unsigned int n = 0; n <= qlimit;) {
  6110. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6111. std::unique_lock<std::mutex> lock(sem_mtx);
  6112. while (credits <= 0) {
  6113. sem_cv.wait(lock);
  6114. }
  6115. /* Consume the credit and signal the test code if they are all gone. */
  6116. if (--credits == 0) { sem_cv.notify_one(); }
  6117. });
  6118. if (n < qlimit) {
  6119. /* The first qlimit enqueues must succeed. */
  6120. EXPECT_TRUE(queued);
  6121. } else {
  6122. /* The last one will succeed only when the worker thread
  6123. * starts and dequeues the first blocking task. Although
  6124. * not necessary for the correctness of this test, we sleep for
  6125. * a short while to avoid busy waiting. */
  6126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6127. }
  6128. if (queued) { n++; }
  6129. }
  6130. /* Further enqueues must fail since the queue is full. */
  6131. for (auto i = 0; i < 4; i++) {
  6132. queued = task_queue->enqueue([] {});
  6133. EXPECT_FALSE(queued);
  6134. }
  6135. /* Give the credits to allow the previous tasks to complete. */
  6136. {
  6137. std::unique_lock<std::mutex> lock(sem_mtx);
  6138. credits += qlimit + 1;
  6139. }
  6140. sem_cv.notify_all();
  6141. /* Wait for all the credits to be consumed. */
  6142. {
  6143. std::unique_lock<std::mutex> lock(sem_mtx);
  6144. while (credits > 0) {
  6145. sem_cv.wait(lock);
  6146. }
  6147. }
  6148. /* Check that we are able again to enqueue at least qlimit tasks. */
  6149. for (unsigned int i = 0; i < qlimit; i++) {
  6150. queued = task_queue->enqueue([] {});
  6151. EXPECT_TRUE(queued);
  6152. }
  6153. EXPECT_NO_THROW(task_queue->shutdown());
  6154. }
  6155. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6156. Server svr;
  6157. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6158. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6159. });
  6160. svr.Get("/hello", [](const Request &req, Response &res) {
  6161. res.set_content(req.get_param_value("key"), "text/plain");
  6162. });
  6163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6164. auto se = detail::scope_exit([&] {
  6165. svr.stop();
  6166. thread.join();
  6167. ASSERT_FALSE(svr.is_running());
  6168. });
  6169. svr.wait_until_ready();
  6170. {
  6171. Client cli(HOST, PORT);
  6172. cli.set_follow_location(true);
  6173. auto res = cli.Get("/");
  6174. ASSERT_TRUE(res);
  6175. EXPECT_EQ(StatusCode::OK_200, res->status);
  6176. EXPECT_EQ("val&key2=val2", res->body);
  6177. }
  6178. }
  6179. TEST(VulnerabilityTest, CRLFInjection) {
  6180. Server svr;
  6181. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6182. res.set_content("Hello 1", "text/plain");
  6183. });
  6184. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6185. res.set_content("Hello 2", "text/plain");
  6186. });
  6187. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6188. res.set_content("Hello 3", "text/plain");
  6189. });
  6190. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6191. res.set_content("Hello 4", "text/plain");
  6192. });
  6193. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6194. for (const auto &x : req.headers) {
  6195. auto key = x.first;
  6196. EXPECT_STRNE("evil", key.c_str());
  6197. }
  6198. });
  6199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6200. auto se = detail::scope_exit([&] {
  6201. svr.stop();
  6202. thread.join();
  6203. ASSERT_FALSE(svr.is_running());
  6204. });
  6205. svr.wait_until_ready();
  6206. {
  6207. Client cli(HOST, PORT);
  6208. cli.Post("/test1", "A=B",
  6209. "application/x-www-form-urlencoded\r\nevil: hello1");
  6210. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6211. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6212. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6213. }
  6214. }
  6215. TEST(PathParamsTest, StaticMatch) {
  6216. const auto pattern = "/users/all";
  6217. detail::PathParamsMatcher matcher(pattern);
  6218. Request request;
  6219. request.path = "/users/all";
  6220. ASSERT_TRUE(matcher.match(request));
  6221. std::unordered_map<std::string, std::string> expected_params = {};
  6222. EXPECT_EQ(request.path_params, expected_params);
  6223. }
  6224. TEST(PathParamsTest, StaticMismatch) {
  6225. const auto pattern = "/users/all";
  6226. detail::PathParamsMatcher matcher(pattern);
  6227. Request request;
  6228. request.path = "/users/1";
  6229. ASSERT_FALSE(matcher.match(request));
  6230. }
  6231. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6232. const auto pattern = "/users/:id/subscriptions";
  6233. detail::PathParamsMatcher matcher(pattern);
  6234. Request request;
  6235. request.path = "/users/42/subscriptions";
  6236. ASSERT_TRUE(matcher.match(request));
  6237. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6238. EXPECT_EQ(request.path_params, expected_params);
  6239. }
  6240. TEST(PathParamsTest, SingleParamInTheEnd) {
  6241. const auto pattern = "/users/:id";
  6242. detail::PathParamsMatcher matcher(pattern);
  6243. Request request;
  6244. request.path = "/users/24";
  6245. ASSERT_TRUE(matcher.match(request));
  6246. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6247. EXPECT_EQ(request.path_params, expected_params);
  6248. }
  6249. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6250. const auto pattern = "/users/:id/";
  6251. detail::PathParamsMatcher matcher(pattern);
  6252. Request request;
  6253. request.path = "/users/42/";
  6254. ASSERT_TRUE(matcher.match(request));
  6255. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6256. EXPECT_EQ(request.path_params, expected_params);
  6257. }
  6258. TEST(PathParamsTest, EmptyParam) {
  6259. const auto pattern = "/users/:id/";
  6260. detail::PathParamsMatcher matcher(pattern);
  6261. Request request;
  6262. request.path = "/users//";
  6263. ASSERT_TRUE(matcher.match(request));
  6264. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6265. EXPECT_EQ(request.path_params, expected_params);
  6266. }
  6267. TEST(PathParamsTest, FragmentMismatch) {
  6268. const auto pattern = "/users/:id/";
  6269. detail::PathParamsMatcher matcher(pattern);
  6270. Request request;
  6271. request.path = "/admins/24/";
  6272. ASSERT_FALSE(matcher.match(request));
  6273. }
  6274. TEST(PathParamsTest, ExtraFragments) {
  6275. const auto pattern = "/users/:id";
  6276. detail::PathParamsMatcher matcher(pattern);
  6277. Request request;
  6278. request.path = "/users/42/subscriptions";
  6279. ASSERT_FALSE(matcher.match(request));
  6280. }
  6281. TEST(PathParamsTest, MissingTrailingParam) {
  6282. const auto pattern = "/users/:id";
  6283. detail::PathParamsMatcher matcher(pattern);
  6284. Request request;
  6285. request.path = "/users";
  6286. ASSERT_FALSE(matcher.match(request));
  6287. }
  6288. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6289. const auto pattern = "/users/:id/subscriptions";
  6290. detail::PathParamsMatcher matcher(pattern);
  6291. Request request;
  6292. request.path = "/users/subscriptions";
  6293. ASSERT_FALSE(matcher.match(request));
  6294. }
  6295. TEST(PathParamsTest, MultipleParams) {
  6296. const auto pattern = "/users/:userid/subscriptions/:subid";
  6297. detail::PathParamsMatcher matcher(pattern);
  6298. Request request;
  6299. request.path = "/users/42/subscriptions/2";
  6300. ASSERT_TRUE(matcher.match(request));
  6301. std::unordered_map<std::string, std::string> expected_params = {
  6302. {"userid", "42"}, {"subid", "2"}};
  6303. EXPECT_EQ(request.path_params, expected_params);
  6304. }
  6305. TEST(PathParamsTest, SequenceOfParams) {
  6306. const auto pattern = "/values/:x/:y/:z";
  6307. detail::PathParamsMatcher matcher(pattern);
  6308. Request request;
  6309. request.path = "/values/1/2/3";
  6310. ASSERT_TRUE(matcher.match(request));
  6311. std::unordered_map<std::string, std::string> expected_params = {
  6312. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6313. EXPECT_EQ(request.path_params, expected_params);
  6314. }
  6315. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6316. // If ipv6 regex working, regex match codepath is taken.
  6317. // else port will default to 80 in Client impl
  6318. int clientImplMagicPort = 80;
  6319. int port = 4321;
  6320. // above ports must be different to avoid false negative
  6321. EXPECT_NE(clientImplMagicPort, port);
  6322. std::string ipV6TestURL = "http://[ff06::c3]";
  6323. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6324. CLIENT_PRIVATE_KEY_FILE);
  6325. EXPECT_EQ(cli.port(), port);
  6326. }
  6327. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6328. auto file_path = "./www/dir/index.html";
  6329. auto dir_path = "./www/dir";
  6330. EXPECT_TRUE(detail::is_file(file_path));
  6331. EXPECT_FALSE(detail::is_dir(file_path));
  6332. EXPECT_FALSE(detail::is_file(dir_path));
  6333. EXPECT_TRUE(detail::is_dir(dir_path));
  6334. }
  6335. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6336. Server svr;
  6337. svr.Get("/test", [&](const Request &req, Response &) {
  6338. auto val = req.get_header_value("Test");
  6339. EXPECT_EQ(val.size(), 7u);
  6340. EXPECT_EQ(val, "_ _ _");
  6341. });
  6342. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6343. auto se = detail::scope_exit([&] {
  6344. svr.stop();
  6345. thread.join();
  6346. ASSERT_FALSE(svr.is_running());
  6347. });
  6348. svr.wait_until_ready();
  6349. Client cli(HOST, PORT);
  6350. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6351. }