test.cc 231 KB

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