test.cc 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854
  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("/file_content",
  1882. [&](const Request & /*req*/, Response &res) {
  1883. res.set_file_content("./www/dir/test.html");
  1884. })
  1885. .Get("/file_content_with_content_type",
  1886. [&](const Request & /*req*/, Response &res) {
  1887. res.set_file_content("./www/file", "text/plain");
  1888. })
  1889. .Get("/invalid_file_content",
  1890. [&](const Request & /*req*/, Response &res) {
  1891. res.set_file_content("./www/dir/invalid_file_path");
  1892. })
  1893. .Get("/http_response_splitting",
  1894. [&](const Request & /*req*/, Response &res) {
  1895. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1896. EXPECT_EQ(0U, res.headers.size());
  1897. EXPECT_FALSE(res.has_header("a"));
  1898. res.set_header("a", "1\nSet-Cookie: a=1");
  1899. EXPECT_EQ(0U, res.headers.size());
  1900. EXPECT_FALSE(res.has_header("a"));
  1901. res.set_header("a", "1\rSet-Cookie: a=1");
  1902. EXPECT_EQ(0U, res.headers.size());
  1903. EXPECT_FALSE(res.has_header("a"));
  1904. res.set_header("a\r\nb", "0");
  1905. EXPECT_EQ(0U, res.headers.size());
  1906. EXPECT_FALSE(res.has_header("a"));
  1907. res.set_header("a\rb", "0");
  1908. EXPECT_EQ(0U, res.headers.size());
  1909. EXPECT_FALSE(res.has_header("a"));
  1910. res.set_header("a\nb", "0");
  1911. EXPECT_EQ(0U, res.headers.size());
  1912. EXPECT_FALSE(res.has_header("a"));
  1913. res.set_redirect("1\r\nSet-Cookie: a=1");
  1914. EXPECT_EQ(0U, res.headers.size());
  1915. EXPECT_FALSE(res.has_header("Location"));
  1916. })
  1917. .Get("/slow",
  1918. [&](const Request & /*req*/, Response &res) {
  1919. std::this_thread::sleep_for(std::chrono::seconds(2));
  1920. res.set_content("slow", "text/plain");
  1921. })
  1922. #if 0
  1923. .Post("/slowpost",
  1924. [&](const Request & /*req*/, Response &res) {
  1925. std::this_thread::sleep_for(std::chrono::seconds(2));
  1926. res.set_content("slow", "text/plain");
  1927. })
  1928. #endif
  1929. .Get("/remote_addr",
  1930. [&](const Request &req, Response &res) {
  1931. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1932. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1933. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1934. EXPECT_EQ(req.remote_port,
  1935. std::stoi(req.get_header_value("REMOTE_PORT")));
  1936. res.set_content(remote_addr.c_str(), "text/plain");
  1937. })
  1938. .Get("/local_addr",
  1939. [&](const Request &req, Response &res) {
  1940. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1941. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1942. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1943. auto local_port = req.get_header_value("LOCAL_PORT");
  1944. EXPECT_EQ(req.local_addr, local_addr);
  1945. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1946. res.set_content(local_addr.append(":").append(local_port),
  1947. "text/plain");
  1948. })
  1949. .Get("/endwith%",
  1950. [&](const Request & /*req*/, Response &res) {
  1951. res.set_content("Hello World!", "text/plain");
  1952. })
  1953. .Get("/a\\+\\+b",
  1954. [&](const Request &req, Response &res) {
  1955. ASSERT_TRUE(req.has_param("a +b"));
  1956. auto val = req.get_param_value("a +b");
  1957. res.set_content(val, "text/plain");
  1958. })
  1959. .Get("/", [&](const Request & /*req*/,
  1960. Response &res) { res.set_redirect("/hi"); })
  1961. .Post("/1",
  1962. [](const Request & /*req*/, Response &res) {
  1963. res.set_redirect("/2", StatusCode::SeeOther_303);
  1964. })
  1965. .Get("/2",
  1966. [](const Request & /*req*/, Response &res) {
  1967. res.set_content("redirected.", "text/plain");
  1968. res.status = StatusCode::OK_200;
  1969. })
  1970. .Post("/person",
  1971. [&](const Request &req, Response &res) {
  1972. if (req.has_param("name") && req.has_param("note")) {
  1973. persons_[req.get_param_value("name")] =
  1974. req.get_param_value("note");
  1975. } else {
  1976. res.status = StatusCode::BadRequest_400;
  1977. }
  1978. })
  1979. .Put("/person",
  1980. [&](const Request &req, Response &res) {
  1981. if (req.has_param("name") && req.has_param("note")) {
  1982. persons_[req.get_param_value("name")] =
  1983. req.get_param_value("note");
  1984. } else {
  1985. res.status = StatusCode::BadRequest_400;
  1986. }
  1987. })
  1988. .Get("/person/(.*)",
  1989. [&](const Request &req, Response &res) {
  1990. string name = req.matches[1];
  1991. if (persons_.find(name) != persons_.end()) {
  1992. auto note = persons_[name];
  1993. res.set_content(note, "text/plain");
  1994. } else {
  1995. res.status = StatusCode::NotFound_404;
  1996. }
  1997. })
  1998. .Post("/x-www-form-urlencoded-json",
  1999. [&](const Request &req, Response &res) {
  2000. auto json = req.get_param_value("json");
  2001. ASSERT_EQ(JSON_DATA, json);
  2002. res.set_content(json, "appliation/json");
  2003. res.status = StatusCode::OK_200;
  2004. })
  2005. .Get("/streamed-chunked",
  2006. [&](const Request & /*req*/, Response &res) {
  2007. res.set_chunked_content_provider(
  2008. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2009. sink.os << "123";
  2010. sink.os << "456";
  2011. sink.os << "789";
  2012. sink.done();
  2013. return true;
  2014. });
  2015. })
  2016. .Get("/streamed-chunked2",
  2017. [&](const Request & /*req*/, Response &res) {
  2018. auto i = new int(0);
  2019. res.set_chunked_content_provider(
  2020. "text/plain",
  2021. [i](size_t /*offset*/, DataSink &sink) {
  2022. switch (*i) {
  2023. case 0: sink.os << "123"; break;
  2024. case 1: sink.os << "456"; break;
  2025. case 2: sink.os << "789"; break;
  2026. case 3: sink.done(); break;
  2027. }
  2028. (*i)++;
  2029. return true;
  2030. },
  2031. [i](bool success) {
  2032. EXPECT_TRUE(success);
  2033. delete i;
  2034. });
  2035. })
  2036. .Get("/streamed-chunked-with-trailer",
  2037. [&](const Request & /*req*/, Response &res) {
  2038. auto i = new int(0);
  2039. res.set_header("Trailer", "Dummy1, Dummy2");
  2040. res.set_chunked_content_provider(
  2041. "text/plain",
  2042. [i](size_t /*offset*/, DataSink &sink) {
  2043. switch (*i) {
  2044. case 0: sink.os << "123"; break;
  2045. case 1: sink.os << "456"; break;
  2046. case 2: sink.os << "789"; break;
  2047. case 3: {
  2048. sink.done_with_trailer(
  2049. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2050. } break;
  2051. }
  2052. (*i)++;
  2053. return true;
  2054. },
  2055. [i](bool success) {
  2056. EXPECT_TRUE(success);
  2057. delete i;
  2058. });
  2059. })
  2060. .Get("/streamed",
  2061. [&](const Request & /*req*/, Response &res) {
  2062. res.set_content_provider(
  2063. 6, "text/plain",
  2064. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2065. sink.os << (offset < 3 ? "a" : "b");
  2066. return true;
  2067. });
  2068. })
  2069. .Get("/streamed-with-range",
  2070. [&](const Request &req, Response &res) {
  2071. auto data = new std::string("abcdefg");
  2072. res.set_content_provider(
  2073. data->size(), "text/plain",
  2074. [data](size_t offset, size_t length, DataSink &sink) {
  2075. size_t DATA_CHUNK_SIZE = 4;
  2076. const auto &d = *data;
  2077. auto out_len =
  2078. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2079. auto ret =
  2080. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2081. EXPECT_TRUE(ret);
  2082. return true;
  2083. },
  2084. [data, &req](bool success) {
  2085. EXPECT_EQ(success, !req.has_param("error"));
  2086. delete data;
  2087. });
  2088. })
  2089. .Get("/streamed-cancel",
  2090. [&](const Request & /*req*/, Response &res) {
  2091. res.set_content_provider(
  2092. size_t(-1), "text/plain",
  2093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2094. sink.os << "data_chunk";
  2095. return true;
  2096. });
  2097. })
  2098. .Get("/regex-with-delimiter",
  2099. [&](const Request &req, Response & /*res*/) {
  2100. ASSERT_TRUE(req.has_param("key"));
  2101. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2102. })
  2103. .Get("/with-range",
  2104. [&](const Request & /*req*/, Response &res) {
  2105. res.set_content("abcdefg", "text/plain");
  2106. })
  2107. .Get("/with-range-customized-response",
  2108. [&](const Request & /*req*/, Response &res) {
  2109. res.status = StatusCode::BadRequest_400;
  2110. res.set_content(JSON_DATA, "application/json");
  2111. })
  2112. .Post("/chunked",
  2113. [&](const Request &req, Response & /*res*/) {
  2114. EXPECT_EQ(req.body, "dechunked post body");
  2115. })
  2116. .Post("/large-chunked",
  2117. [&](const Request &req, Response & /*res*/) {
  2118. std::string expected(6 * 30 * 1024u, 'a');
  2119. EXPECT_EQ(req.body, expected);
  2120. })
  2121. .Post("/multipart",
  2122. [&](const Request &req, Response & /*res*/) {
  2123. EXPECT_EQ(6u, req.files.size());
  2124. ASSERT_TRUE(!req.has_file("???"));
  2125. ASSERT_TRUE(req.body.empty());
  2126. {
  2127. const auto &file = req.get_file_value("text1");
  2128. EXPECT_TRUE(file.filename.empty());
  2129. EXPECT_EQ("text default", file.content);
  2130. }
  2131. {
  2132. const auto &file = req.get_file_value("text2");
  2133. EXPECT_TRUE(file.filename.empty());
  2134. EXPECT_EQ("aωb", file.content);
  2135. }
  2136. {
  2137. const auto &file = req.get_file_value("file1");
  2138. EXPECT_EQ("hello.txt", file.filename);
  2139. EXPECT_EQ("text/plain", file.content_type);
  2140. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2141. }
  2142. {
  2143. const auto &file = req.get_file_value("file3");
  2144. EXPECT_TRUE(file.filename.empty());
  2145. EXPECT_EQ("application/octet-stream", file.content_type);
  2146. EXPECT_EQ(0u, file.content.size());
  2147. }
  2148. {
  2149. const auto &file = req.get_file_value("file4");
  2150. EXPECT_TRUE(file.filename.empty());
  2151. EXPECT_EQ(0u, file.content.size());
  2152. EXPECT_EQ("application/json tmp-string", file.content_type);
  2153. }
  2154. })
  2155. .Post("/multipart/multi_file_values",
  2156. [&](const Request &req, Response & /*res*/) {
  2157. EXPECT_EQ(5u, req.files.size());
  2158. ASSERT_TRUE(!req.has_file("???"));
  2159. ASSERT_TRUE(req.body.empty());
  2160. {
  2161. const auto &text_value = req.get_file_values("text");
  2162. EXPECT_EQ(1u, text_value.size());
  2163. auto &text = text_value[0];
  2164. EXPECT_TRUE(text.filename.empty());
  2165. EXPECT_EQ("default text", text.content);
  2166. }
  2167. {
  2168. const auto &text1_values = req.get_file_values("multi_text1");
  2169. EXPECT_EQ(2u, text1_values.size());
  2170. EXPECT_EQ("aaaaa", text1_values[0].content);
  2171. EXPECT_EQ("bbbbb", text1_values[1].content);
  2172. }
  2173. {
  2174. const auto &file1_values = req.get_file_values("multi_file1");
  2175. EXPECT_EQ(2u, file1_values.size());
  2176. auto file1 = file1_values[0];
  2177. EXPECT_EQ(file1.filename, "hello.txt");
  2178. EXPECT_EQ(file1.content_type, "text/plain");
  2179. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2180. auto file2 = file1_values[1];
  2181. EXPECT_EQ(file2.filename, "world.json");
  2182. EXPECT_EQ(file2.content_type, "application/json");
  2183. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2184. }
  2185. })
  2186. .Post("/empty",
  2187. [&](const Request &req, Response &res) {
  2188. EXPECT_EQ(req.body, "");
  2189. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2190. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2191. res.set_content("empty", "text/plain");
  2192. })
  2193. .Post("/empty-no-content-type",
  2194. [&](const Request &req, Response &res) {
  2195. EXPECT_EQ(req.body, "");
  2196. EXPECT_FALSE(req.has_header("Content-Type"));
  2197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2198. res.set_content("empty-no-content-type", "text/plain");
  2199. })
  2200. .Post("/path-only",
  2201. [&](const Request &req, Response &res) {
  2202. EXPECT_EQ(req.body, "");
  2203. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2205. res.set_content("path-only", "text/plain");
  2206. })
  2207. .Post("/path-headers-only",
  2208. [&](const Request &req, Response &res) {
  2209. EXPECT_EQ(req.body, "");
  2210. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2212. EXPECT_EQ("world", req.get_header_value("hello"));
  2213. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2214. res.set_content("path-headers-only", "text/plain");
  2215. })
  2216. .Post("/post-large",
  2217. [&](const Request &req, Response &res) {
  2218. EXPECT_EQ(req.body, LARGE_DATA);
  2219. res.set_content(req.body, "text/plain");
  2220. })
  2221. .Put("/empty-no-content-type",
  2222. [&](const Request &req, Response &res) {
  2223. EXPECT_EQ(req.body, "");
  2224. EXPECT_FALSE(req.has_header("Content-Type"));
  2225. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2226. res.set_content("empty-no-content-type", "text/plain");
  2227. })
  2228. .Put("/put",
  2229. [&](const Request &req, Response &res) {
  2230. EXPECT_EQ(req.body, "PUT");
  2231. res.set_content(req.body, "text/plain");
  2232. })
  2233. .Put("/put-large",
  2234. [&](const Request &req, Response &res) {
  2235. EXPECT_EQ(req.body, LARGE_DATA);
  2236. res.set_content(req.body, "text/plain");
  2237. })
  2238. .Patch("/patch",
  2239. [&](const Request &req, Response &res) {
  2240. EXPECT_EQ(req.body, "PATCH");
  2241. res.set_content(req.body, "text/plain");
  2242. })
  2243. .Delete("/delete",
  2244. [&](const Request & /*req*/, Response &res) {
  2245. res.set_content("DELETE", "text/plain");
  2246. })
  2247. .Delete("/delete-body",
  2248. [&](const Request &req, Response &res) {
  2249. EXPECT_EQ(req.body, "content");
  2250. res.set_content(req.body, "text/plain");
  2251. })
  2252. .Options(R"(\*)",
  2253. [&](const Request & /*req*/, Response &res) {
  2254. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2255. })
  2256. .Get("/request-target",
  2257. [&](const Request &req, Response & /*res*/) {
  2258. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2259. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2260. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2261. })
  2262. .Get("/long-query-value",
  2263. [&](const Request &req, Response & /*res*/) {
  2264. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2265. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2266. })
  2267. .Get("/array-param",
  2268. [&](const Request &req, Response & /*res*/) {
  2269. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2270. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2271. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2272. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2273. })
  2274. .Post("/validate-no-multiple-headers",
  2275. [&](const Request &req, Response & /*res*/) {
  2276. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2277. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2278. })
  2279. .Post("/content_receiver",
  2280. [&](const Request &req, Response &res,
  2281. const ContentReader &content_reader) {
  2282. if (req.is_multipart_form_data()) {
  2283. MultipartFormDataItems files;
  2284. content_reader(
  2285. [&](const MultipartFormData &file) {
  2286. files.push_back(file);
  2287. return true;
  2288. },
  2289. [&](const char *data, size_t data_length) {
  2290. files.back().content.append(data, data_length);
  2291. return true;
  2292. });
  2293. EXPECT_EQ(5u, files.size());
  2294. {
  2295. const auto &file = get_file_value(files, "text1");
  2296. EXPECT_TRUE(file.filename.empty());
  2297. EXPECT_EQ("text default", file.content);
  2298. }
  2299. {
  2300. const auto &file = get_file_value(files, "text2");
  2301. EXPECT_TRUE(file.filename.empty());
  2302. EXPECT_EQ("aωb", file.content);
  2303. }
  2304. {
  2305. const auto &file = get_file_value(files, "file1");
  2306. EXPECT_EQ("hello.txt", file.filename);
  2307. EXPECT_EQ("text/plain", file.content_type);
  2308. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2309. }
  2310. {
  2311. const auto &file = get_file_value(files, "file3");
  2312. EXPECT_TRUE(file.filename.empty());
  2313. EXPECT_EQ("application/octet-stream", file.content_type);
  2314. EXPECT_EQ(0u, file.content.size());
  2315. }
  2316. } else {
  2317. std::string body;
  2318. content_reader([&](const char *data, size_t data_length) {
  2319. EXPECT_EQ(7U, 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. })
  2327. .Put("/content_receiver",
  2328. [&](const Request & /*req*/, Response &res,
  2329. const ContentReader &content_reader) {
  2330. std::string body;
  2331. content_reader([&](const char *data, size_t data_length) {
  2332. body.append(data, data_length);
  2333. return true;
  2334. });
  2335. EXPECT_EQ(body, "content");
  2336. res.set_content(body, "text/plain");
  2337. })
  2338. .Patch("/content_receiver",
  2339. [&](const Request & /*req*/, Response &res,
  2340. const ContentReader &content_reader) {
  2341. std::string body;
  2342. content_reader([&](const char *data, size_t data_length) {
  2343. body.append(data, data_length);
  2344. return true;
  2345. });
  2346. EXPECT_EQ(body, "content");
  2347. res.set_content(body, "text/plain");
  2348. })
  2349. .Post("/query-string-and-body",
  2350. [&](const Request &req, Response & /*res*/) {
  2351. ASSERT_TRUE(req.has_param("key"));
  2352. EXPECT_EQ(req.get_param_value("key"), "value");
  2353. EXPECT_EQ(req.body, "content");
  2354. })
  2355. .Get("/last-request",
  2356. [&](const Request &req, Response & /*res*/) {
  2357. EXPECT_EQ("close", req.get_header_value("Connection"));
  2358. })
  2359. .Get(R"(/redirect/(\d+))",
  2360. [&](const Request &req, Response &res) {
  2361. auto num = std::stoi(req.matches[1]) + 1;
  2362. std::string url = "/redirect/" + std::to_string(num);
  2363. res.set_redirect(url);
  2364. })
  2365. .Post("/binary",
  2366. [&](const Request &req, Response &res) {
  2367. EXPECT_EQ(4U, req.body.size());
  2368. EXPECT_EQ("application/octet-stream",
  2369. req.get_header_value("Content-Type"));
  2370. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2371. res.set_content(req.body, "application/octet-stream");
  2372. })
  2373. .Put("/binary",
  2374. [&](const Request &req, Response &res) {
  2375. EXPECT_EQ(4U, req.body.size());
  2376. EXPECT_EQ("application/octet-stream",
  2377. req.get_header_value("Content-Type"));
  2378. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2379. res.set_content(req.body, "application/octet-stream");
  2380. })
  2381. .Patch("/binary",
  2382. [&](const Request &req, Response &res) {
  2383. EXPECT_EQ(4U, req.body.size());
  2384. EXPECT_EQ("application/octet-stream",
  2385. req.get_header_value("Content-Type"));
  2386. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2387. res.set_content(req.body, "application/octet-stream");
  2388. })
  2389. .Delete("/binary",
  2390. [&](const Request &req, Response &res) {
  2391. EXPECT_EQ(4U, req.body.size());
  2392. EXPECT_EQ("application/octet-stream",
  2393. req.get_header_value("Content-Type"));
  2394. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2395. res.set_content(req.body, "application/octet-stream");
  2396. })
  2397. .Get("/issue1772",
  2398. [&](const Request & /*req*/, Response &res) {
  2399. res.status = 401;
  2400. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2401. })
  2402. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  2403. .Get("/compress",
  2404. [&](const Request & /*req*/, Response &res) {
  2405. res.set_content(
  2406. "12345678901234567890123456789012345678901234567890123456789"
  2407. "01234567890123456789012345678901234567890",
  2408. "text/plain");
  2409. })
  2410. .Get("/nocompress",
  2411. [&](const Request & /*req*/, Response &res) {
  2412. res.set_content(
  2413. "12345678901234567890123456789012345678901234567890123456789"
  2414. "01234567890123456789012345678901234567890",
  2415. "application/octet-stream");
  2416. })
  2417. .Post("/compress-multipart",
  2418. [&](const Request &req, Response & /*res*/) {
  2419. EXPECT_EQ(2u, req.files.size());
  2420. ASSERT_TRUE(!req.has_file("???"));
  2421. {
  2422. const auto &file = req.get_file_value("key1");
  2423. EXPECT_TRUE(file.filename.empty());
  2424. EXPECT_EQ("test", file.content);
  2425. }
  2426. {
  2427. const auto &file = req.get_file_value("key2");
  2428. EXPECT_TRUE(file.filename.empty());
  2429. EXPECT_EQ("--abcdefg123", file.content);
  2430. }
  2431. })
  2432. #endif
  2433. ;
  2434. persons_["john"] = "programmer";
  2435. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2436. svr_.wait_until_ready();
  2437. }
  2438. virtual void TearDown() {
  2439. svr_.stop();
  2440. if (!request_threads_.empty()) {
  2441. std::this_thread::sleep_for(std::chrono::seconds(1));
  2442. for (auto &t : request_threads_) {
  2443. t.join();
  2444. }
  2445. }
  2446. t_.join();
  2447. }
  2448. map<string, string> persons_;
  2449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2450. SSLClient cli_;
  2451. SSLServer svr_;
  2452. #else
  2453. Client cli_;
  2454. Server svr_;
  2455. #endif
  2456. thread t_;
  2457. std::vector<thread> request_threads_;
  2458. };
  2459. TEST_F(ServerTest, GetMethod200) {
  2460. auto res = cli_.Get("/hi");
  2461. ASSERT_TRUE(res);
  2462. EXPECT_EQ("HTTP/1.1", res->version);
  2463. EXPECT_EQ(StatusCode::OK_200, res->status);
  2464. EXPECT_EQ("OK", res->reason);
  2465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2466. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2467. EXPECT_EQ("Hello World!", res->body);
  2468. }
  2469. TEST_F(ServerTest, GetEmptyFile) {
  2470. auto res = cli_.Get("/empty_file");
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::OK_200, res->status);
  2473. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  2474. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  2475. EXPECT_EQ("", res->body);
  2476. }
  2477. TEST_F(ServerTest, GetFileContent) {
  2478. auto res = cli_.Get("/file_content");
  2479. ASSERT_TRUE(res);
  2480. EXPECT_EQ(StatusCode::OK_200, res->status);
  2481. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2482. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2483. EXPECT_EQ("test.html", res->body);
  2484. }
  2485. TEST_F(ServerTest, GetFileContentWithContentType) {
  2486. auto res = cli_.Get("/file_content_with_content_type");
  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_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2491. EXPECT_EQ("file\n", res->body);
  2492. }
  2493. TEST_F(ServerTest, GetInvalidFileContent) {
  2494. auto res = cli_.Get("/invalid_file_content");
  2495. ASSERT_TRUE(res);
  2496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2497. }
  2498. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2499. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2500. ASSERT_TRUE(res);
  2501. EXPECT_EQ("HTTP/1.1", res->version);
  2502. EXPECT_EQ(StatusCode::OK_200, res->status);
  2503. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2504. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2505. EXPECT_EQ("Hello World!", res->body);
  2506. }
  2507. TEST_F(ServerTest, GetMethod302) {
  2508. auto res = cli_.Get("/");
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(StatusCode::Found_302, res->status);
  2511. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2512. }
  2513. TEST_F(ServerTest, GetMethod302Redirect) {
  2514. cli_.set_follow_location(true);
  2515. auto res = cli_.Get("/");
  2516. ASSERT_TRUE(res);
  2517. EXPECT_EQ(StatusCode::OK_200, res->status);
  2518. EXPECT_EQ("Hello World!", res->body);
  2519. EXPECT_EQ("/hi", res->location);
  2520. }
  2521. TEST_F(ServerTest, GetMethod404) {
  2522. auto res = cli_.Get("/invalid");
  2523. ASSERT_TRUE(res);
  2524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2525. }
  2526. TEST_F(ServerTest, HeadMethod200) {
  2527. auto res = cli_.Head("/hi");
  2528. ASSERT_TRUE(res);
  2529. EXPECT_EQ(StatusCode::OK_200, res->status);
  2530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2531. EXPECT_TRUE(res->body.empty());
  2532. }
  2533. TEST_F(ServerTest, HeadMethod200Static) {
  2534. auto res = cli_.Head("/mount/dir/index.html");
  2535. ASSERT_TRUE(res);
  2536. EXPECT_EQ(StatusCode::OK_200, res->status);
  2537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2538. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2539. EXPECT_TRUE(res->body.empty());
  2540. }
  2541. TEST_F(ServerTest, HeadMethod404) {
  2542. auto res = cli_.Head("/invalid");
  2543. ASSERT_TRUE(res);
  2544. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2545. EXPECT_TRUE(res->body.empty());
  2546. }
  2547. TEST_F(ServerTest, GetMethodPersonJohn) {
  2548. auto res = cli_.Get("/person/john");
  2549. ASSERT_TRUE(res);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2552. EXPECT_EQ("programmer", res->body);
  2553. }
  2554. TEST_F(ServerTest, PostMethod1) {
  2555. auto res = cli_.Get("/person/john1");
  2556. ASSERT_TRUE(res);
  2557. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2558. res = cli_.Post("/person", "name=john1&note=coder",
  2559. "application/x-www-form-urlencoded");
  2560. ASSERT_TRUE(res);
  2561. ASSERT_EQ(StatusCode::OK_200, res->status);
  2562. res = cli_.Get("/person/john1");
  2563. ASSERT_TRUE(res);
  2564. ASSERT_EQ(StatusCode::OK_200, res->status);
  2565. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2566. ASSERT_EQ("coder", res->body);
  2567. }
  2568. TEST_F(ServerTest, PostMethod2) {
  2569. auto res = cli_.Get("/person/john2");
  2570. ASSERT_TRUE(res);
  2571. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2572. Params params;
  2573. params.emplace("name", "john2");
  2574. params.emplace("note", "coder");
  2575. res = cli_.Post("/person", params);
  2576. ASSERT_TRUE(res);
  2577. ASSERT_EQ(StatusCode::OK_200, res->status);
  2578. res = cli_.Get("/person/john2");
  2579. ASSERT_TRUE(res);
  2580. ASSERT_EQ(StatusCode::OK_200, res->status);
  2581. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2582. ASSERT_EQ("coder", res->body);
  2583. }
  2584. TEST_F(ServerTest, PutMethod3) {
  2585. auto res = cli_.Get("/person/john3");
  2586. ASSERT_TRUE(res);
  2587. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2588. Params params;
  2589. params.emplace("name", "john3");
  2590. params.emplace("note", "coder");
  2591. res = cli_.Put("/person", params);
  2592. ASSERT_TRUE(res);
  2593. ASSERT_EQ(StatusCode::OK_200, res->status);
  2594. res = cli_.Get("/person/john3");
  2595. ASSERT_TRUE(res);
  2596. ASSERT_EQ(StatusCode::OK_200, res->status);
  2597. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2598. ASSERT_EQ("coder", res->body);
  2599. }
  2600. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2601. Params params;
  2602. params.emplace("json", JSON_DATA);
  2603. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2604. ASSERT_TRUE(res);
  2605. ASSERT_EQ(StatusCode::OK_200, res->status);
  2606. ASSERT_EQ(JSON_DATA, res->body);
  2607. }
  2608. TEST_F(ServerTest, PostEmptyContent) {
  2609. auto res = cli_.Post("/empty", "", "text/plain");
  2610. ASSERT_TRUE(res);
  2611. ASSERT_EQ(StatusCode::OK_200, res->status);
  2612. ASSERT_EQ("empty", res->body);
  2613. }
  2614. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2615. auto res = cli_.Post("/empty-no-content-type");
  2616. ASSERT_TRUE(res);
  2617. ASSERT_EQ(StatusCode::OK_200, res->status);
  2618. ASSERT_EQ("empty-no-content-type", res->body);
  2619. }
  2620. TEST_F(ServerTest, PostPathOnly) {
  2621. auto res = cli_.Post("/path-only");
  2622. ASSERT_TRUE(res);
  2623. ASSERT_EQ(StatusCode::OK_200, res->status);
  2624. ASSERT_EQ("path-only", res->body);
  2625. }
  2626. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2627. auto res = cli_.Post("/path-headers-only",
  2628. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2629. ASSERT_TRUE(res);
  2630. ASSERT_EQ(StatusCode::OK_200, res->status);
  2631. ASSERT_EQ("path-headers-only", res->body);
  2632. }
  2633. TEST_F(ServerTest, PostLarge) {
  2634. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2635. ASSERT_TRUE(res);
  2636. ASSERT_EQ(StatusCode::OK_200, res->status);
  2637. EXPECT_EQ(LARGE_DATA, res->body);
  2638. }
  2639. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2640. auto res = cli_.Put("/empty-no-content-type");
  2641. ASSERT_TRUE(res);
  2642. ASSERT_EQ(StatusCode::OK_200, res->status);
  2643. ASSERT_EQ("empty-no-content-type", res->body);
  2644. }
  2645. TEST_F(ServerTest, GetMethodDir) {
  2646. auto res = cli_.Get("/dir/");
  2647. ASSERT_TRUE(res);
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2650. auto body = R"(<html>
  2651. <head>
  2652. </head>
  2653. <body>
  2654. <a href="/dir/test.html">Test</a>
  2655. <a href="/hi">hi</a>
  2656. </body>
  2657. </html>
  2658. )";
  2659. EXPECT_EQ(body, res->body);
  2660. }
  2661. TEST_F(ServerTest, GetMethodDirTest) {
  2662. auto res = cli_.Get("/dir/test.html");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2666. EXPECT_EQ("test.html", res->body);
  2667. }
  2668. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2669. auto res = cli_.Get("/dir/../dir/test.html");
  2670. ASSERT_TRUE(res);
  2671. EXPECT_EQ(StatusCode::OK_200, res->status);
  2672. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2673. EXPECT_EQ("test.html", res->body);
  2674. }
  2675. TEST_F(ServerTest, GetMethodInvalidPath) {
  2676. auto res = cli_.Get("/dir/../test.html");
  2677. ASSERT_TRUE(res);
  2678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2679. }
  2680. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2681. auto res = cli_.Get("/../www/dir/test.html");
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2684. }
  2685. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2686. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2687. ASSERT_TRUE(res);
  2688. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2689. }
  2690. TEST_F(ServerTest, GetMethodDirMountTest) {
  2691. auto res = cli_.Get("/mount/dir/test.html");
  2692. ASSERT_TRUE(res);
  2693. EXPECT_EQ(StatusCode::OK_200, res->status);
  2694. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2695. EXPECT_EQ("test.html", res->body);
  2696. }
  2697. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2698. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2699. ASSERT_TRUE(res);
  2700. EXPECT_EQ(StatusCode::OK_200, res->status);
  2701. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2702. EXPECT_EQ("test.html", res->body);
  2703. }
  2704. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2705. auto res = cli_.Get("/mount/dir/../test.html");
  2706. ASSERT_TRUE(res);
  2707. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2708. }
  2709. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2710. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2711. ASSERT_TRUE(res);
  2712. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2713. }
  2714. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2715. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2716. ASSERT_TRUE(res);
  2717. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2718. }
  2719. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2720. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2721. ASSERT_TRUE(res);
  2722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2723. }
  2724. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2725. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2726. ASSERT_TRUE(res);
  2727. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2728. }
  2729. TEST_F(ServerTest, PostMethod303) {
  2730. auto res = cli_.Post("/1", "body", "text/plain");
  2731. ASSERT_TRUE(res);
  2732. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2733. EXPECT_EQ("/2", res->get_header_value("Location"));
  2734. }
  2735. TEST_F(ServerTest, PostMethod303Redirect) {
  2736. cli_.set_follow_location(true);
  2737. auto res = cli_.Post("/1", "body", "text/plain");
  2738. ASSERT_TRUE(res);
  2739. EXPECT_EQ(StatusCode::OK_200, res->status);
  2740. EXPECT_EQ("redirected.", res->body);
  2741. EXPECT_EQ("/2", res->location);
  2742. }
  2743. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2744. auto res = cli_.Get("/dir/test.abcde");
  2745. ASSERT_TRUE(res);
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2748. EXPECT_EQ("abcde", res->body);
  2749. }
  2750. TEST_F(ServerTest, StaticFileRange) {
  2751. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2752. ASSERT_TRUE(res);
  2753. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2754. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2755. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2756. EXPECT_EQ(true, res->has_header("Content-Range"));
  2757. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2758. EXPECT_EQ(std::string("cd"), res->body);
  2759. }
  2760. TEST_F(ServerTest, StaticFileRanges) {
  2761. auto res =
  2762. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2763. ASSERT_TRUE(res);
  2764. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2765. EXPECT_TRUE(
  2766. res->get_header_value("Content-Type")
  2767. .find(
  2768. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2769. 0);
  2770. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2771. }
  2772. TEST_F(ServerTest, StaticFileRangeHead) {
  2773. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2774. ASSERT_TRUE(res);
  2775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2776. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2777. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2778. EXPECT_EQ(true, res->has_header("Content-Range"));
  2779. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2780. }
  2781. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2782. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2783. ASSERT_TRUE(res);
  2784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2786. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2787. EXPECT_EQ(true, res->has_header("Content-Range"));
  2788. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2789. res->get_header_value("Content-Range"));
  2790. EXPECT_EQ("LAST\n", res->body);
  2791. }
  2792. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2793. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2794. ASSERT_TRUE(res);
  2795. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2796. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2797. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2798. EXPECT_EQ(true, res->has_header("Content-Range"));
  2799. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2800. }
  2801. TEST_F(ServerTest, StaticFileBigFile) {
  2802. auto res = cli_.Get("/dir/1MB.txt");
  2803. ASSERT_TRUE(res);
  2804. EXPECT_EQ(StatusCode::OK_200, res->status);
  2805. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2806. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2807. }
  2808. TEST_F(ServerTest, InvalidBaseDirMount) {
  2809. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2810. }
  2811. TEST_F(ServerTest, Binary) {
  2812. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2813. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2814. "application/octet-stream");
  2815. ASSERT_TRUE(res);
  2816. ASSERT_EQ(StatusCode::OK_200, res->status);
  2817. ASSERT_EQ(4U, res->body.size());
  2818. res = cli_.Put("/binary", binary.data(), binary.size(),
  2819. "application/octet-stream");
  2820. ASSERT_TRUE(res);
  2821. ASSERT_EQ(StatusCode::OK_200, res->status);
  2822. ASSERT_EQ(4U, res->body.size());
  2823. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2824. "application/octet-stream");
  2825. ASSERT_TRUE(res);
  2826. ASSERT_EQ(StatusCode::OK_200, res->status);
  2827. ASSERT_EQ(4U, res->body.size());
  2828. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2829. "application/octet-stream");
  2830. ASSERT_TRUE(res);
  2831. ASSERT_EQ(StatusCode::OK_200, res->status);
  2832. ASSERT_EQ(4U, res->body.size());
  2833. }
  2834. TEST_F(ServerTest, BinaryString) {
  2835. auto binary = std::string("\x00\x01\x02\x03", 4);
  2836. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2837. ASSERT_TRUE(res);
  2838. ASSERT_EQ(StatusCode::OK_200, res->status);
  2839. ASSERT_EQ(4U, res->body.size());
  2840. res = cli_.Put("/binary", binary, "application/octet-stream");
  2841. ASSERT_TRUE(res);
  2842. ASSERT_EQ(StatusCode::OK_200, res->status);
  2843. ASSERT_EQ(4U, res->body.size());
  2844. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2845. ASSERT_TRUE(res);
  2846. ASSERT_EQ(StatusCode::OK_200, res->status);
  2847. ASSERT_EQ(4U, res->body.size());
  2848. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2849. ASSERT_TRUE(res);
  2850. ASSERT_EQ(StatusCode::OK_200, res->status);
  2851. ASSERT_EQ(4U, res->body.size());
  2852. }
  2853. TEST_F(ServerTest, EmptyRequest) {
  2854. auto res = cli_.Get("");
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::Connection, res.error());
  2857. }
  2858. TEST_F(ServerTest, LongRequest) {
  2859. std::string request;
  2860. for (size_t i = 0; i < 545; i++) {
  2861. request += "/TooLongRequest";
  2862. }
  2863. request += "OK";
  2864. auto res = cli_.Get(request.c_str());
  2865. ASSERT_TRUE(res);
  2866. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2867. }
  2868. TEST_F(ServerTest, TooLongRequest) {
  2869. std::string request;
  2870. for (size_t i = 0; i < 545; i++) {
  2871. request += "/TooLongRequest";
  2872. }
  2873. request += "_NG";
  2874. auto res = cli_.Get(request.c_str());
  2875. ASSERT_TRUE(res);
  2876. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2877. }
  2878. TEST_F(ServerTest, LongHeader) {
  2879. Request req;
  2880. req.method = "GET";
  2881. req.path = "/hi";
  2882. std::string host_and_port;
  2883. host_and_port += HOST;
  2884. host_and_port += ":";
  2885. host_and_port += std::to_string(PORT);
  2886. req.headers.emplace("Host", host_and_port.c_str());
  2887. req.headers.emplace("Accept", "*/*");
  2888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2889. req.headers.emplace(
  2890. "Header-Name",
  2891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2894. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2895. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2919. "@@@@@@@@@@@@@@@@");
  2920. auto res = std::make_shared<Response>();
  2921. auto error = Error::Success;
  2922. auto ret = cli_.send(req, *res, error);
  2923. ASSERT_TRUE(ret);
  2924. EXPECT_EQ(StatusCode::OK_200, res->status);
  2925. }
  2926. TEST_F(ServerTest, LongQueryValue) {
  2927. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2928. ASSERT_TRUE(res);
  2929. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2930. }
  2931. TEST_F(ServerTest, TooLongHeader) {
  2932. Request req;
  2933. req.method = "GET";
  2934. req.path = "/hi";
  2935. std::string host_and_port;
  2936. host_and_port += HOST;
  2937. host_and_port += ":";
  2938. host_and_port += std::to_string(PORT);
  2939. req.headers.emplace("Host", host_and_port.c_str());
  2940. req.headers.emplace("Accept", "*/*");
  2941. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2942. req.headers.emplace(
  2943. "Header-Name",
  2944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2964. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2965. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2966. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2967. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2968. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2969. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2970. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2971. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2972. "@@@@@@@@@@@@@@@@@");
  2973. auto res = std::make_shared<Response>();
  2974. auto error = Error::Success;
  2975. auto ret = cli_.send(req, *res, error);
  2976. ASSERT_TRUE(ret);
  2977. EXPECT_EQ(StatusCode::OK_200, res->status);
  2978. }
  2979. TEST_F(ServerTest, PercentEncoding) {
  2980. auto res = cli_.Get("/e%6edwith%");
  2981. ASSERT_TRUE(res);
  2982. EXPECT_EQ(StatusCode::OK_200, res->status);
  2983. }
  2984. TEST_F(ServerTest, PercentEncodingUnicode) {
  2985. auto res = cli_.Get("/e%u006edwith%");
  2986. ASSERT_TRUE(res);
  2987. EXPECT_EQ(StatusCode::OK_200, res->status);
  2988. }
  2989. TEST_F(ServerTest, InvalidPercentEncoding) {
  2990. auto res = cli_.Get("/%endwith%");
  2991. ASSERT_TRUE(res);
  2992. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2993. }
  2994. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2995. auto res = cli_.Get("/%uendwith%");
  2996. ASSERT_TRUE(res);
  2997. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2998. }
  2999. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3000. auto res = cli_.Get("/hello?aaa=bbb%");
  3001. ASSERT_TRUE(res);
  3002. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3003. }
  3004. TEST_F(ServerTest, PlusSignEncoding) {
  3005. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3006. ASSERT_TRUE(res);
  3007. EXPECT_EQ(StatusCode::OK_200, res->status);
  3008. EXPECT_EQ("a +b", res->body);
  3009. }
  3010. TEST_F(ServerTest, MultipartFormData) {
  3011. MultipartFormDataItems items = {
  3012. {"text1", "text default", "", ""},
  3013. {"text2", "aωb", "", ""},
  3014. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3015. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3016. {"file3", "", "", "application/octet-stream"},
  3017. {"file4", "", "", " application/json tmp-string "}};
  3018. auto res = cli_.Post("/multipart", items);
  3019. ASSERT_TRUE(res);
  3020. EXPECT_EQ(StatusCode::OK_200, res->status);
  3021. }
  3022. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3023. MultipartFormDataItems items = {
  3024. {"text", "default text", "", ""},
  3025. {"multi_text1", "aaaaa", "", ""},
  3026. {"multi_text1", "bbbbb", "", ""},
  3027. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3028. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3029. "application/json"},
  3030. };
  3031. auto res = cli_.Post("/multipart/multi_file_values", items);
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. }
  3035. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3036. auto res = cli_.Get("/hi");
  3037. ASSERT_TRUE(res);
  3038. EXPECT_EQ(StatusCode::OK_200, res->status);
  3039. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3040. EXPECT_EQ("Hello World!", res->body);
  3041. }
  3042. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3043. Request req;
  3044. req.method = "POST";
  3045. req.path = "/chunked";
  3046. std::string host_and_port;
  3047. host_and_port += HOST;
  3048. host_and_port += ":";
  3049. host_and_port += std::to_string(PORT);
  3050. req.headers.emplace("Host", host_and_port.c_str());
  3051. req.headers.emplace("Accept", "*/*");
  3052. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3053. req.headers.emplace("Content-Type", "text/plain");
  3054. req.headers.emplace("Content-Length", "0");
  3055. req.headers.emplace(
  3056. "Transfer-Encoding",
  3057. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3058. // Client does not chunk, so make a chunked body manually.
  3059. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3060. auto res = std::make_shared<Response>();
  3061. auto error = Error::Success;
  3062. auto ret = cli_.send(req, *res, error);
  3063. ASSERT_TRUE(ret);
  3064. EXPECT_EQ(StatusCode::OK_200, res->status);
  3065. }
  3066. TEST_F(ServerTest, GetStreamed2) {
  3067. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3068. ASSERT_TRUE(res);
  3069. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3070. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3071. EXPECT_EQ(true, res->has_header("Content-Range"));
  3072. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3073. EXPECT_EQ(std::string("ab"), res->body);
  3074. }
  3075. TEST_F(ServerTest, GetStreamed) {
  3076. auto res = cli_.Get("/streamed");
  3077. ASSERT_TRUE(res);
  3078. EXPECT_EQ(StatusCode::OK_200, res->status);
  3079. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3080. EXPECT_EQ(std::string("aaabbb"), res->body);
  3081. }
  3082. TEST_F(ServerTest, GetStreamedWithRange1) {
  3083. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3084. ASSERT_TRUE(res);
  3085. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3086. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3087. EXPECT_EQ(true, res->has_header("Content-Range"));
  3088. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3089. EXPECT_EQ(std::string("def"), res->body);
  3090. }
  3091. TEST_F(ServerTest, GetStreamedWithRange2) {
  3092. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3093. ASSERT_TRUE(res);
  3094. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3095. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3096. EXPECT_EQ(true, res->has_header("Content-Range"));
  3097. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3098. EXPECT_EQ(std::string("bcdefg"), res->body);
  3099. }
  3100. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3101. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3102. ASSERT_TRUE(res);
  3103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3104. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3105. EXPECT_EQ(true, res->has_header("Content-Range"));
  3106. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3107. EXPECT_EQ(std::string("efg"), res->body);
  3108. }
  3109. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3110. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3111. ASSERT_TRUE(res);
  3112. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3113. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3114. EXPECT_EQ(false, res->has_header("Content-Range"));
  3115. EXPECT_EQ(0U, res->body.size());
  3116. }
  3117. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3118. auto res = cli_.Get("/streamed-with-range",
  3119. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3120. "92233720368547758079223372036854775807"}});
  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, GetRangeWithMaxLongLength) {
  3128. auto res = cli_.Get(
  3129. "/with-range",
  3130. {{"Range",
  3131. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())}});
  3132. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3133. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3134. EXPECT_EQ(false, res->has_header("Content-Range"));
  3135. EXPECT_EQ(0U, res->body.size());
  3136. }
  3137. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  3138. auto res = cli_.Get("/with-range", {{"Range", "bytes=0-"}});
  3139. ASSERT_TRUE(res);
  3140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3141. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  3142. EXPECT_EQ(true, res->has_header("Content-Range"));
  3143. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  3144. EXPECT_EQ(std::string("abcdefg"), res->body);
  3145. }
  3146. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3147. auto res =
  3148. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3149. ASSERT_TRUE(res);
  3150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3151. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3152. EXPECT_EQ(false, res->has_header("Content-Range"));
  3153. EXPECT_EQ(267U, res->body.size());
  3154. }
  3155. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3156. Ranges ranges;
  3157. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3158. ranges.emplace_back(0, -1);
  3159. }
  3160. auto res =
  3161. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3162. ASSERT_TRUE(res);
  3163. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3164. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3165. EXPECT_EQ(false, res->has_header("Content-Range"));
  3166. EXPECT_EQ(0U, res->body.size());
  3167. }
  3168. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3169. auto res = cli_.Get("/streamed-with-range?error",
  3170. {{make_range_header({{0, -1}, {0, -1}})}});
  3171. ASSERT_TRUE(res);
  3172. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3173. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3174. EXPECT_EQ(false, res->has_header("Content-Range"));
  3175. EXPECT_EQ(0U, res->body.size());
  3176. }
  3177. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3178. auto res = cli_.Get("/streamed-with-range?error",
  3179. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3180. ASSERT_TRUE(res);
  3181. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3182. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3183. EXPECT_EQ(false, res->has_header("Content-Range"));
  3184. EXPECT_EQ(0U, res->body.size());
  3185. }
  3186. TEST_F(ServerTest, GetStreamedEndless) {
  3187. uint64_t offset = 0;
  3188. auto res = cli_.Get("/streamed-cancel",
  3189. [&](const char * /*data*/, uint64_t data_length) {
  3190. if (offset < 100) {
  3191. offset += data_length;
  3192. return true;
  3193. }
  3194. return false;
  3195. });
  3196. ASSERT_TRUE(!res);
  3197. EXPECT_EQ(Error::Canceled, res.error());
  3198. }
  3199. TEST_F(ServerTest, ClientStop) {
  3200. std::atomic_size_t count{4};
  3201. std::vector<std::thread> threads;
  3202. for (auto i = count.load(); i != 0; --i) {
  3203. threads.emplace_back([&]() {
  3204. auto res = cli_.Get("/streamed-cancel",
  3205. [&](const char *, uint64_t) { return true; });
  3206. --count;
  3207. ASSERT_TRUE(!res);
  3208. EXPECT_TRUE(res.error() == Error::Canceled ||
  3209. res.error() == Error::Read || res.error() == Error::Write);
  3210. });
  3211. }
  3212. std::this_thread::sleep_for(std::chrono::seconds(2));
  3213. while (count != 0) {
  3214. cli_.stop();
  3215. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3216. }
  3217. for (auto &t : threads) {
  3218. t.join();
  3219. }
  3220. }
  3221. TEST_F(ServerTest, GetWithRange1) {
  3222. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  3223. ASSERT_TRUE(res);
  3224. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3225. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3226. EXPECT_EQ(true, res->has_header("Content-Range"));
  3227. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3228. EXPECT_EQ(std::string("def"), res->body);
  3229. }
  3230. TEST_F(ServerTest, GetWithRange2) {
  3231. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3234. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3235. EXPECT_EQ(true, res->has_header("Content-Range"));
  3236. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3237. EXPECT_EQ(std::string("bcdefg"), res->body);
  3238. }
  3239. TEST_F(ServerTest, GetWithRange3) {
  3240. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3243. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3244. EXPECT_EQ(true, res->has_header("Content-Range"));
  3245. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3246. EXPECT_EQ(std::string("a"), res->body);
  3247. }
  3248. TEST_F(ServerTest, GetWithRange4) {
  3249. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  3250. ASSERT_TRUE(res);
  3251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3252. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3253. EXPECT_EQ(true, res->has_header("Content-Range"));
  3254. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3255. EXPECT_EQ(std::string("fg"), res->body);
  3256. }
  3257. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3258. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3261. }
  3262. TEST_F(ServerTest, GetWithRangeMultipart) {
  3263. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3264. ASSERT_TRUE(res);
  3265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3266. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3267. EXPECT_EQ(false, res->has_header("Content-Range"));
  3268. EXPECT_EQ(267U, res->body.size());
  3269. }
  3270. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3271. auto res =
  3272. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3273. ASSERT_TRUE(res);
  3274. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3275. }
  3276. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3277. auto res = cli_.Get("/with-range-customized-response",
  3278. {{make_range_header({{1, 2}})}});
  3279. ASSERT_TRUE(res);
  3280. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3281. EXPECT_EQ(true, res->has_header("Content-Length"));
  3282. EXPECT_EQ(false, res->has_header("Content-Range"));
  3283. EXPECT_EQ(JSON_DATA, res->body);
  3284. }
  3285. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3286. auto res = cli_.Get("/with-range-customized-response",
  3287. {{make_range_header({{1, 2}, {4, 5}})}});
  3288. ASSERT_TRUE(res);
  3289. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3290. EXPECT_EQ(true, res->has_header("Content-Length"));
  3291. EXPECT_EQ(false, res->has_header("Content-Range"));
  3292. EXPECT_EQ(JSON_DATA, res->body);
  3293. }
  3294. TEST_F(ServerTest, Issue1772) {
  3295. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3296. ASSERT_TRUE(res);
  3297. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3298. }
  3299. TEST_F(ServerTest, GetStreamedChunked) {
  3300. auto res = cli_.Get("/streamed-chunked");
  3301. ASSERT_TRUE(res);
  3302. EXPECT_EQ(StatusCode::OK_200, res->status);
  3303. EXPECT_EQ(std::string("123456789"), res->body);
  3304. }
  3305. TEST_F(ServerTest, GetStreamedChunked2) {
  3306. auto res = cli_.Get("/streamed-chunked2");
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(StatusCode::OK_200, res->status);
  3309. EXPECT_EQ(std::string("123456789"), res->body);
  3310. }
  3311. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3312. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3313. ASSERT_TRUE(res);
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. EXPECT_EQ(std::string("123456789"), res->body);
  3316. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3317. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3318. }
  3319. TEST_F(ServerTest, LargeChunkedPost) {
  3320. Request req;
  3321. req.method = "POST";
  3322. req.path = "/large-chunked";
  3323. std::string host_and_port;
  3324. host_and_port += HOST;
  3325. host_and_port += ":";
  3326. host_and_port += std::to_string(PORT);
  3327. req.headers.emplace("Host", host_and_port.c_str());
  3328. req.headers.emplace("Accept", "*/*");
  3329. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3330. req.headers.emplace("Content-Type", "text/plain");
  3331. req.headers.emplace("Content-Length", "0");
  3332. req.headers.emplace("Transfer-Encoding", "chunked");
  3333. std::string long_string(30 * 1024u, 'a');
  3334. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3335. // Attempt to make a large enough post to exceed OS buffers, to test that
  3336. // the server handles short reads if the full chunk data isn't available.
  3337. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3338. auto res = std::make_shared<Response>();
  3339. auto error = Error::Success;
  3340. auto ret = cli_.send(req, *res, error);
  3341. ASSERT_TRUE(ret);
  3342. EXPECT_EQ(StatusCode::OK_200, res->status);
  3343. }
  3344. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3345. auto res = cli_.Get("/remote_addr");
  3346. ASSERT_TRUE(res);
  3347. EXPECT_EQ(StatusCode::OK_200, res->status);
  3348. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3349. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3350. }
  3351. TEST_F(ServerTest, GetMethodLocalAddr) {
  3352. auto res = cli_.Get("/local_addr");
  3353. ASSERT_TRUE(res);
  3354. EXPECT_EQ(StatusCode::OK_200, res->status);
  3355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3356. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3357. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3358. }
  3359. TEST_F(ServerTest, HTTPResponseSplitting) {
  3360. auto res = cli_.Get("/http_response_splitting");
  3361. ASSERT_TRUE(res);
  3362. EXPECT_EQ(StatusCode::OK_200, res->status);
  3363. }
  3364. TEST_F(ServerTest, SlowRequest) {
  3365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3366. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3367. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3368. }
  3369. #if 0
  3370. TEST_F(ServerTest, SlowPost) {
  3371. char buffer[64 * 1024];
  3372. memset(buffer, 0x42, sizeof(buffer));
  3373. auto res = cli_.Post(
  3374. "/slowpost", 64 * 1024 * 1024,
  3375. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3376. auto ret = sink.write(buffer, sizeof(buffer));
  3377. EXPECT_TRUE(ret);
  3378. return true;
  3379. },
  3380. "text/plain");
  3381. ASSERT_TRUE(res);
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. }
  3384. TEST_F(ServerTest, SlowPostFail) {
  3385. char buffer[64 * 1024];
  3386. memset(buffer, 0x42, sizeof(buffer));
  3387. cli_.set_write_timeout(std::chrono::seconds(0));
  3388. auto res = cli_.Post(
  3389. "/slowpost", 64 * 1024 * 1024,
  3390. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3391. sink.write(buffer, sizeof(buffer));
  3392. return true;
  3393. },
  3394. "text/plain");
  3395. ASSERT_TRUE(!res);
  3396. EXPECT_EQ(Error::Write, res.error());
  3397. }
  3398. #endif
  3399. TEST_F(ServerTest, Put) {
  3400. auto res = cli_.Put("/put", "PUT", "text/plain");
  3401. ASSERT_TRUE(res);
  3402. EXPECT_EQ(StatusCode::OK_200, res->status);
  3403. EXPECT_EQ("PUT", res->body);
  3404. }
  3405. TEST_F(ServerTest, PutWithContentProvider) {
  3406. auto res = cli_.Put(
  3407. "/put", 3,
  3408. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3409. sink.os << "PUT";
  3410. return true;
  3411. },
  3412. "text/plain");
  3413. ASSERT_TRUE(res);
  3414. EXPECT_EQ(StatusCode::OK_200, res->status);
  3415. EXPECT_EQ("PUT", res->body);
  3416. }
  3417. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3418. auto res = cli_.Post(
  3419. "/post", 42,
  3420. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3421. return false;
  3422. },
  3423. "text/plain");
  3424. ASSERT_TRUE(!res);
  3425. EXPECT_EQ(Error::Canceled, res.error());
  3426. }
  3427. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3428. auto res = cli_.Put(
  3429. "/put",
  3430. [](size_t /*offset*/, DataSink &sink) {
  3431. sink.os << "PUT";
  3432. sink.done();
  3433. return true;
  3434. },
  3435. "text/plain");
  3436. ASSERT_TRUE(res);
  3437. EXPECT_EQ(StatusCode::OK_200, res->status);
  3438. EXPECT_EQ("PUT", res->body);
  3439. }
  3440. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3441. auto res = cli_.Post(
  3442. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3443. "text/plain");
  3444. ASSERT_TRUE(!res);
  3445. EXPECT_EQ(Error::Canceled, res.error());
  3446. }
  3447. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3448. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3449. cli_.set_compress(true);
  3450. auto res = cli_.Put(
  3451. "/put", 3,
  3452. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3453. sink.os << "PUT";
  3454. return true;
  3455. },
  3456. "text/plain");
  3457. ASSERT_TRUE(res);
  3458. EXPECT_EQ(StatusCode::OK_200, res->status);
  3459. EXPECT_EQ("PUT", res->body);
  3460. }
  3461. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3462. cli_.set_compress(true);
  3463. auto res = cli_.Post(
  3464. "/post", 42,
  3465. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3466. return false;
  3467. },
  3468. "text/plain");
  3469. ASSERT_TRUE(!res);
  3470. EXPECT_EQ(Error::Canceled, res.error());
  3471. }
  3472. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3473. cli_.set_compress(true);
  3474. auto res = cli_.Put(
  3475. "/put",
  3476. [](size_t /*offset*/, DataSink &sink) {
  3477. sink.os << "PUT";
  3478. sink.done();
  3479. return true;
  3480. },
  3481. "text/plain");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("PUT", res->body);
  3485. }
  3486. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3487. cli_.set_compress(true);
  3488. auto res = cli_.Post(
  3489. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3490. "text/plain");
  3491. ASSERT_TRUE(!res);
  3492. EXPECT_EQ(Error::Canceled, res.error());
  3493. }
  3494. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3495. cli_.set_compress(true);
  3496. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3497. ASSERT_TRUE(res);
  3498. EXPECT_EQ(StatusCode::OK_200, res->status);
  3499. EXPECT_EQ(LARGE_DATA, res->body);
  3500. }
  3501. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3502. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3503. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3504. Client cli(s.c_str());
  3505. cli.enable_server_certificate_verification(false);
  3506. #else
  3507. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3508. Client cli(s.c_str());
  3509. #endif
  3510. cli.set_compress(true);
  3511. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3512. ASSERT_TRUE(res);
  3513. EXPECT_EQ(StatusCode::OK_200, res->status);
  3514. EXPECT_EQ(LARGE_DATA, res->body);
  3515. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  3516. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3517. }
  3518. TEST_F(ServerTest, PutContentWithDeflate) {
  3519. cli_.set_compress(false);
  3520. Headers headers;
  3521. headers.emplace("Content-Encoding", "deflate");
  3522. // PUT in deflate format:
  3523. auto res = cli_.Put("/put", headers,
  3524. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::OK_200, res->status);
  3527. EXPECT_EQ("PUT", res->body);
  3528. }
  3529. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3530. Headers headers;
  3531. headers.emplace("Accept-Encoding", "gzip, deflate");
  3532. auto res = cli_.Get("/streamed-chunked", headers);
  3533. ASSERT_TRUE(res);
  3534. EXPECT_EQ(StatusCode::OK_200, res->status);
  3535. EXPECT_EQ(std::string("123456789"), res->body);
  3536. }
  3537. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3538. Headers headers;
  3539. headers.emplace("Accept-Encoding", "gzip, deflate");
  3540. auto res = cli_.Get("/streamed-chunked2", headers);
  3541. ASSERT_TRUE(res);
  3542. EXPECT_EQ(StatusCode::OK_200, res->status);
  3543. EXPECT_EQ(std::string("123456789"), res->body);
  3544. }
  3545. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3546. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3547. ASSERT_TRUE(res);
  3548. EXPECT_EQ(StatusCode::OK_200, res->status);
  3549. }
  3550. TEST(GzipDecompressor, ChunkedDecompression) {
  3551. std::string data;
  3552. for (size_t i = 0; i < 32 * 1024; ++i) {
  3553. data.push_back(static_cast<char>('a' + i % 26));
  3554. }
  3555. std::string compressed_data;
  3556. {
  3557. httplib::detail::gzip_compressor compressor;
  3558. bool result = compressor.compress(
  3559. data.data(), data.size(),
  3560. /*last=*/true,
  3561. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3562. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3563. compressed_data_size);
  3564. return true;
  3565. });
  3566. ASSERT_TRUE(result);
  3567. }
  3568. std::string decompressed_data;
  3569. {
  3570. httplib::detail::gzip_decompressor decompressor;
  3571. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3572. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3573. size_t chunk_size = 130;
  3574. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3575. chunk_begin += chunk_size) {
  3576. size_t current_chunk_size =
  3577. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3578. bool result = decompressor.decompress(
  3579. compressed_data.data() + chunk_begin, current_chunk_size,
  3580. [&](const char *decompressed_data_chunk,
  3581. size_t decompressed_data_chunk_size) {
  3582. decompressed_data.insert(decompressed_data.size(),
  3583. decompressed_data_chunk,
  3584. decompressed_data_chunk_size);
  3585. return true;
  3586. });
  3587. ASSERT_TRUE(result);
  3588. }
  3589. }
  3590. ASSERT_EQ(data, decompressed_data);
  3591. }
  3592. TEST(GzipDecompressor, DeflateDecompression) {
  3593. std::string original_text = "Raw deflate without gzip";
  3594. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3595. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3596. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3597. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3598. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3599. std::string decompressed_data;
  3600. {
  3601. httplib::detail::gzip_decompressor decompressor;
  3602. bool result = decompressor.decompress(
  3603. compressed_data.data(), compressed_data.size(),
  3604. [&](const char *decompressed_data_chunk,
  3605. size_t decompressed_data_chunk_size) {
  3606. decompressed_data.insert(decompressed_data.size(),
  3607. decompressed_data_chunk,
  3608. decompressed_data_chunk_size);
  3609. return true;
  3610. });
  3611. ASSERT_TRUE(result);
  3612. }
  3613. ASSERT_EQ(original_text, decompressed_data);
  3614. }
  3615. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3616. std::string original_text = "Raw deflate without gzip";
  3617. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3618. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3619. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3620. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3621. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3622. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3623. std::string decompressed_data;
  3624. {
  3625. httplib::detail::gzip_decompressor decompressor;
  3626. bool result = decompressor.decompress(
  3627. compressed_data.data(), compressed_data.size(),
  3628. [&](const char *decompressed_data_chunk,
  3629. size_t decompressed_data_chunk_size) {
  3630. decompressed_data.insert(decompressed_data.size(),
  3631. decompressed_data_chunk,
  3632. decompressed_data_chunk_size);
  3633. return true;
  3634. });
  3635. ASSERT_TRUE(result);
  3636. }
  3637. ASSERT_EQ(original_text, decompressed_data);
  3638. }
  3639. #ifdef _WIN32
  3640. TEST(GzipDecompressor, LargeRandomData) {
  3641. // prepare large random data that is difficult to be compressed and is
  3642. // expected to have large size even when compressed
  3643. std::random_device seed_gen;
  3644. std::mt19937 random(seed_gen());
  3645. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3646. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3647. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3648. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3649. // compress data over 4GiB
  3650. std::string compressed_data;
  3651. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3652. httplib::detail::gzip_compressor compressor;
  3653. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3654. data.size() * sizeof(std::uint32_t), true,
  3655. [&](const char *data, size_t size) {
  3656. compressed_data.insert(
  3657. compressed_data.size(), data, size);
  3658. return true;
  3659. });
  3660. ASSERT_TRUE(result);
  3661. // FIXME: compressed data size is expected to be greater than 4GiB,
  3662. // but there is no guarantee
  3663. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3664. // decompress data over 4GiB
  3665. std::string decompressed_data;
  3666. decompressed_data.reserve(data_size);
  3667. httplib::detail::gzip_decompressor decompressor;
  3668. result = decompressor.decompress(
  3669. compressed_data.data(), compressed_data.size(),
  3670. [&](const char *data, size_t size) {
  3671. decompressed_data.insert(decompressed_data.size(), data, size);
  3672. return true;
  3673. });
  3674. ASSERT_TRUE(result);
  3675. // compare
  3676. ASSERT_EQ(data_size, decompressed_data.size());
  3677. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3678. 0);
  3679. }
  3680. #endif
  3681. #endif
  3682. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3683. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3684. Headers headers;
  3685. headers.emplace("Accept-Encoding", "br");
  3686. auto res = cli_.Get("/streamed-chunked", headers);
  3687. ASSERT_TRUE(res);
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. EXPECT_EQ(std::string("123456789"), res->body);
  3690. }
  3691. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3692. Headers headers;
  3693. headers.emplace("Accept-Encoding", "br");
  3694. auto res = cli_.Get("/streamed-chunked2", headers);
  3695. ASSERT_TRUE(res);
  3696. EXPECT_EQ(StatusCode::OK_200, res->status);
  3697. EXPECT_EQ(std::string("123456789"), res->body);
  3698. }
  3699. #endif
  3700. TEST_F(ServerTest, Patch) {
  3701. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3702. ASSERT_TRUE(res);
  3703. EXPECT_EQ(StatusCode::OK_200, res->status);
  3704. EXPECT_EQ("PATCH", res->body);
  3705. }
  3706. TEST_F(ServerTest, Delete) {
  3707. auto res = cli_.Delete("/delete");
  3708. ASSERT_TRUE(res);
  3709. EXPECT_EQ(StatusCode::OK_200, res->status);
  3710. EXPECT_EQ("DELETE", res->body);
  3711. }
  3712. TEST_F(ServerTest, DeleteContentReceiver) {
  3713. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3714. ASSERT_TRUE(res);
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. EXPECT_EQ("content", res->body);
  3717. }
  3718. TEST_F(ServerTest, Options) {
  3719. auto res = cli_.Options("*");
  3720. ASSERT_TRUE(res);
  3721. EXPECT_EQ(StatusCode::OK_200, res->status);
  3722. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3723. EXPECT_TRUE(res->body.empty());
  3724. }
  3725. TEST_F(ServerTest, URL) {
  3726. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3727. ASSERT_TRUE(res);
  3728. EXPECT_EQ(StatusCode::OK_200, res->status);
  3729. }
  3730. TEST_F(ServerTest, ArrayParam) {
  3731. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. }
  3735. TEST_F(ServerTest, NoMultipleHeaders) {
  3736. Headers headers = {{"Content-Length", "5"}};
  3737. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3738. "text/plain");
  3739. ASSERT_TRUE(res);
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. }
  3742. TEST_F(ServerTest, PostContentReceiver) {
  3743. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3744. ASSERT_TRUE(res);
  3745. ASSERT_EQ(StatusCode::OK_200, res->status);
  3746. ASSERT_EQ("content", res->body);
  3747. }
  3748. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3749. MultipartFormDataItems items = {
  3750. {"text1", "text default", "", ""},
  3751. {"text2", "aωb", "", ""},
  3752. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3753. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3754. {"file3", "", "", "application/octet-stream"},
  3755. };
  3756. auto res = cli_.Post("/content_receiver", items);
  3757. ASSERT_TRUE(res);
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. }
  3760. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3761. MultipartFormDataItems items = {
  3762. {"text1", "text default", "", ""},
  3763. {"text2", "aωb", "", ""},
  3764. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3765. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3766. {"file3", "", "", "application/octet-stream"},
  3767. };
  3768. auto boundary = std::string("+++++");
  3769. std::string body;
  3770. for (const auto &item : items) {
  3771. body += "--" + boundary + "\r\n";
  3772. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3773. if (!item.filename.empty()) {
  3774. body += "; filename=\"" + item.filename + "\"";
  3775. }
  3776. body += "\r\n";
  3777. if (!item.content_type.empty()) {
  3778. body += "Content-Type: " + item.content_type + "\r\n";
  3779. }
  3780. body += "\r\n";
  3781. body += item.content + "\r\n";
  3782. }
  3783. body += "--" + boundary + "--\r\n";
  3784. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3785. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3786. ASSERT_TRUE(res);
  3787. EXPECT_EQ(StatusCode::OK_200, res->status);
  3788. }
  3789. TEST_F(ServerTest, PostContentReceiverGzip) {
  3790. cli_.set_compress(true);
  3791. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3792. ASSERT_TRUE(res);
  3793. ASSERT_EQ(StatusCode::OK_200, res->status);
  3794. ASSERT_EQ("content", res->body);
  3795. }
  3796. TEST_F(ServerTest, PutContentReceiver) {
  3797. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3798. ASSERT_TRUE(res);
  3799. ASSERT_EQ(StatusCode::OK_200, res->status);
  3800. ASSERT_EQ("content", res->body);
  3801. }
  3802. TEST_F(ServerTest, PatchContentReceiver) {
  3803. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3804. ASSERT_TRUE(res);
  3805. ASSERT_EQ(StatusCode::OK_200, res->status);
  3806. ASSERT_EQ("content", res->body);
  3807. }
  3808. TEST_F(ServerTest, PostQueryStringAndBody) {
  3809. auto res =
  3810. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(StatusCode::OK_200, res->status);
  3813. }
  3814. TEST_F(ServerTest, HTTP2Magic) {
  3815. Request req;
  3816. req.method = "PRI";
  3817. req.path = "*";
  3818. req.body = "SM";
  3819. auto res = std::make_shared<Response>();
  3820. auto error = Error::Success;
  3821. auto ret = cli_.send(req, *res, error);
  3822. ASSERT_TRUE(ret);
  3823. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3824. }
  3825. TEST_F(ServerTest, KeepAlive) {
  3826. auto res = cli_.Get("/hi");
  3827. ASSERT_TRUE(res);
  3828. EXPECT_EQ(StatusCode::OK_200, res->status);
  3829. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3830. EXPECT_EQ("Hello World!", res->body);
  3831. res = cli_.Get("/hi");
  3832. ASSERT_TRUE(res);
  3833. EXPECT_EQ(StatusCode::OK_200, res->status);
  3834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3835. EXPECT_EQ("Hello World!", res->body);
  3836. res = cli_.Get("/hi");
  3837. ASSERT_TRUE(res);
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3840. EXPECT_EQ("Hello World!", res->body);
  3841. res = cli_.Get("/not-exist");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3844. res = cli_.Post("/empty", "", "text/plain");
  3845. ASSERT_TRUE(res);
  3846. EXPECT_EQ(StatusCode::OK_200, res->status);
  3847. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("empty", res->body);
  3849. EXPECT_EQ("close", res->get_header_value("Connection"));
  3850. res = cli_.Post(
  3851. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3852. "text/plain");
  3853. ASSERT_TRUE(res);
  3854. EXPECT_EQ(StatusCode::OK_200, res->status);
  3855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3856. EXPECT_EQ("empty", res->body);
  3857. cli_.set_keep_alive(false);
  3858. res = cli_.Get("/last-request");
  3859. ASSERT_TRUE(res);
  3860. EXPECT_EQ(StatusCode::OK_200, res->status);
  3861. EXPECT_EQ("close", res->get_header_value("Connection"));
  3862. }
  3863. TEST_F(ServerTest, TooManyRedirect) {
  3864. cli_.set_follow_location(true);
  3865. auto res = cli_.Get("/redirect/0");
  3866. ASSERT_TRUE(!res);
  3867. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3868. }
  3869. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3870. TEST_F(ServerTest, Gzip) {
  3871. Headers headers;
  3872. headers.emplace("Accept-Encoding", "gzip, deflate");
  3873. auto res = cli_.Get("/compress", headers);
  3874. ASSERT_TRUE(res);
  3875. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3877. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3878. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3879. "7890123456789012345678901234567890",
  3880. res->body);
  3881. EXPECT_EQ(StatusCode::OK_200, res->status);
  3882. }
  3883. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3884. auto res = cli_.Get("/compress");
  3885. ASSERT_TRUE(res);
  3886. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3887. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3888. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3889. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3890. "7890123456789012345678901234567890",
  3891. res->body);
  3892. EXPECT_EQ(StatusCode::OK_200, res->status);
  3893. }
  3894. TEST_F(ServerTest, GzipWithContentReceiver) {
  3895. Headers headers;
  3896. headers.emplace("Accept-Encoding", "gzip, deflate");
  3897. std::string body;
  3898. auto res = cli_.Get("/compress", headers,
  3899. [&](const char *data, uint64_t data_length) {
  3900. EXPECT_EQ(100U, data_length);
  3901. body.append(data, data_length);
  3902. return true;
  3903. });
  3904. ASSERT_TRUE(res);
  3905. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3906. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3907. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3908. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3909. "7890123456789012345678901234567890",
  3910. body);
  3911. EXPECT_EQ(StatusCode::OK_200, res->status);
  3912. }
  3913. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3914. Headers headers;
  3915. headers.emplace("Accept-Encoding", "gzip, deflate");
  3916. cli_.set_decompress(false);
  3917. auto res = cli_.Get("/compress", headers);
  3918. ASSERT_TRUE(res);
  3919. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3920. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3921. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3922. EXPECT_EQ(33U, res->body.size());
  3923. EXPECT_EQ(StatusCode::OK_200, res->status);
  3924. }
  3925. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3926. std::string body;
  3927. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3928. EXPECT_EQ(100U, data_length);
  3929. body.append(data, data_length);
  3930. return true;
  3931. });
  3932. ASSERT_TRUE(res);
  3933. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3934. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3935. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3936. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3937. "7890123456789012345678901234567890",
  3938. body);
  3939. EXPECT_EQ(StatusCode::OK_200, res->status);
  3940. }
  3941. TEST_F(ServerTest, NoGzip) {
  3942. Headers headers;
  3943. headers.emplace("Accept-Encoding", "gzip, deflate");
  3944. auto res = cli_.Get("/nocompress", headers);
  3945. ASSERT_TRUE(res);
  3946. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3947. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3948. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3949. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3950. "7890123456789012345678901234567890",
  3951. res->body);
  3952. EXPECT_EQ(StatusCode::OK_200, res->status);
  3953. }
  3954. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3955. Headers headers;
  3956. headers.emplace("Accept-Encoding", "gzip, deflate");
  3957. std::string body;
  3958. auto res = cli_.Get("/nocompress", headers,
  3959. [&](const char *data, uint64_t data_length) {
  3960. EXPECT_EQ(100U, data_length);
  3961. body.append(data, data_length);
  3962. return true;
  3963. });
  3964. ASSERT_TRUE(res);
  3965. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3966. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3967. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3968. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3969. "7890123456789012345678901234567890",
  3970. body);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, MultipartFormDataGzip) {
  3974. MultipartFormDataItems items = {
  3975. {"key1", "test", "", ""},
  3976. {"key2", "--abcdefg123", "", ""},
  3977. };
  3978. cli_.set_compress(true);
  3979. auto res = cli_.Post("/compress-multipart", items);
  3980. ASSERT_TRUE(res);
  3981. EXPECT_EQ(StatusCode::OK_200, res->status);
  3982. }
  3983. #endif
  3984. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3985. TEST_F(ServerTest, Brotli) {
  3986. Headers headers;
  3987. headers.emplace("Accept-Encoding", "br");
  3988. auto res = cli_.Get("/compress", headers);
  3989. ASSERT_TRUE(res);
  3990. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3992. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3994. "7890123456789012345678901234567890",
  3995. res->body);
  3996. EXPECT_EQ(StatusCode::OK_200, res->status);
  3997. }
  3998. #endif
  3999. // Sends a raw request to a server listening at HOST:PORT.
  4000. static bool send_request(time_t read_timeout_sec, const std::string &req,
  4001. std::string *resp = nullptr) {
  4002. auto error = Error::Success;
  4003. auto client_sock = detail::create_client_socket(
  4004. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4005. /*connection_timeout_sec=*/5, 0,
  4006. /*read_timeout_sec=*/5, 0,
  4007. /*write_timeout_sec=*/5, 0, std::string(), error);
  4008. if (client_sock == INVALID_SOCKET) { return false; }
  4009. auto ret = detail::process_client_socket(
  4010. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  4011. if (req.size() !=
  4012. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  4013. return false;
  4014. }
  4015. char buf[512];
  4016. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4017. while (line_reader.getline()) {
  4018. if (resp) { *resp += line_reader.ptr(); }
  4019. }
  4020. return true;
  4021. });
  4022. detail::close_socket(client_sock);
  4023. return ret;
  4024. }
  4025. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4026. Server svr;
  4027. std::string header_value;
  4028. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4029. header_value = req.get_header_value("foo");
  4030. res.set_content("ok", "text/plain");
  4031. });
  4032. thread t = thread([&] { svr.listen(HOST, PORT); });
  4033. auto se = detail::scope_exit([&] {
  4034. svr.stop();
  4035. t.join();
  4036. ASSERT_FALSE(svr.is_running());
  4037. });
  4038. svr.wait_until_ready();
  4039. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4040. // like characters are not treated the same - use vertical tab and escape.
  4041. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4042. "foo: \t \v bar \x1B\t \r\n"
  4043. "Connection: close\r\n"
  4044. "\r\n";
  4045. ASSERT_TRUE(send_request(5, req));
  4046. EXPECT_EQ(header_value, "\v bar \x1B");
  4047. }
  4048. // Sends a raw request and verifies that there isn't a crash or exception.
  4049. static void test_raw_request(const std::string &req,
  4050. std::string *out = nullptr) {
  4051. Server svr;
  4052. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4053. res.set_content("ok", "text/plain");
  4054. });
  4055. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4056. res.set_content("ok", "text/plain");
  4057. });
  4058. svr.Get("/header_field_value_check",
  4059. [&](const Request & /*req*/, Response &res) {
  4060. res.set_content("ok", "text/plain");
  4061. });
  4062. // Server read timeout must be longer than the client read timeout for the
  4063. // bug to reproduce, probably to force the server to process a request
  4064. // without a trailing blank line.
  4065. const time_t client_read_timeout_sec = 1;
  4066. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4067. bool listen_thread_ok = false;
  4068. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4069. auto se = detail::scope_exit([&] {
  4070. svr.stop();
  4071. t.join();
  4072. ASSERT_FALSE(svr.is_running());
  4073. EXPECT_TRUE(listen_thread_ok);
  4074. });
  4075. svr.wait_until_ready();
  4076. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4077. }
  4078. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4079. // A certain header line causes an exception if the header property is parsed
  4080. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4081. test_raw_request(
  4082. "GET /hi HTTP/1.1\r\n"
  4083. " : "
  4084. " "
  4085. " ");
  4086. }
  4087. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4088. // A certain header line causes an exception if the header property *name* is
  4089. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4090. // greedy matcher and requires backtracking when there are a lot of ":"
  4091. // characters.
  4092. // This occurs with libc++ but not libstdc++.
  4093. test_raw_request(
  4094. "GET /hi HTTP/1.1\r\n"
  4095. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4096. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4097. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4098. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4099. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4100. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4101. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4102. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4103. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4104. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4105. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4106. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4107. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4108. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4109. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4110. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4111. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4112. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4113. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4114. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4115. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4116. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4117. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4118. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4119. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4120. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4121. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4122. "&&&%%%");
  4123. }
  4124. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4125. // Make sure this doesn't crash the server.
  4126. // In a previous version of the header line regex, the "\r" rendered the line
  4127. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4128. // a new position where the leading white space ended and the field value
  4129. // began.
  4130. // The crash occurs with libc++ but not libstdc++.
  4131. test_raw_request("GET /hi HTTP/1.1\r\n"
  4132. "a:" +
  4133. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4134. "\r\n"
  4135. "\r\n");
  4136. }
  4137. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4138. std::string out;
  4139. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4140. "Content-Type: text/plain\r\n"
  4141. "Transfer-Encoding: chunked\r\n"
  4142. "\r\n"
  4143. "nothex\r\n",
  4144. &out);
  4145. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4146. }
  4147. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4148. std::string out;
  4149. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4150. "Content-Type: text/plain\r\n"
  4151. "Transfer-Encoding: chunked\r\n"
  4152. "\r\n"
  4153. "3\r\n"
  4154. "xyz\r\n"
  4155. "NaN\r\n",
  4156. &out);
  4157. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4158. }
  4159. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4160. std::string out;
  4161. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4162. "Content-Type: text/plain\r\n"
  4163. "Transfer-Encoding: chunked\r\n"
  4164. "\r\n"
  4165. // Length is too large for 64 bits.
  4166. "1ffffffffffffffff\r\n"
  4167. "xyz\r\n",
  4168. &out);
  4169. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4170. }
  4171. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4172. test_raw_request("GET /hi HTTP/1.1\r\n"
  4173. "Content-Type: text/plain\r\n\r");
  4174. }
  4175. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4176. std::string out;
  4177. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4178. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4179. }
  4180. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4181. std::string out;
  4182. std::string request(
  4183. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4184. test_raw_request(request, &out);
  4185. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4186. }
  4187. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4188. Server svr;
  4189. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4190. res.set_header("Cache-Control", "no-cache");
  4191. res.set_chunked_content_provider(
  4192. "text/event-stream", [](size_t offset, DataSink &sink) {
  4193. std::string s = "data:";
  4194. s += std::to_string(offset);
  4195. s += "\n\n";
  4196. auto ret = sink.write(s.data(), s.size());
  4197. EXPECT_TRUE(ret);
  4198. std::this_thread::sleep_for(std::chrono::seconds(1));
  4199. return true;
  4200. });
  4201. });
  4202. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4203. svr.wait_until_ready();
  4204. Client client(HOST, PORT);
  4205. const Headers headers = {{"Accept", "text/event-stream"}};
  4206. auto get_thread = std::thread([&client, &headers]() {
  4207. auto res = client.Get(
  4208. "/events", headers,
  4209. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4210. });
  4211. auto se = detail::scope_exit([&] {
  4212. svr.stop();
  4213. get_thread.join();
  4214. listen_thread.join();
  4215. ASSERT_FALSE(svr.is_running());
  4216. });
  4217. // Give GET time to get a few messages.
  4218. std::this_thread::sleep_for(std::chrono::seconds(2));
  4219. }
  4220. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4221. httplib::Server svr;
  4222. svr.Post("/hi",
  4223. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4224. res.status = StatusCode::OK_200;
  4225. });
  4226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4227. svr.wait_until_ready();
  4228. Client cli(HOST, PORT);
  4229. auto res = cli.Post("/hi", "data", "text/plain");
  4230. ASSERT_TRUE(res);
  4231. EXPECT_EQ(StatusCode::OK_200, res->status);
  4232. svr.stop();
  4233. thread.join();
  4234. ASSERT_FALSE(svr.is_running());
  4235. res = cli.Post("/hi", "data", "text/plain");
  4236. ASSERT_FALSE(res);
  4237. }
  4238. TEST(ServerStopTest, ListenFailure) {
  4239. Server svr;
  4240. auto t = thread([&]() {
  4241. auto ret = svr.listen("????", PORT);
  4242. EXPECT_FALSE(ret);
  4243. });
  4244. svr.wait_until_ready();
  4245. svr.stop();
  4246. t.join();
  4247. }
  4248. TEST(ServerStopTest, Decommision) {
  4249. Server svr;
  4250. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4251. for (int i = 0; i < 4; i++) {
  4252. auto is_even = !(i % 2);
  4253. std::thread t{[&] {
  4254. try {
  4255. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4256. if (is_even) {
  4257. throw std::runtime_error("Some thing that happens to go wrong.");
  4258. }
  4259. svr.listen(HOST, PORT);
  4260. } catch (...) { svr.decommission(); }
  4261. }};
  4262. svr.wait_until_ready();
  4263. // Server is up
  4264. {
  4265. Client cli(HOST, PORT);
  4266. auto res = cli.Get("/hi");
  4267. if (is_even) {
  4268. EXPECT_FALSE(res);
  4269. } else {
  4270. EXPECT_TRUE(res);
  4271. EXPECT_EQ("hi...", res->body);
  4272. }
  4273. }
  4274. svr.stop();
  4275. t.join();
  4276. // Server is down...
  4277. {
  4278. Client cli(HOST, PORT);
  4279. auto res = cli.Get("/hi");
  4280. EXPECT_FALSE(res);
  4281. }
  4282. }
  4283. }
  4284. TEST(StreamingTest, NoContentLengthStreaming) {
  4285. Server svr;
  4286. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4287. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4288. if (offset < 6) {
  4289. sink.os << (offset < 3 ? "a" : "b");
  4290. } else {
  4291. sink.done();
  4292. }
  4293. return true;
  4294. });
  4295. });
  4296. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4297. auto listen_se = detail::scope_exit([&] {
  4298. svr.stop();
  4299. listen_thread.join();
  4300. ASSERT_FALSE(svr.is_running());
  4301. });
  4302. svr.wait_until_ready();
  4303. Client client(HOST, PORT);
  4304. auto get_thread = std::thread([&client]() {
  4305. std::string s;
  4306. auto res =
  4307. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4308. s += std::string(data, len);
  4309. return true;
  4310. });
  4311. EXPECT_EQ("aaabbb", s);
  4312. });
  4313. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4314. // Give GET time to get a few messages.
  4315. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4316. }
  4317. TEST(MountTest, Unmount) {
  4318. Server svr;
  4319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. listen_thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. Client cli("localhost", PORT);
  4327. svr.set_mount_point("/mount2", "./www2");
  4328. auto res = cli.Get("/");
  4329. ASSERT_TRUE(res);
  4330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4331. res = cli.Get("/mount2/dir/test.html");
  4332. ASSERT_TRUE(res);
  4333. EXPECT_EQ(StatusCode::OK_200, res->status);
  4334. svr.set_mount_point("/", "./www");
  4335. res = cli.Get("/dir/");
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::OK_200, res->status);
  4338. svr.remove_mount_point("/");
  4339. res = cli.Get("/dir/");
  4340. ASSERT_TRUE(res);
  4341. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4342. svr.remove_mount_point("/mount2");
  4343. res = cli.Get("/mount2/dir/test.html");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4346. }
  4347. TEST(MountTest, Redicect) {
  4348. Server svr;
  4349. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. listen_thread.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.set_mount_point("/", "./www");
  4356. svr.wait_until_ready();
  4357. Client cli("localhost", PORT);
  4358. auto res = cli.Get("/dir/");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. res = cli.Get("/dir");
  4362. ASSERT_TRUE(res);
  4363. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4364. res = cli.Get("/file");
  4365. ASSERT_TRUE(res);
  4366. EXPECT_EQ(StatusCode::OK_200, res->status);
  4367. res = cli.Get("/file/");
  4368. ASSERT_TRUE(res);
  4369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4370. cli.set_follow_location(true);
  4371. res = cli.Get("/dir");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. }
  4375. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4376. TEST(ExceptionTest, ThrowExceptionInHandler) {
  4377. Server svr;
  4378. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4379. throw std::runtime_error("exception...");
  4380. });
  4381. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4382. throw std::runtime_error("exception\r\n...");
  4383. });
  4384. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4385. auto se = detail::scope_exit([&] {
  4386. svr.stop();
  4387. listen_thread.join();
  4388. ASSERT_FALSE(svr.is_running());
  4389. });
  4390. svr.wait_until_ready();
  4391. Client cli("localhost", PORT);
  4392. {
  4393. auto res = cli.Get("/exception");
  4394. ASSERT_TRUE(res);
  4395. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4396. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4397. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  4398. }
  4399. {
  4400. auto res = cli.Get("/unknown");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4404. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  4405. }
  4406. }
  4407. #endif
  4408. TEST(KeepAliveTest, ReadTimeout) {
  4409. Server svr;
  4410. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4411. std::this_thread::sleep_for(std::chrono::seconds(2));
  4412. res.set_content("a", "text/plain");
  4413. });
  4414. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4415. res.set_content("b", "text/plain");
  4416. });
  4417. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4418. auto se = detail::scope_exit([&] {
  4419. svr.stop();
  4420. listen_thread.join();
  4421. ASSERT_FALSE(svr.is_running());
  4422. });
  4423. svr.wait_until_ready();
  4424. Client cli("localhost", PORT);
  4425. cli.set_keep_alive(true);
  4426. cli.set_read_timeout(std::chrono::seconds(1));
  4427. auto resa = cli.Get("/a");
  4428. ASSERT_FALSE(resa);
  4429. EXPECT_EQ(Error::Read, resa.error());
  4430. auto resb = cli.Get("/b");
  4431. ASSERT_TRUE(resb);
  4432. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4433. EXPECT_EQ("b", resb->body);
  4434. }
  4435. TEST(KeepAliveTest, Issue1041) {
  4436. Server svr;
  4437. svr.set_keep_alive_timeout(3);
  4438. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4439. res.set_content("Hello World!", "text/plain");
  4440. });
  4441. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4442. auto se = detail::scope_exit([&] {
  4443. svr.stop();
  4444. listen_thread.join();
  4445. ASSERT_FALSE(svr.is_running());
  4446. });
  4447. svr.wait_until_ready();
  4448. Client cli(HOST, PORT);
  4449. cli.set_keep_alive(true);
  4450. auto result = cli.Get("/hi");
  4451. ASSERT_TRUE(result);
  4452. EXPECT_EQ(StatusCode::OK_200, result->status);
  4453. std::this_thread::sleep_for(std::chrono::seconds(5));
  4454. result = cli.Get("/hi");
  4455. ASSERT_TRUE(result);
  4456. EXPECT_EQ(StatusCode::OK_200, result->status);
  4457. }
  4458. TEST(KeepAliveTest, Issue1959) {
  4459. Server svr;
  4460. svr.set_keep_alive_timeout(5);
  4461. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4462. res.set_content("a", "text/plain");
  4463. });
  4464. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4465. auto se = detail::scope_exit([&] {
  4466. if (!svr.is_running()) return;
  4467. svr.stop();
  4468. listen_thread.join();
  4469. ASSERT_FALSE(svr.is_running());
  4470. });
  4471. svr.wait_until_ready();
  4472. Client cli("localhost", PORT);
  4473. cli.set_keep_alive(true);
  4474. using namespace std::chrono;
  4475. auto start = steady_clock::now();
  4476. cli.Get("/a");
  4477. svr.stop();
  4478. listen_thread.join();
  4479. auto end = steady_clock::now();
  4480. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4481. EXPECT_LT(elapsed, 5000);
  4482. }
  4483. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4484. TEST(KeepAliveTest, SSLClientReconnection) {
  4485. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4486. ASSERT_TRUE(svr.is_valid());
  4487. svr.set_keep_alive_timeout(1);
  4488. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4489. res.set_content("Hello World!", "text/plain");
  4490. });
  4491. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4492. auto se = detail::scope_exit([&] {
  4493. svr.stop();
  4494. listen_thread.join();
  4495. ASSERT_FALSE(svr.is_running());
  4496. });
  4497. svr.wait_until_ready();
  4498. SSLClient cli(HOST, PORT);
  4499. cli.enable_server_certificate_verification(false);
  4500. cli.set_keep_alive(true);
  4501. auto result = cli.Get("/hi");
  4502. ASSERT_TRUE(result);
  4503. EXPECT_EQ(StatusCode::OK_200, result->status);
  4504. result = cli.Get("/hi");
  4505. ASSERT_TRUE(result);
  4506. EXPECT_EQ(StatusCode::OK_200, result->status);
  4507. std::this_thread::sleep_for(std::chrono::seconds(2));
  4508. // Recoonect
  4509. result = cli.Get("/hi");
  4510. ASSERT_TRUE(result);
  4511. EXPECT_EQ(StatusCode::OK_200, result->status);
  4512. result = cli.Get("/hi");
  4513. ASSERT_TRUE(result);
  4514. EXPECT_EQ(StatusCode::OK_200, result->status);
  4515. }
  4516. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4518. ASSERT_TRUE(svr.is_valid());
  4519. svr.set_keep_alive_timeout(1);
  4520. std::string content = "reconnect";
  4521. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4522. res.set_content("Hello World!", "text/plain");
  4523. });
  4524. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4525. auto se = detail::scope_exit([&] {
  4526. svr.stop();
  4527. listen_thread.join();
  4528. ASSERT_FALSE(svr.is_running());
  4529. });
  4530. svr.wait_until_ready();
  4531. SSLClient cli(HOST, PORT);
  4532. cli.enable_server_certificate_verification(false);
  4533. cli.set_keep_alive(true);
  4534. auto result = cli.Post(
  4535. "/hi", content.size(),
  4536. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4537. sink.write(content.c_str(), content.size());
  4538. return true;
  4539. },
  4540. "text/plain");
  4541. ASSERT_TRUE(result);
  4542. EXPECT_EQ(200, result->status);
  4543. std::this_thread::sleep_for(std::chrono::seconds(2));
  4544. // Recoonect
  4545. result = cli.Post(
  4546. "/hi", content.size(),
  4547. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4548. sink.write(content.c_str(), content.size());
  4549. return true;
  4550. },
  4551. "text/plain");
  4552. ASSERT_TRUE(result);
  4553. EXPECT_EQ(200, result->status);
  4554. result = cli.Post(
  4555. "/hi", content.size(),
  4556. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4557. sink.write(content.c_str(), content.size());
  4558. return true;
  4559. },
  4560. "text/plain");
  4561. ASSERT_TRUE(result);
  4562. EXPECT_EQ(200, result->status);
  4563. }
  4564. #endif
  4565. TEST(ClientProblemDetectionTest, ContentProvider) {
  4566. Server svr;
  4567. size_t content_length = 1024 * 1024;
  4568. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4569. res.set_content_provider(
  4570. content_length, "text/plain",
  4571. [&](size_t offset, size_t length, DataSink &sink) {
  4572. auto out_len = std::min(length, static_cast<size_t>(1024));
  4573. std::string out(out_len, '@');
  4574. sink.write(out.data(), out_len);
  4575. return offset < 4096;
  4576. },
  4577. [](bool success) { ASSERT_FALSE(success); });
  4578. });
  4579. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4580. res.set_content_provider(
  4581. 0, "text/plain",
  4582. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4583. EXPECT_TRUE(false);
  4584. return true;
  4585. },
  4586. [](bool success) { ASSERT_FALSE(success); });
  4587. });
  4588. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4589. auto se = detail::scope_exit([&] {
  4590. svr.stop();
  4591. listen_thread.join();
  4592. ASSERT_FALSE(svr.is_running());
  4593. });
  4594. svr.wait_until_ready();
  4595. Client cli("localhost", PORT);
  4596. {
  4597. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4598. size_t /*data_length*/) { return false; });
  4599. ASSERT_FALSE(res);
  4600. }
  4601. {
  4602. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4603. size_t /*data_length*/) { return false; });
  4604. ASSERT_TRUE(res);
  4605. }
  4606. }
  4607. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4608. Server svr;
  4609. svr.set_error_handler([](Request const &, Response &res) -> void {
  4610. res.set_chunked_content_provider(
  4611. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4612. sink.os << "hello";
  4613. sink.os << "world";
  4614. sink.done();
  4615. return true;
  4616. });
  4617. });
  4618. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4619. auto se = detail::scope_exit([&] {
  4620. svr.stop();
  4621. listen_thread.join();
  4622. ASSERT_FALSE(svr.is_running());
  4623. });
  4624. svr.wait_until_ready();
  4625. Client cli("localhost", PORT);
  4626. auto res = cli.Get("/");
  4627. ASSERT_TRUE(res);
  4628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4629. EXPECT_EQ("helloworld", res->body);
  4630. }
  4631. TEST(LongPollingTest, ClientCloseDetection) {
  4632. Server svr;
  4633. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4634. res.set_chunked_content_provider(
  4635. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4636. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4637. sink.os << "hello";
  4638. auto count = 10;
  4639. while (count > 0 && sink.is_writable()) {
  4640. this_thread::sleep_for(chrono::milliseconds(10));
  4641. }
  4642. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4643. return true;
  4644. });
  4645. });
  4646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4647. auto se = detail::scope_exit([&] {
  4648. svr.stop();
  4649. listen_thread.join();
  4650. ASSERT_FALSE(svr.is_running());
  4651. });
  4652. svr.wait_until_ready();
  4653. Client cli("localhost", PORT);
  4654. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4655. EXPECT_EQ("hello", string(data, data_length));
  4656. return false; // close the socket immediately.
  4657. });
  4658. ASSERT_FALSE(res);
  4659. }
  4660. TEST(GetWithParametersTest, GetWithParameters) {
  4661. Server svr;
  4662. svr.Get("/", [&](const Request &req, Response &) {
  4663. EXPECT_EQ("world", req.get_param_value("hello"));
  4664. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4665. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4666. });
  4667. svr.Get("/params", [&](const Request &req, Response &) {
  4668. EXPECT_EQ("world", req.get_param_value("hello"));
  4669. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4670. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4671. });
  4672. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4673. EXPECT_EQ("resource-id", req.matches[1]);
  4674. EXPECT_EQ("foo", req.get_param_value("param1"));
  4675. EXPECT_EQ("bar", req.get_param_value("param2"));
  4676. });
  4677. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4678. EXPECT_EQ("user-id", req.path_params.at("id"));
  4679. EXPECT_EQ("foo", req.get_param_value("param1"));
  4680. EXPECT_EQ("bar", req.get_param_value("param2"));
  4681. });
  4682. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4683. auto se = detail::scope_exit([&] {
  4684. svr.stop();
  4685. listen_thread.join();
  4686. ASSERT_FALSE(svr.is_running());
  4687. });
  4688. svr.wait_until_ready();
  4689. {
  4690. Client cli(HOST, PORT);
  4691. Params params;
  4692. params.emplace("hello", "world");
  4693. params.emplace("hello2", "world2");
  4694. params.emplace("hello3", "world3");
  4695. auto res = cli.Get("/", params, Headers{});
  4696. ASSERT_TRUE(res);
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. }
  4699. {
  4700. Client cli(HOST, PORT);
  4701. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4702. ASSERT_TRUE(res);
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. }
  4705. {
  4706. Client cli(HOST, PORT);
  4707. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4708. ASSERT_TRUE(res);
  4709. EXPECT_EQ(StatusCode::OK_200, res->status);
  4710. }
  4711. {
  4712. Client cli(HOST, PORT);
  4713. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4714. ASSERT_TRUE(res);
  4715. EXPECT_EQ(StatusCode::OK_200, res->status);
  4716. }
  4717. }
  4718. TEST(GetWithParametersTest, GetWithParameters2) {
  4719. Server svr;
  4720. svr.Get("/", [&](const Request &req, Response &res) {
  4721. auto text = req.get_param_value("hello");
  4722. res.set_content(text, "text/plain");
  4723. });
  4724. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4725. auto se = detail::scope_exit([&] {
  4726. svr.stop();
  4727. listen_thread.join();
  4728. ASSERT_FALSE(svr.is_running());
  4729. });
  4730. svr.wait_until_ready();
  4731. Client cli("localhost", PORT);
  4732. Params params;
  4733. params.emplace("hello", "world");
  4734. std::string body;
  4735. auto res = cli.Get("/", params, Headers{},
  4736. [&](const char *data, size_t data_length) {
  4737. body.append(data, data_length);
  4738. return true;
  4739. });
  4740. ASSERT_TRUE(res);
  4741. EXPECT_EQ(StatusCode::OK_200, res->status);
  4742. EXPECT_EQ("world", body);
  4743. }
  4744. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4745. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4746. auto host = "httpbin.org";
  4747. auto path = std::string{"/range/32"};
  4748. #else
  4749. auto host = "nghttp2.org";
  4750. auto path = std::string{"/httpbin/range/32"};
  4751. #endif
  4752. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4753. SSLClient cli(host);
  4754. #else
  4755. Client cli(host);
  4756. #endif
  4757. cli.set_default_headers({make_range_header({{1, 10}})});
  4758. cli.set_connection_timeout(5);
  4759. {
  4760. auto res = cli.Get(path);
  4761. ASSERT_TRUE(res);
  4762. EXPECT_EQ("bcdefghijk", res->body);
  4763. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4764. }
  4765. {
  4766. auto res = cli.Get(path);
  4767. ASSERT_TRUE(res);
  4768. EXPECT_EQ("bcdefghijk", res->body);
  4769. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4770. }
  4771. }
  4772. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4773. Server svr;
  4774. svr.set_default_headers({{"Hello", "World"}});
  4775. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4776. res.set_content("ok", "text/plain");
  4777. });
  4778. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4779. auto se = detail::scope_exit([&] {
  4780. svr.stop();
  4781. listen_thread.join();
  4782. ASSERT_FALSE(svr.is_running());
  4783. });
  4784. svr.wait_until_ready();
  4785. Client cli("localhost", PORT);
  4786. auto res = cli.Get("/");
  4787. ASSERT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. EXPECT_EQ("ok", res->body);
  4790. EXPECT_EQ("World", res->get_header_value("Hello"));
  4791. }
  4792. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4793. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4795. ASSERT_TRUE(svr.is_valid());
  4796. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4797. std::this_thread::sleep_for(std::chrono::seconds(2));
  4798. res.set_content("a", "text/plain");
  4799. });
  4800. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4801. res.set_content("b", "text/plain");
  4802. });
  4803. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4804. auto se = detail::scope_exit([&] {
  4805. svr.stop();
  4806. listen_thread.join();
  4807. ASSERT_FALSE(svr.is_running());
  4808. });
  4809. svr.wait_until_ready();
  4810. SSLClient cli("localhost", PORT);
  4811. cli.enable_server_certificate_verification(false);
  4812. cli.set_keep_alive(true);
  4813. cli.set_read_timeout(std::chrono::seconds(1));
  4814. auto resa = cli.Get("/a");
  4815. ASSERT_TRUE(!resa);
  4816. EXPECT_EQ(Error::Read, resa.error());
  4817. auto resb = cli.Get("/b");
  4818. ASSERT_TRUE(resb);
  4819. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4820. EXPECT_EQ("b", resb->body);
  4821. }
  4822. #endif
  4823. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4824. protected:
  4825. ServerTestWithAI_PASSIVE()
  4826. : cli_(HOST, PORT)
  4827. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4828. ,
  4829. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4830. #endif
  4831. {
  4832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4833. cli_.enable_server_certificate_verification(false);
  4834. #endif
  4835. }
  4836. virtual void SetUp() {
  4837. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4838. res.set_content("Hello World!", "text/plain");
  4839. });
  4840. t_ = thread(
  4841. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4842. svr_.wait_until_ready();
  4843. }
  4844. virtual void TearDown() {
  4845. svr_.stop();
  4846. t_.join();
  4847. }
  4848. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4849. SSLClient cli_;
  4850. SSLServer svr_;
  4851. #else
  4852. Client cli_;
  4853. Server svr_;
  4854. #endif
  4855. thread t_;
  4856. };
  4857. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4858. auto res = cli_.Get("/hi");
  4859. ASSERT_TRUE(res);
  4860. EXPECT_EQ(StatusCode::OK_200, res->status);
  4861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4862. EXPECT_EQ("Hello World!", res->body);
  4863. }
  4864. class ServerUpDownTest : public ::testing::Test {
  4865. protected:
  4866. ServerUpDownTest() : cli_(HOST, PORT) {}
  4867. virtual void SetUp() {
  4868. t_ = thread([&]() {
  4869. svr_.bind_to_any_port(HOST);
  4870. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4871. ASSERT_TRUE(svr_.listen_after_bind());
  4872. });
  4873. svr_.wait_until_ready();
  4874. }
  4875. virtual void TearDown() {
  4876. svr_.stop();
  4877. t_.join();
  4878. }
  4879. Client cli_;
  4880. Server svr_;
  4881. thread t_;
  4882. };
  4883. TEST_F(ServerUpDownTest, QuickStartStop) {
  4884. // Should not crash, especially when run with
  4885. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4886. }
  4887. class PayloadMaxLengthTest : public ::testing::Test {
  4888. protected:
  4889. PayloadMaxLengthTest()
  4890. : cli_(HOST, PORT)
  4891. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4892. ,
  4893. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4894. #endif
  4895. {
  4896. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4897. cli_.enable_server_certificate_verification(false);
  4898. #endif
  4899. }
  4900. virtual void SetUp() {
  4901. svr_.set_payload_max_length(8);
  4902. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4903. res.set_content("test", "text/plain");
  4904. });
  4905. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4906. svr_.wait_until_ready();
  4907. }
  4908. virtual void TearDown() {
  4909. svr_.stop();
  4910. t_.join();
  4911. }
  4912. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4913. SSLClient cli_;
  4914. SSLServer svr_;
  4915. #else
  4916. Client cli_;
  4917. Server svr_;
  4918. #endif
  4919. thread t_;
  4920. };
  4921. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4922. auto res = cli_.Post("/test", "123456789", "text/plain");
  4923. ASSERT_TRUE(res);
  4924. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4925. res = cli_.Post("/test", "12345678", "text/plain");
  4926. ASSERT_TRUE(res);
  4927. EXPECT_EQ(StatusCode::OK_200, res->status);
  4928. }
  4929. TEST(HostAndPortPropertiesTest, NoSSL) {
  4930. httplib::Client cli("www.google.com", 1234);
  4931. ASSERT_EQ("www.google.com", cli.host());
  4932. ASSERT_EQ(1234, cli.port());
  4933. }
  4934. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4935. httplib::Client cli("www.google.com:1234");
  4936. ASSERT_EQ("www.google.com", cli.host());
  4937. ASSERT_EQ(1234, cli.port());
  4938. }
  4939. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4940. TEST(HostAndPortPropertiesTest, SSL) {
  4941. httplib::SSLClient cli("www.google.com");
  4942. ASSERT_EQ("www.google.com", cli.host());
  4943. ASSERT_EQ(443, cli.port());
  4944. }
  4945. #endif
  4946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4947. TEST(SSLClientTest, UpdateCAStore) {
  4948. httplib::SSLClient httplib_client("www.google.com");
  4949. auto ca_store_1 = X509_STORE_new();
  4950. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4951. nullptr);
  4952. httplib_client.set_ca_cert_store(ca_store_1);
  4953. auto ca_store_2 = X509_STORE_new();
  4954. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4955. nullptr);
  4956. httplib_client.set_ca_cert_store(ca_store_2);
  4957. }
  4958. TEST(SSLClientTest, ServerNameIndication_Online) {
  4959. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4960. auto host = "httpbin.org";
  4961. auto path = std::string{"/get"};
  4962. #else
  4963. auto host = "nghttp2.org";
  4964. auto path = std::string{"/httpbin/get"};
  4965. #endif
  4966. SSLClient cli(host, 443);
  4967. auto res = cli.Get(path);
  4968. ASSERT_TRUE(res);
  4969. ASSERT_EQ(StatusCode::OK_200, res->status);
  4970. }
  4971. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4972. Client cli("https://google.com");
  4973. auto res = cli.Get("/");
  4974. ASSERT_TRUE(res);
  4975. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4976. }
  4977. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4978. SSLClient cli("google.com");
  4979. cli.enable_server_certificate_verification(true);
  4980. cli.set_ca_cert_path("hello");
  4981. auto res = cli.Get("/");
  4982. ASSERT_TRUE(!res);
  4983. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4984. }
  4985. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4986. SSLClient cli("google.com");
  4987. cli.set_ca_cert_path(CA_CERT_FILE);
  4988. auto res = cli.Get("/");
  4989. ASSERT_TRUE(res);
  4990. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4991. }
  4992. TEST(SSLClientTest, ServerCertificateVerification4) {
  4993. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4994. ASSERT_TRUE(svr.is_valid());
  4995. svr.Get("/test", [&](const Request &, Response &res) {
  4996. res.set_content("test", "text/plain");
  4997. svr.stop();
  4998. ASSERT_TRUE(true);
  4999. });
  5000. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5001. auto se = detail::scope_exit([&] {
  5002. t.join();
  5003. ASSERT_FALSE(svr.is_running());
  5004. });
  5005. svr.wait_until_ready();
  5006. SSLClient cli("127.0.0.1", PORT);
  5007. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5008. cli.enable_server_certificate_verification(true);
  5009. cli.set_connection_timeout(30);
  5010. auto res = cli.Get("/test");
  5011. ASSERT_TRUE(res);
  5012. ASSERT_EQ(StatusCode::OK_200, res->status);
  5013. }
  5014. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5015. std::string cert;
  5016. detail::read_file(CA_CERT_FILE, cert);
  5017. SSLClient cli("google.com");
  5018. cli.load_ca_cert_store(cert.data(), cert.size());
  5019. const auto res = cli.Get("/");
  5020. ASSERT_TRUE(res);
  5021. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5022. }
  5023. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5024. // clang-format off
  5025. static constexpr char cert[] =
  5026. "GlobalSign Root CA\n"
  5027. "==================\n"
  5028. "-----BEGIN CERTIFICATE-----\n"
  5029. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5030. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5031. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5032. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5033. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5034. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5035. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5036. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5037. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5038. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5039. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5040. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5041. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5042. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5043. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5044. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5045. "-----END CERTIFICATE-----\n";
  5046. // clang-format on
  5047. SSLClient cli("google.com");
  5048. cli.load_ca_cert_store(cert, sizeof(cert));
  5049. const auto res = cli.Get("/");
  5050. ASSERT_TRUE(res);
  5051. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5052. }
  5053. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5054. SSLClient cli("www.youtube.com");
  5055. cli.set_ca_cert_path(CA_CERT_FILE);
  5056. cli.enable_server_certificate_verification(true);
  5057. cli.set_follow_location(true);
  5058. auto res = cli.Get("/");
  5059. ASSERT_TRUE(res);
  5060. ASSERT_EQ(StatusCode::OK_200, res->status);
  5061. }
  5062. #if 0
  5063. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5064. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5065. ASSERT_TRUE(cli != nullptr);
  5066. cli->set_address_family(AF_INET6);
  5067. cli->set_interface("en0");
  5068. auto res = cli->Get("/get");
  5069. ASSERT_TRUE(res);
  5070. ASSERT_EQ(StatusCode::OK_200, res->status);
  5071. }
  5072. #endif
  5073. void ClientCertPresent(
  5074. const std::string &client_cert_file,
  5075. const std::string &client_private_key_file,
  5076. const std::string &client_encrypted_private_key_pass = std::string()) {
  5077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5078. CLIENT_CA_CERT_DIR);
  5079. ASSERT_TRUE(svr.is_valid());
  5080. svr.Get("/test", [&](const Request &req, Response &res) {
  5081. res.set_content("test", "text/plain");
  5082. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5083. ASSERT_TRUE(peer_cert != nullptr);
  5084. auto subject_name = X509_get_subject_name(peer_cert);
  5085. ASSERT_TRUE(subject_name != nullptr);
  5086. std::string common_name;
  5087. {
  5088. char name[BUFSIZ];
  5089. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5090. name, sizeof(name));
  5091. common_name.assign(name, static_cast<size_t>(name_len));
  5092. }
  5093. EXPECT_EQ("Common Name", common_name);
  5094. X509_free(peer_cert);
  5095. });
  5096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5097. auto se = detail::scope_exit([&] {
  5098. svr.stop();
  5099. t.join();
  5100. ASSERT_FALSE(svr.is_running());
  5101. });
  5102. svr.wait_until_ready();
  5103. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5104. client_encrypted_private_key_pass);
  5105. cli.enable_server_certificate_verification(false);
  5106. cli.set_connection_timeout(30);
  5107. auto res = cli.Get("/test");
  5108. ASSERT_TRUE(res);
  5109. ASSERT_EQ(StatusCode::OK_200, res->status);
  5110. }
  5111. TEST(SSLClientServerTest, ClientCertPresent) {
  5112. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5113. }
  5114. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5115. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5116. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5117. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5118. }
  5119. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5120. void MemoryClientCertPresent(
  5121. const std::string &client_cert_file,
  5122. const std::string &client_private_key_file,
  5123. const std::string &client_encrypted_private_key_pass = std::string()) {
  5124. auto f = fopen(SERVER_CERT_FILE, "r+");
  5125. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5126. fclose(f);
  5127. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5128. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5129. fclose(f);
  5130. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5131. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5132. auto client_ca_cert_store = X509_STORE_new();
  5133. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5134. X509_free(client_cert);
  5135. fclose(f);
  5136. f = fopen(client_cert_file.c_str(), "r+");
  5137. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5138. fclose(f);
  5139. f = fopen(client_private_key_file.c_str(), "r+");
  5140. auto client_private_key = PEM_read_PrivateKey(
  5141. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5142. fclose(f);
  5143. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5144. ASSERT_TRUE(svr.is_valid());
  5145. svr.Get("/test", [&](const Request &req, Response &res) {
  5146. res.set_content("test", "text/plain");
  5147. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5148. ASSERT_TRUE(peer_cert != nullptr);
  5149. auto subject_name = X509_get_subject_name(peer_cert);
  5150. ASSERT_TRUE(subject_name != nullptr);
  5151. std::string common_name;
  5152. {
  5153. char name[BUFSIZ];
  5154. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5155. name, sizeof(name));
  5156. common_name.assign(name, static_cast<size_t>(name_len));
  5157. }
  5158. EXPECT_EQ("Common Name", common_name);
  5159. X509_free(peer_cert);
  5160. });
  5161. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5162. auto se = detail::scope_exit([&] {
  5163. svr.stop();
  5164. t.join();
  5165. ASSERT_FALSE(svr.is_running());
  5166. });
  5167. svr.wait_until_ready();
  5168. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5169. client_encrypted_private_key_pass);
  5170. cli.enable_server_certificate_verification(false);
  5171. cli.set_connection_timeout(30);
  5172. auto res = cli.Get("/test");
  5173. ASSERT_TRUE(res);
  5174. ASSERT_EQ(StatusCode::OK_200, res->status);
  5175. X509_free(server_cert);
  5176. EVP_PKEY_free(server_private_key);
  5177. X509_free(client_cert);
  5178. EVP_PKEY_free(client_private_key);
  5179. }
  5180. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5181. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5182. }
  5183. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5184. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5185. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5186. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5187. }
  5188. #endif
  5189. TEST(SSLClientServerTest, ClientCertMissing) {
  5190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5191. CLIENT_CA_CERT_DIR);
  5192. ASSERT_TRUE(svr.is_valid());
  5193. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5194. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5195. auto se = detail::scope_exit([&] {
  5196. svr.stop();
  5197. t.join();
  5198. ASSERT_FALSE(svr.is_running());
  5199. });
  5200. svr.wait_until_ready();
  5201. SSLClient cli(HOST, PORT);
  5202. auto res = cli.Get("/test");
  5203. cli.set_connection_timeout(30);
  5204. ASSERT_TRUE(!res);
  5205. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5206. }
  5207. TEST(SSLClientServerTest, TrustDirOptional) {
  5208. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5209. ASSERT_TRUE(svr.is_valid());
  5210. svr.Get("/test", [&](const Request &, Response &res) {
  5211. res.set_content("test", "text/plain");
  5212. });
  5213. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5214. auto se = detail::scope_exit([&] {
  5215. svr.stop();
  5216. t.join();
  5217. ASSERT_FALSE(svr.is_running());
  5218. });
  5219. svr.wait_until_ready();
  5220. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5221. cli.enable_server_certificate_verification(false);
  5222. cli.set_connection_timeout(30);
  5223. auto res = cli.Get("/test");
  5224. ASSERT_TRUE(res);
  5225. ASSERT_EQ(StatusCode::OK_200, res->status);
  5226. }
  5227. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5228. class NoListenSSLServer : public SSLServer {
  5229. public:
  5230. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5231. const char *client_ca_cert_file_path,
  5232. const char *client_ca_cert_dir_path = nullptr)
  5233. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5234. client_ca_cert_dir_path),
  5235. stop_(false) {}
  5236. std::atomic_bool stop_;
  5237. private:
  5238. bool process_and_close_socket(socket_t /*sock*/) override {
  5239. // Don't create SSL context
  5240. while (!stop_.load()) {
  5241. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5242. }
  5243. return true;
  5244. }
  5245. };
  5246. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5247. CLIENT_CA_CERT_FILE);
  5248. ASSERT_TRUE(svr.is_valid());
  5249. svr.Get("/test", [&](const Request &, Response &res) {
  5250. res.set_content("test", "text/plain");
  5251. });
  5252. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5253. auto se = detail::scope_exit([&] {
  5254. svr.stop_ = true;
  5255. svr.stop();
  5256. t.join();
  5257. ASSERT_FALSE(svr.is_running());
  5258. });
  5259. svr.wait_until_ready();
  5260. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5261. cli.enable_server_certificate_verification(false);
  5262. cli.set_connection_timeout(1);
  5263. auto res = cli.Get("/test");
  5264. ASSERT_TRUE(!res);
  5265. EXPECT_EQ(Error::SSLConnection, res.error());
  5266. }
  5267. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5268. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5269. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5270. SSL_CTX_set_options(&ssl_ctx,
  5271. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5272. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5273. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5274. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5275. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5276. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5277. "ECDHE-DSS-AES128-SHA256:"
  5278. "ECDHE-RSA-AES256-SHA256:"
  5279. "ECDHE-DSS-AES256-SHA256:";
  5280. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5281. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5282. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5283. SSL_FILETYPE_PEM) != 1) {
  5284. return false;
  5285. }
  5286. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5287. CLIENT_CA_CERT_DIR);
  5288. SSL_CTX_set_verify(
  5289. &ssl_ctx,
  5290. SSL_VERIFY_PEER |
  5291. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5292. nullptr);
  5293. return true;
  5294. };
  5295. SSLServer svr(setup_ssl_ctx_callback);
  5296. ASSERT_TRUE(svr.is_valid());
  5297. svr.Get("/test", [&](const Request &req, Response &res) {
  5298. res.set_content("test", "text/plain");
  5299. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5300. ASSERT_TRUE(peer_cert != nullptr);
  5301. auto subject_name = X509_get_subject_name(peer_cert);
  5302. ASSERT_TRUE(subject_name != nullptr);
  5303. std::string common_name;
  5304. {
  5305. char name[BUFSIZ];
  5306. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5307. name, sizeof(name));
  5308. common_name.assign(name, static_cast<size_t>(name_len));
  5309. }
  5310. EXPECT_EQ("Common Name", common_name);
  5311. X509_free(peer_cert);
  5312. });
  5313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. t.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. });
  5319. svr.wait_until_ready();
  5320. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5321. cli.enable_server_certificate_verification(false);
  5322. cli.set_connection_timeout(30);
  5323. auto res = cli.Get("/test");
  5324. ASSERT_TRUE(res);
  5325. ASSERT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5328. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5329. // prepare large data
  5330. std::random_device seed_gen;
  5331. std::mt19937 random(seed_gen());
  5332. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5333. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5334. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5335. // server
  5336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5337. ASSERT_TRUE(svr.is_valid());
  5338. svr.Post("/binary", [&](const Request &req, Response &res) {
  5339. EXPECT_EQ(large_size_byte, req.body.size());
  5340. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5341. res.set_content(req.body, "application/octet-stream");
  5342. });
  5343. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5344. auto se = detail::scope_exit([&] {
  5345. svr.stop();
  5346. listen_thread.join();
  5347. ASSERT_FALSE(svr.is_running());
  5348. });
  5349. svr.wait_until_ready();
  5350. // client POST
  5351. SSLClient cli("localhost", PORT);
  5352. cli.enable_server_certificate_verification(false);
  5353. cli.set_read_timeout(std::chrono::seconds(100));
  5354. cli.set_write_timeout(std::chrono::seconds(100));
  5355. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5356. large_size_byte, "application/octet-stream");
  5357. // compare
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ(large_size_byte, res->body.size());
  5360. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5361. }
  5362. #endif
  5363. #ifdef _WIN32
  5364. TEST(CleanupTest, WSACleanup) {
  5365. int ret = WSACleanup();
  5366. ASSERT_EQ(0, ret);
  5367. }
  5368. #endif
  5369. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5370. TEST(NoSSLSupport, SimpleInterface) {
  5371. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5372. }
  5373. #endif
  5374. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5375. TEST(InvalidScheme, SimpleInterface) {
  5376. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5377. }
  5378. #endif
  5379. TEST(NoScheme, SimpleInterface) {
  5380. Client cli("yahoo.com:80");
  5381. ASSERT_TRUE(cli.is_valid());
  5382. }
  5383. TEST(SendAPI, SimpleInterface_Online) {
  5384. Client cli("http://yahoo.com");
  5385. Request req;
  5386. req.method = "GET";
  5387. req.path = "/";
  5388. auto res = cli.send(req);
  5389. ASSERT_TRUE(res);
  5390. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5391. }
  5392. TEST(ClientImplMethods, GetSocketTest) {
  5393. httplib::Server svr;
  5394. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5395. res.status = StatusCode::OK_200;
  5396. });
  5397. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5398. auto se = detail::scope_exit([&] {
  5399. svr.stop();
  5400. thread.join();
  5401. ASSERT_FALSE(svr.is_running());
  5402. });
  5403. svr.wait_until_ready();
  5404. {
  5405. httplib::Client cli("http://127.0.0.1:3333");
  5406. cli.set_keep_alive(true);
  5407. // Use the behavior of cpp-httplib of opening the connection
  5408. // only when the first request happens. If that changes,
  5409. // this test would be obsolete.
  5410. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5411. // This also implicitly tests the server. But other tests would fail much
  5412. // earlier than this one to be considered.
  5413. auto res = cli.Get("/");
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5417. }
  5418. }
  5419. // Disabled due to out-of-memory problem on GitHub Actions
  5420. #ifdef _WIN64
  5421. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5422. // allocate content size larger than 2GB in memory
  5423. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5424. char *content = (char *)malloc(content_size);
  5425. ASSERT_TRUE(content);
  5426. Server svr;
  5427. svr.Get("/foo",
  5428. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5429. res.set_content(content, content_size, "application/octet-stream");
  5430. });
  5431. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5432. auto se = detail::scope_exit([&] {
  5433. svr.stop();
  5434. listen_thread.join();
  5435. if (content) free(content);
  5436. ASSERT_FALSE(svr.is_running());
  5437. });
  5438. svr.wait_until_ready();
  5439. Client cli(HOST, PORT);
  5440. auto res = cli.Get("/foo");
  5441. ASSERT_TRUE(res);
  5442. EXPECT_EQ(StatusCode::OK_200, res->status);
  5443. EXPECT_EQ(content_size, res->body.length());
  5444. }
  5445. #endif
  5446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5447. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5448. Client cli("http://yahoo.com");
  5449. auto res = cli.Get("/");
  5450. ASSERT_TRUE(res);
  5451. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5452. cli.set_follow_location(true);
  5453. res = cli.Get("/");
  5454. ASSERT_TRUE(res);
  5455. EXPECT_EQ(StatusCode::OK_200, res->status);
  5456. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5457. }
  5458. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5459. Client cli("https://yahoo.com");
  5460. auto res = cli.Get("/");
  5461. ASSERT_TRUE(res);
  5462. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5463. cli.set_follow_location(true);
  5464. res = cli.Get("/");
  5465. ASSERT_TRUE(res);
  5466. EXPECT_EQ(StatusCode::OK_200, res->status);
  5467. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5468. }
  5469. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5470. Client cli("https://yahoo.com");
  5471. auto res = cli.Get("/");
  5472. ASSERT_TRUE(res);
  5473. ASSERT_FALSE(!res);
  5474. ASSERT_TRUE(res);
  5475. ASSERT_FALSE(res == nullptr);
  5476. ASSERT_TRUE(res != nullptr);
  5477. EXPECT_EQ(Error::Success, res.error());
  5478. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5479. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5480. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5481. cli.set_follow_location(true);
  5482. res = cli.Get("/");
  5483. ASSERT_TRUE(res);
  5484. EXPECT_EQ(Error::Success, res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5486. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5487. EXPECT_EQ(StatusCode::OK_200, res->status);
  5488. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5489. }
  5490. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5491. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5492. Client cli("https://cdnjs.cloudflare.com");
  5493. auto res =
  5494. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5495. ASSERT_TRUE(res);
  5496. EXPECT_EQ(StatusCode::OK_200, res->status);
  5497. EXPECT_EQ(287630U, res->body.size());
  5498. EXPECT_EQ("application/javascript; charset=utf-8",
  5499. res->get_header_value("Content-Type"));
  5500. }
  5501. #endif
  5502. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5503. Client cli("https://nghttp2.org");
  5504. cli.set_follow_location(true);
  5505. auto res =
  5506. cli.Get("/httpbin/"
  5507. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5508. ASSERT_TRUE(res);
  5509. EXPECT_EQ(StatusCode::OK_200, res->status);
  5510. }
  5511. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5512. Client cli("https://nghttp2.org");
  5513. cli.set_follow_location(true);
  5514. Params params;
  5515. params.emplace("url", "http://www.google.com");
  5516. params.emplace("status_code", "302");
  5517. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5518. ASSERT_TRUE(res);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. }
  5521. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5522. Client cli("https://nghttp2.org");
  5523. cli.set_follow_location(true);
  5524. Params params;
  5525. params.emplace("url", "http://www.google.com");
  5526. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5527. ASSERT_TRUE(res);
  5528. EXPECT_EQ(StatusCode::OK_200, res->status);
  5529. }
  5530. TEST(HttpToHttpsRedirectTest, CertFile) {
  5531. Server svr;
  5532. ASSERT_TRUE(svr.is_valid());
  5533. svr.Get("/index", [&](const Request &, Response &res) {
  5534. res.set_redirect("https://127.0.0.1:1235/index");
  5535. svr.stop();
  5536. });
  5537. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5538. ASSERT_TRUE(ssl_svr.is_valid());
  5539. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5540. res.set_content("test", "text/plain");
  5541. ssl_svr.stop();
  5542. });
  5543. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5544. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5545. auto se = detail::scope_exit([&] {
  5546. t2.join();
  5547. t.join();
  5548. ASSERT_FALSE(svr.is_running());
  5549. });
  5550. svr.wait_until_ready();
  5551. ssl_svr.wait_until_ready();
  5552. Client cli("127.0.0.1", PORT);
  5553. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5554. cli.enable_server_certificate_verification(true);
  5555. cli.set_follow_location(true);
  5556. cli.set_connection_timeout(30);
  5557. auto res = cli.Get("/index");
  5558. ASSERT_TRUE(res);
  5559. ASSERT_EQ(StatusCode::OK_200, res->status);
  5560. }
  5561. TEST(MultipartFormDataTest, LargeData) {
  5562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5563. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5564. const ContentReader &content_reader) {
  5565. if (req.is_multipart_form_data()) {
  5566. MultipartFormDataItems files;
  5567. content_reader(
  5568. [&](const MultipartFormData &file) {
  5569. files.push_back(file);
  5570. return true;
  5571. },
  5572. [&](const char *data, size_t data_length) {
  5573. files.back().content.append(data, data_length);
  5574. return true;
  5575. });
  5576. EXPECT_TRUE(std::string(files[0].name) == "document");
  5577. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5578. EXPECT_TRUE(files[0].filename == "2MB_data");
  5579. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5580. EXPECT_TRUE(files[1].name == "hello");
  5581. EXPECT_TRUE(files[1].content == "world");
  5582. EXPECT_TRUE(files[1].filename == "");
  5583. EXPECT_TRUE(files[1].content_type == "");
  5584. } else {
  5585. std::string body;
  5586. content_reader([&](const char *data, size_t data_length) {
  5587. body.append(data, data_length);
  5588. return true;
  5589. });
  5590. }
  5591. });
  5592. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5593. auto se = detail::scope_exit([&] {
  5594. svr.stop();
  5595. t.join();
  5596. ASSERT_FALSE(svr.is_running());
  5597. });
  5598. svr.wait_until_ready();
  5599. {
  5600. std::string data(1024 * 1024 * 2, '.');
  5601. std::stringstream buffer;
  5602. buffer << data;
  5603. Client cli("https://localhost:8080");
  5604. cli.enable_server_certificate_verification(false);
  5605. MultipartFormDataItems items{
  5606. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5607. {"hello", "world", "", ""},
  5608. };
  5609. auto res = cli.Post("/post", items);
  5610. ASSERT_TRUE(res);
  5611. ASSERT_EQ(StatusCode::OK_200, res->status);
  5612. }
  5613. }
  5614. TEST(MultipartFormDataTest, DataProviderItems) {
  5615. std::random_device seed_gen;
  5616. std::mt19937 random(seed_gen());
  5617. std::string rand1;
  5618. rand1.resize(1000);
  5619. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5620. std::string rand2;
  5621. rand2.resize(3000);
  5622. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5624. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5625. const ContentReader &content_reader) {
  5626. ASSERT_FALSE(req.is_multipart_form_data());
  5627. std::string body;
  5628. content_reader([&](const char *data, size_t data_length) {
  5629. body.append(data, data_length);
  5630. return true;
  5631. });
  5632. EXPECT_EQ(body, "");
  5633. });
  5634. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5635. const ContentReader &content_reader) {
  5636. ASSERT_TRUE(req.is_multipart_form_data());
  5637. MultipartFormDataItems files;
  5638. content_reader(
  5639. [&](const MultipartFormData &file) {
  5640. files.push_back(file);
  5641. return true;
  5642. },
  5643. [&](const char *data, size_t data_length) {
  5644. files.back().content.append(data, data_length);
  5645. return true;
  5646. });
  5647. ASSERT_TRUE(files.size() == 2);
  5648. EXPECT_EQ(std::string(files[0].name), "name1");
  5649. EXPECT_EQ(files[0].content, "Testing123");
  5650. EXPECT_EQ(files[0].filename, "filename1");
  5651. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5652. EXPECT_EQ(files[1].name, "name2");
  5653. EXPECT_EQ(files[1].content, "Testing456");
  5654. EXPECT_EQ(files[1].filename, "");
  5655. EXPECT_EQ(files[1].content_type, "");
  5656. });
  5657. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5658. const ContentReader &content_reader) {
  5659. ASSERT_TRUE(req.is_multipart_form_data());
  5660. MultipartFormDataItems files;
  5661. content_reader(
  5662. [&](const MultipartFormData &file) {
  5663. files.push_back(file);
  5664. return true;
  5665. },
  5666. [&](const char *data, size_t data_length) {
  5667. files.back().content.append(data, data_length);
  5668. return true;
  5669. });
  5670. ASSERT_TRUE(files.size() == 2);
  5671. EXPECT_EQ(files[0].name, "name3");
  5672. EXPECT_EQ(files[0].content, rand1);
  5673. EXPECT_EQ(files[0].filename, "filename3");
  5674. EXPECT_EQ(files[0].content_type, "");
  5675. EXPECT_EQ(files[1].name, "name4");
  5676. EXPECT_EQ(files[1].content, rand2);
  5677. EXPECT_EQ(files[1].filename, "filename4");
  5678. EXPECT_EQ(files[1].content_type, "");
  5679. });
  5680. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5681. const ContentReader &content_reader) {
  5682. ASSERT_TRUE(req.is_multipart_form_data());
  5683. MultipartFormDataItems files;
  5684. content_reader(
  5685. [&](const MultipartFormData &file) {
  5686. files.push_back(file);
  5687. return true;
  5688. },
  5689. [&](const char *data, size_t data_length) {
  5690. files.back().content.append(data, data_length);
  5691. return true;
  5692. });
  5693. ASSERT_TRUE(files.size() == 4);
  5694. EXPECT_EQ(std::string(files[0].name), "name1");
  5695. EXPECT_EQ(files[0].content, "Testing123");
  5696. EXPECT_EQ(files[0].filename, "filename1");
  5697. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5698. EXPECT_EQ(files[1].name, "name2");
  5699. EXPECT_EQ(files[1].content, "Testing456");
  5700. EXPECT_EQ(files[1].filename, "");
  5701. EXPECT_EQ(files[1].content_type, "");
  5702. EXPECT_EQ(files[2].name, "name3");
  5703. EXPECT_EQ(files[2].content, rand1);
  5704. EXPECT_EQ(files[2].filename, "filename3");
  5705. EXPECT_EQ(files[2].content_type, "");
  5706. EXPECT_EQ(files[3].name, "name4");
  5707. EXPECT_EQ(files[3].content, rand2);
  5708. EXPECT_EQ(files[3].filename, "filename4");
  5709. EXPECT_EQ(files[3].content_type, "");
  5710. });
  5711. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5712. auto se = detail::scope_exit([&] {
  5713. svr.stop();
  5714. t.join();
  5715. ASSERT_FALSE(svr.is_running());
  5716. });
  5717. svr.wait_until_ready();
  5718. {
  5719. Client cli("https://localhost:8080");
  5720. cli.enable_server_certificate_verification(false);
  5721. MultipartFormDataItems items{
  5722. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5723. {"name2", "Testing456", "", ""}, // not a file
  5724. };
  5725. {
  5726. auto res = cli.Post("/post-none", {}, {}, {});
  5727. ASSERT_TRUE(res);
  5728. ASSERT_EQ(StatusCode::OK_200, res->status);
  5729. }
  5730. MultipartFormDataProviderItems providers;
  5731. {
  5732. auto res =
  5733. cli.Post("/post-items", {}, items, providers); // empty providers
  5734. ASSERT_TRUE(res);
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. }
  5737. providers.push_back({"name3",
  5738. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5739. // test the offset is given correctly at each step
  5740. if (!offset)
  5741. sink.os.write(rand1.data(), 30);
  5742. else if (offset == 30)
  5743. sink.os.write(rand1.data() + 30, 300);
  5744. else if (offset == 330)
  5745. sink.os.write(rand1.data() + 330, 670);
  5746. else if (offset == rand1.size())
  5747. sink.done();
  5748. return true;
  5749. },
  5750. "filename3",
  5751. {}});
  5752. providers.push_back({"name4",
  5753. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5754. // test the offset is given correctly at each step
  5755. if (!offset)
  5756. sink.os.write(rand2.data(), 2000);
  5757. else if (offset == 2000)
  5758. sink.os.write(rand2.data() + 2000, 1);
  5759. else if (offset == 2001)
  5760. sink.os.write(rand2.data() + 2001, 999);
  5761. else if (offset == rand2.size())
  5762. sink.done();
  5763. return true;
  5764. },
  5765. "filename4",
  5766. {}});
  5767. {
  5768. auto res = cli.Post("/post-providers", {}, {}, providers);
  5769. ASSERT_TRUE(res);
  5770. ASSERT_EQ(StatusCode::OK_200, res->status);
  5771. }
  5772. {
  5773. auto res = cli.Post("/post-both", {}, items, providers);
  5774. ASSERT_TRUE(res);
  5775. ASSERT_EQ(StatusCode::OK_200, res->status);
  5776. }
  5777. }
  5778. }
  5779. TEST(MultipartFormDataTest, BadHeader) {
  5780. Server svr;
  5781. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5782. res.set_content("ok", "text/plain");
  5783. });
  5784. thread t = thread([&] { svr.listen(HOST, PORT); });
  5785. auto se = detail::scope_exit([&] {
  5786. svr.stop();
  5787. t.join();
  5788. ASSERT_FALSE(svr.is_running());
  5789. });
  5790. svr.wait_until_ready();
  5791. const std::string body =
  5792. "This is the preamble. It is to be ignored, though it\r\n"
  5793. "is a handy place for composition agents to include an\r\n"
  5794. "explanatory note to non-MIME conformant readers.\r\n"
  5795. "\r\n"
  5796. "\r\n"
  5797. "--simple boundary\r\n"
  5798. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5799. ": BAD...\r\n"
  5800. "\r\n"
  5801. "value1\r\n"
  5802. "--simple boundary\r\n"
  5803. "Content-Disposition: form-data; name=\"field2\"; "
  5804. "filename=\"example.txt\"\r\n"
  5805. "\r\n"
  5806. "value2\r\n"
  5807. "--simple boundary--\r\n"
  5808. "This is the epilogue. It is also to be ignored.\r\n";
  5809. std::string content_type =
  5810. R"(multipart/form-data; boundary="simple boundary")";
  5811. Client cli(HOST, PORT);
  5812. auto res = cli.Post("/post", body, content_type.c_str());
  5813. ASSERT_TRUE(res);
  5814. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5815. }
  5816. TEST(MultipartFormDataTest, WithPreamble) {
  5817. Server svr;
  5818. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5819. res.set_content("ok", "text/plain");
  5820. });
  5821. thread t = thread([&] { svr.listen(HOST, PORT); });
  5822. auto se = detail::scope_exit([&] {
  5823. svr.stop();
  5824. t.join();
  5825. ASSERT_FALSE(svr.is_running());
  5826. });
  5827. svr.wait_until_ready();
  5828. const std::string body =
  5829. "This is the preamble. It is to be ignored, though it\r\n"
  5830. "is a handy place for composition agents to include an\r\n"
  5831. "explanatory note to non-MIME conformant readers.\r\n"
  5832. "\r\n"
  5833. "\r\n"
  5834. "--simple boundary\r\n"
  5835. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5836. "\r\n"
  5837. "value1\r\n"
  5838. "--simple boundary\r\n"
  5839. "Content-Disposition: form-data; name=\"field2\"; "
  5840. "filename=\"example.txt\"\r\n"
  5841. "\r\n"
  5842. "value2\r\n"
  5843. "--simple boundary--\r\n"
  5844. "This is the epilogue. It is also to be ignored.\r\n";
  5845. std::string content_type =
  5846. R"(multipart/form-data; boundary="simple boundary")";
  5847. Client cli(HOST, PORT);
  5848. auto res = cli.Post("/post", body, content_type.c_str());
  5849. ASSERT_TRUE(res);
  5850. EXPECT_EQ(StatusCode::OK_200, res->status);
  5851. }
  5852. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5854. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5855. const ContentReader &content_reader) {
  5856. if (req.is_multipart_form_data()) {
  5857. MultipartFormDataItems files;
  5858. content_reader(
  5859. [&](const MultipartFormData &file) {
  5860. files.push_back(file);
  5861. return true;
  5862. },
  5863. [&](const char *data, size_t data_length) {
  5864. files.back().content.append(data, data_length);
  5865. return true;
  5866. });
  5867. EXPECT_TRUE(std::string(files[0].name) == "document");
  5868. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5869. EXPECT_TRUE(files[0].filename == "2MB_data");
  5870. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5871. EXPECT_TRUE(files[1].name == "hello");
  5872. EXPECT_TRUE(files[1].content == "world");
  5873. EXPECT_TRUE(files[1].filename == "");
  5874. EXPECT_TRUE(files[1].content_type == "");
  5875. } else {
  5876. std::string body;
  5877. content_reader([&](const char *data, size_t data_length) {
  5878. body.append(data, data_length);
  5879. return true;
  5880. });
  5881. }
  5882. });
  5883. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5884. auto se = detail::scope_exit([&] {
  5885. svr.stop();
  5886. t.join();
  5887. ASSERT_FALSE(svr.is_running());
  5888. });
  5889. svr.wait_until_ready();
  5890. {
  5891. std::string data(1024 * 1024 * 2, '.');
  5892. std::stringstream buffer;
  5893. buffer << data;
  5894. Client cli("https://localhost:8080");
  5895. cli.enable_server_certificate_verification(false);
  5896. MultipartFormDataItems items{
  5897. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5898. {"hello", "world", "", ""},
  5899. };
  5900. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5901. ASSERT_TRUE(res);
  5902. ASSERT_EQ(StatusCode::OK_200, res->status);
  5903. }
  5904. }
  5905. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5906. std::string data(1024 * 1024 * 2, '&');
  5907. std::stringstream buffer;
  5908. buffer << data;
  5909. Client cli("https://localhost:8080");
  5910. MultipartFormDataItems items{
  5911. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5912. {"hello", "world", "", ""},
  5913. };
  5914. for (const char &c : " \t\r\n") {
  5915. auto res =
  5916. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5917. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5918. ASSERT_FALSE(res);
  5919. }
  5920. }
  5921. TEST(MultipartFormDataTest, PutFormData) {
  5922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5923. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5924. const ContentReader &content_reader) {
  5925. if (req.is_multipart_form_data()) {
  5926. MultipartFormDataItems files;
  5927. content_reader(
  5928. [&](const MultipartFormData &file) {
  5929. files.push_back(file);
  5930. return true;
  5931. },
  5932. [&](const char *data, size_t data_length) {
  5933. files.back().content.append(data, data_length);
  5934. return true;
  5935. });
  5936. EXPECT_TRUE(std::string(files[0].name) == "document");
  5937. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5938. EXPECT_TRUE(files[0].filename == "2MB_data");
  5939. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5940. EXPECT_TRUE(files[1].name == "hello");
  5941. EXPECT_TRUE(files[1].content == "world");
  5942. EXPECT_TRUE(files[1].filename == "");
  5943. EXPECT_TRUE(files[1].content_type == "");
  5944. } else {
  5945. std::string body;
  5946. content_reader([&](const char *data, size_t data_length) {
  5947. body.append(data, data_length);
  5948. return true;
  5949. });
  5950. }
  5951. });
  5952. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5953. auto se = detail::scope_exit([&] {
  5954. svr.stop();
  5955. t.join();
  5956. ASSERT_FALSE(svr.is_running());
  5957. });
  5958. svr.wait_until_ready();
  5959. {
  5960. std::string data(1024 * 1024 * 2, '&');
  5961. std::stringstream buffer;
  5962. buffer << data;
  5963. Client cli("https://localhost:8080");
  5964. cli.enable_server_certificate_verification(false);
  5965. MultipartFormDataItems items{
  5966. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5967. {"hello", "world", "", ""},
  5968. };
  5969. auto res = cli.Put("/put", items);
  5970. ASSERT_TRUE(res);
  5971. ASSERT_EQ(StatusCode::OK_200, res->status);
  5972. }
  5973. }
  5974. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5976. svr.Put("/put_customboundary",
  5977. [&](const Request &req, const Response & /*res*/,
  5978. const ContentReader &content_reader) {
  5979. if (req.is_multipart_form_data()) {
  5980. MultipartFormDataItems files;
  5981. content_reader(
  5982. [&](const MultipartFormData &file) {
  5983. files.push_back(file);
  5984. return true;
  5985. },
  5986. [&](const char *data, size_t data_length) {
  5987. files.back().content.append(data, data_length);
  5988. return true;
  5989. });
  5990. EXPECT_TRUE(std::string(files[0].name) == "document");
  5991. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5992. EXPECT_TRUE(files[0].filename == "2MB_data");
  5993. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5994. EXPECT_TRUE(files[1].name == "hello");
  5995. EXPECT_TRUE(files[1].content == "world");
  5996. EXPECT_TRUE(files[1].filename == "");
  5997. EXPECT_TRUE(files[1].content_type == "");
  5998. } else {
  5999. std::string body;
  6000. content_reader([&](const char *data, size_t data_length) {
  6001. body.append(data, data_length);
  6002. return true;
  6003. });
  6004. }
  6005. });
  6006. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. ASSERT_FALSE(svr.is_running());
  6011. });
  6012. svr.wait_until_ready();
  6013. {
  6014. std::string data(1024 * 1024 * 2, '&');
  6015. std::stringstream buffer;
  6016. buffer << data;
  6017. Client cli("https://localhost:8080");
  6018. cli.enable_server_certificate_verification(false);
  6019. MultipartFormDataItems items{
  6020. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6021. {"hello", "world", "", ""},
  6022. };
  6023. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6024. ASSERT_TRUE(res);
  6025. ASSERT_EQ(StatusCode::OK_200, res->status);
  6026. }
  6027. }
  6028. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6029. std::string data(1024 * 1024 * 2, '&');
  6030. std::stringstream buffer;
  6031. buffer << data;
  6032. Client cli("https://localhost:8080");
  6033. cli.enable_server_certificate_verification(false);
  6034. MultipartFormDataItems items{
  6035. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6036. {"hello", "world", "", ""},
  6037. };
  6038. for (const char &c : " \t\r\n") {
  6039. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6040. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6041. ASSERT_FALSE(res);
  6042. }
  6043. }
  6044. TEST(MultipartFormDataTest, AlternateFilename) {
  6045. auto handled = false;
  6046. Server svr;
  6047. svr.Post("/test", [&](const Request &req, Response &res) {
  6048. ASSERT_EQ(3u, req.files.size());
  6049. auto it = req.files.begin();
  6050. ASSERT_EQ("file1", it->second.name);
  6051. ASSERT_EQ("A.txt", it->second.filename);
  6052. ASSERT_EQ("text/plain", it->second.content_type);
  6053. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6054. ++it;
  6055. ASSERT_EQ("file2", it->second.name);
  6056. ASSERT_EQ("a.html", it->second.filename);
  6057. ASSERT_EQ("text/html", it->second.content_type);
  6058. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6059. it->second.content);
  6060. ++it;
  6061. ASSERT_EQ("text", it->second.name);
  6062. ASSERT_EQ("", it->second.filename);
  6063. ASSERT_EQ("", it->second.content_type);
  6064. ASSERT_EQ("text default", it->second.content);
  6065. res.set_content("ok", "text/plain");
  6066. handled = true;
  6067. });
  6068. thread t = thread([&] { svr.listen(HOST, PORT); });
  6069. auto se = detail::scope_exit([&] {
  6070. svr.stop();
  6071. t.join();
  6072. ASSERT_FALSE(svr.is_running());
  6073. ASSERT_TRUE(handled);
  6074. });
  6075. svr.wait_until_ready();
  6076. auto req = "POST /test HTTP/1.1\r\n"
  6077. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6078. "Content-Length: 399\r\n"
  6079. "\r\n"
  6080. "----------\r\n"
  6081. "Content-Disposition: form-data; name=\"text\"\r\n"
  6082. "\r\n"
  6083. "text default\r\n"
  6084. "----------\r\n"
  6085. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6086. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6087. "Content-Type: text/plain\r\n"
  6088. "\r\n"
  6089. "Content of a.txt.\r\n"
  6090. "\r\n"
  6091. "----------\r\n"
  6092. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6093. "\"a.html\"\r\n"
  6094. "Content-Type: text/html\r\n"
  6095. "\r\n"
  6096. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6097. "\r\n"
  6098. "------------\r\n";
  6099. ASSERT_TRUE(send_request(1, req));
  6100. }
  6101. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6102. auto handled = false;
  6103. Server svr;
  6104. svr.Post("/test", [&](const Request &req, Response &) {
  6105. ASSERT_EQ(2u, req.files.size());
  6106. auto it = req.files.begin();
  6107. ASSERT_EQ("text1", it->second.name);
  6108. ASSERT_EQ("text1", it->second.content);
  6109. ++it;
  6110. ASSERT_EQ("text2", it->second.name);
  6111. ASSERT_EQ("text2", it->second.content);
  6112. handled = true;
  6113. });
  6114. thread t = thread([&] { svr.listen(HOST, PORT); });
  6115. auto se = detail::scope_exit([&] {
  6116. svr.stop();
  6117. t.join();
  6118. ASSERT_FALSE(svr.is_running());
  6119. ASSERT_TRUE(handled);
  6120. });
  6121. svr.wait_until_ready();
  6122. auto req = "POST /test HTTP/1.1\r\n"
  6123. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6124. "Content-Length: 146\r\n"
  6125. "\r\n----------\r\n"
  6126. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6127. "\r\n"
  6128. "text1"
  6129. "\r\n----------\r\n"
  6130. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6131. "\r\n"
  6132. "text2"
  6133. "\r\n------------";
  6134. std::string resonse;
  6135. ASSERT_TRUE(send_request(1, req, &resonse));
  6136. ASSERT_EQ("200", resonse.substr(9, 3));
  6137. }
  6138. TEST(MultipartFormDataTest, ContentLength) {
  6139. auto handled = false;
  6140. Server svr;
  6141. svr.Post("/test", [&](const Request &req, Response &) {
  6142. ASSERT_EQ(2u, req.files.size());
  6143. auto it = req.files.begin();
  6144. ASSERT_EQ("text1", it->second.name);
  6145. ASSERT_EQ("text1", it->second.content);
  6146. ++it;
  6147. ASSERT_EQ("text2", it->second.name);
  6148. ASSERT_EQ("text2", it->second.content);
  6149. handled = true;
  6150. });
  6151. thread t = thread([&] { svr.listen(HOST, PORT); });
  6152. auto se = detail::scope_exit([&] {
  6153. svr.stop();
  6154. t.join();
  6155. ASSERT_FALSE(svr.is_running());
  6156. ASSERT_TRUE(handled);
  6157. });
  6158. svr.wait_until_ready();
  6159. auto req = "POST /test HTTP/1.1\r\n"
  6160. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6161. "Content-Length: 167\r\n"
  6162. "\r\n----------\r\n"
  6163. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6164. "Content-Length: 5\r\n"
  6165. "\r\n"
  6166. "text1"
  6167. "\r\n----------\r\n"
  6168. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6169. "\r\n"
  6170. "text2"
  6171. "\r\n------------\r\n";
  6172. std::string resonse;
  6173. ASSERT_TRUE(send_request(1, req, &resonse));
  6174. ASSERT_EQ("200", resonse.substr(9, 3));
  6175. }
  6176. #endif
  6177. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6178. static constexpr unsigned int number_of_tasks{1000000};
  6179. std::atomic_uint count{0};
  6180. std::unique_ptr<TaskQueue> task_queue{
  6181. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6182. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6183. auto queued = task_queue->enqueue(
  6184. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6185. EXPECT_TRUE(queued);
  6186. }
  6187. EXPECT_NO_THROW(task_queue->shutdown());
  6188. EXPECT_EQ(number_of_tasks, count.load());
  6189. }
  6190. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6191. static constexpr unsigned int number_of_tasks{1000000};
  6192. static constexpr unsigned int qlimit{2};
  6193. unsigned int queued_count{0};
  6194. std::atomic_uint count{0};
  6195. std::unique_ptr<TaskQueue> task_queue{
  6196. new ThreadPool{/*num_threads=*/1, qlimit}};
  6197. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6198. if (task_queue->enqueue(
  6199. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6200. queued_count++;
  6201. }
  6202. }
  6203. EXPECT_NO_THROW(task_queue->shutdown());
  6204. EXPECT_EQ(queued_count, count.load());
  6205. EXPECT_TRUE(queued_count <= number_of_tasks);
  6206. EXPECT_TRUE(queued_count >= qlimit);
  6207. }
  6208. TEST(TaskQueueTest, MaxQueuedRequests) {
  6209. static constexpr unsigned int qlimit{3};
  6210. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6211. std::condition_variable sem_cv;
  6212. std::mutex sem_mtx;
  6213. int credits = 0;
  6214. bool queued;
  6215. /* Fill up the queue with tasks that will block until we give them credits to
  6216. * complete. */
  6217. for (unsigned int n = 0; n <= qlimit;) {
  6218. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6219. std::unique_lock<std::mutex> lock(sem_mtx);
  6220. while (credits <= 0) {
  6221. sem_cv.wait(lock);
  6222. }
  6223. /* Consume the credit and signal the test code if they are all gone. */
  6224. if (--credits == 0) { sem_cv.notify_one(); }
  6225. });
  6226. if (n < qlimit) {
  6227. /* The first qlimit enqueues must succeed. */
  6228. EXPECT_TRUE(queued);
  6229. } else {
  6230. /* The last one will succeed only when the worker thread
  6231. * starts and dequeues the first blocking task. Although
  6232. * not necessary for the correctness of this test, we sleep for
  6233. * a short while to avoid busy waiting. */
  6234. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6235. }
  6236. if (queued) { n++; }
  6237. }
  6238. /* Further enqueues must fail since the queue is full. */
  6239. for (auto i = 0; i < 4; i++) {
  6240. queued = task_queue->enqueue([] {});
  6241. EXPECT_FALSE(queued);
  6242. }
  6243. /* Give the credits to allow the previous tasks to complete. */
  6244. {
  6245. std::unique_lock<std::mutex> lock(sem_mtx);
  6246. credits += qlimit + 1;
  6247. }
  6248. sem_cv.notify_all();
  6249. /* Wait for all the credits to be consumed. */
  6250. {
  6251. std::unique_lock<std::mutex> lock(sem_mtx);
  6252. while (credits > 0) {
  6253. sem_cv.wait(lock);
  6254. }
  6255. }
  6256. /* Check that we are able again to enqueue at least qlimit tasks. */
  6257. for (unsigned int i = 0; i < qlimit; i++) {
  6258. queued = task_queue->enqueue([] {});
  6259. EXPECT_TRUE(queued);
  6260. }
  6261. EXPECT_NO_THROW(task_queue->shutdown());
  6262. }
  6263. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6264. Server svr;
  6265. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6266. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6267. });
  6268. svr.Get("/hello", [](const Request &req, Response &res) {
  6269. res.set_content(req.get_param_value("key"), "text/plain");
  6270. });
  6271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6272. auto se = detail::scope_exit([&] {
  6273. svr.stop();
  6274. thread.join();
  6275. ASSERT_FALSE(svr.is_running());
  6276. });
  6277. svr.wait_until_ready();
  6278. {
  6279. Client cli(HOST, PORT);
  6280. cli.set_follow_location(true);
  6281. auto res = cli.Get("/");
  6282. ASSERT_TRUE(res);
  6283. EXPECT_EQ(StatusCode::OK_200, res->status);
  6284. EXPECT_EQ("val&key2=val2", res->body);
  6285. }
  6286. }
  6287. TEST(VulnerabilityTest, CRLFInjection) {
  6288. Server svr;
  6289. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6290. res.set_content("Hello 1", "text/plain");
  6291. });
  6292. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6293. res.set_content("Hello 2", "text/plain");
  6294. });
  6295. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6296. res.set_content("Hello 3", "text/plain");
  6297. });
  6298. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6299. res.set_content("Hello 4", "text/plain");
  6300. });
  6301. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6302. for (const auto &x : req.headers) {
  6303. auto key = x.first;
  6304. EXPECT_STRNE("evil", key.c_str());
  6305. }
  6306. });
  6307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6308. auto se = detail::scope_exit([&] {
  6309. svr.stop();
  6310. thread.join();
  6311. ASSERT_FALSE(svr.is_running());
  6312. });
  6313. svr.wait_until_ready();
  6314. {
  6315. Client cli(HOST, PORT);
  6316. cli.Post("/test1", "A=B",
  6317. "application/x-www-form-urlencoded\r\nevil: hello1");
  6318. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6319. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6320. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6321. }
  6322. }
  6323. TEST(PathParamsTest, StaticMatch) {
  6324. const auto pattern = "/users/all";
  6325. detail::PathParamsMatcher matcher(pattern);
  6326. Request request;
  6327. request.path = "/users/all";
  6328. ASSERT_TRUE(matcher.match(request));
  6329. std::unordered_map<std::string, std::string> expected_params = {};
  6330. EXPECT_EQ(request.path_params, expected_params);
  6331. }
  6332. TEST(PathParamsTest, StaticMismatch) {
  6333. const auto pattern = "/users/all";
  6334. detail::PathParamsMatcher matcher(pattern);
  6335. Request request;
  6336. request.path = "/users/1";
  6337. ASSERT_FALSE(matcher.match(request));
  6338. }
  6339. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6340. const auto pattern = "/users/:id/subscriptions";
  6341. detail::PathParamsMatcher matcher(pattern);
  6342. Request request;
  6343. request.path = "/users/42/subscriptions";
  6344. ASSERT_TRUE(matcher.match(request));
  6345. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6346. EXPECT_EQ(request.path_params, expected_params);
  6347. }
  6348. TEST(PathParamsTest, SingleParamInTheEnd) {
  6349. const auto pattern = "/users/:id";
  6350. detail::PathParamsMatcher matcher(pattern);
  6351. Request request;
  6352. request.path = "/users/24";
  6353. ASSERT_TRUE(matcher.match(request));
  6354. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6355. EXPECT_EQ(request.path_params, expected_params);
  6356. }
  6357. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6358. const auto pattern = "/users/:id/";
  6359. detail::PathParamsMatcher matcher(pattern);
  6360. Request request;
  6361. request.path = "/users/42/";
  6362. ASSERT_TRUE(matcher.match(request));
  6363. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6364. EXPECT_EQ(request.path_params, expected_params);
  6365. }
  6366. TEST(PathParamsTest, EmptyParam) {
  6367. const auto pattern = "/users/:id/";
  6368. detail::PathParamsMatcher matcher(pattern);
  6369. Request request;
  6370. request.path = "/users//";
  6371. ASSERT_TRUE(matcher.match(request));
  6372. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6373. EXPECT_EQ(request.path_params, expected_params);
  6374. }
  6375. TEST(PathParamsTest, FragmentMismatch) {
  6376. const auto pattern = "/users/:id/";
  6377. detail::PathParamsMatcher matcher(pattern);
  6378. Request request;
  6379. request.path = "/admins/24/";
  6380. ASSERT_FALSE(matcher.match(request));
  6381. }
  6382. TEST(PathParamsTest, ExtraFragments) {
  6383. const auto pattern = "/users/:id";
  6384. detail::PathParamsMatcher matcher(pattern);
  6385. Request request;
  6386. request.path = "/users/42/subscriptions";
  6387. ASSERT_FALSE(matcher.match(request));
  6388. }
  6389. TEST(PathParamsTest, MissingTrailingParam) {
  6390. const auto pattern = "/users/:id";
  6391. detail::PathParamsMatcher matcher(pattern);
  6392. Request request;
  6393. request.path = "/users";
  6394. ASSERT_FALSE(matcher.match(request));
  6395. }
  6396. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6397. const auto pattern = "/users/:id/subscriptions";
  6398. detail::PathParamsMatcher matcher(pattern);
  6399. Request request;
  6400. request.path = "/users/subscriptions";
  6401. ASSERT_FALSE(matcher.match(request));
  6402. }
  6403. TEST(PathParamsTest, MultipleParams) {
  6404. const auto pattern = "/users/:userid/subscriptions/:subid";
  6405. detail::PathParamsMatcher matcher(pattern);
  6406. Request request;
  6407. request.path = "/users/42/subscriptions/2";
  6408. ASSERT_TRUE(matcher.match(request));
  6409. std::unordered_map<std::string, std::string> expected_params = {
  6410. {"userid", "42"}, {"subid", "2"}};
  6411. EXPECT_EQ(request.path_params, expected_params);
  6412. }
  6413. TEST(PathParamsTest, SequenceOfParams) {
  6414. const auto pattern = "/values/:x/:y/:z";
  6415. detail::PathParamsMatcher matcher(pattern);
  6416. Request request;
  6417. request.path = "/values/1/2/3";
  6418. ASSERT_TRUE(matcher.match(request));
  6419. std::unordered_map<std::string, std::string> expected_params = {
  6420. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6421. EXPECT_EQ(request.path_params, expected_params);
  6422. }
  6423. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6424. const auto pattern = "/prefix:suffix";
  6425. detail::PathParamsMatcher matcher(pattern);
  6426. Request request;
  6427. request.path = "/prefix:suffix";
  6428. ASSERT_TRUE(matcher.match(request));
  6429. const std::unordered_map<std::string, std::string> expected_params = {};
  6430. EXPECT_EQ(request.path_params, expected_params);
  6431. }
  6432. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6433. // If ipv6 regex working, regex match codepath is taken.
  6434. // else port will default to 80 in Client impl
  6435. int clientImplMagicPort = 80;
  6436. int port = 4321;
  6437. // above ports must be different to avoid false negative
  6438. EXPECT_NE(clientImplMagicPort, port);
  6439. std::string ipV6TestURL = "http://[ff06::c3]";
  6440. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6441. CLIENT_PRIVATE_KEY_FILE);
  6442. EXPECT_EQ(cli.port(), port);
  6443. }
  6444. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6445. auto file_path = "./www/dir/index.html";
  6446. auto dir_path = "./www/dir";
  6447. detail::FileStat stat_file(file_path);
  6448. EXPECT_TRUE(stat_file.is_file());
  6449. EXPECT_FALSE(stat_file.is_dir());
  6450. detail::FileStat stat_dir(dir_path);
  6451. EXPECT_FALSE(stat_dir.is_file());
  6452. EXPECT_TRUE(stat_dir.is_dir());
  6453. }
  6454. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6455. Server svr;
  6456. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6457. EXPECT_EQ(res.status, 400);
  6458. });
  6459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6460. auto se = detail::scope_exit([&] {
  6461. svr.stop();
  6462. thread.join();
  6463. ASSERT_FALSE(svr.is_running());
  6464. });
  6465. svr.wait_until_ready();
  6466. Client cli(HOST, PORT);
  6467. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6468. }
  6469. #ifndef _WIN32
  6470. TEST(Expect100ContinueTest, ServerClosesConnection) {
  6471. static constexpr char reject[] = "Unauthorized";
  6472. static constexpr char accept[] = "Upload accepted";
  6473. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  6474. Server svr;
  6475. svr.set_expect_100_continue_handler(
  6476. [](const Request & /*req*/, Response &res) {
  6477. res.status = StatusCode::Unauthorized_401;
  6478. res.set_content(reject, "text/plain");
  6479. return res.status;
  6480. });
  6481. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  6482. res.set_content(accept, "text/plain");
  6483. });
  6484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6485. auto se = detail::scope_exit([&] {
  6486. svr.stop();
  6487. thread.join();
  6488. ASSERT_FALSE(svr.is_running());
  6489. });
  6490. svr.wait_until_ready();
  6491. {
  6492. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  6493. curl_easy_init(), &curl_easy_cleanup};
  6494. ASSERT_NE(curl, nullptr);
  6495. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  6496. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  6497. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  6498. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  6499. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  6500. &curl_slist_free_all};
  6501. ASSERT_NE(list, nullptr);
  6502. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  6503. struct read_data {
  6504. size_t read_size;
  6505. size_t total_size;
  6506. } data = {0, total_size};
  6507. using read_callback_t =
  6508. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6509. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  6510. void *userdata) -> size_t {
  6511. read_data *data = (read_data *)userdata;
  6512. if (!userdata || data->read_size >= data->total_size) { return 0; }
  6513. std::fill_n(ptr, size * nmemb, 'A');
  6514. data->read_size += size * nmemb;
  6515. return size * nmemb;
  6516. };
  6517. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  6518. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  6519. std::vector<char> buffer;
  6520. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  6521. using write_callback_t =
  6522. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6523. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  6524. void *userdata) -> size_t {
  6525. std::vector<char> *buffer = (std::vector<char> *)userdata;
  6526. buffer->reserve(buffer->size() + size * nmemb + 1);
  6527. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  6528. return size * nmemb;
  6529. };
  6530. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  6531. {
  6532. const auto res = curl_easy_perform(curl.get());
  6533. ASSERT_EQ(res, CURLE_OK);
  6534. }
  6535. {
  6536. auto response_code = long{};
  6537. const auto res =
  6538. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  6539. ASSERT_EQ(res, CURLE_OK);
  6540. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  6541. }
  6542. {
  6543. auto dl = curl_off_t{};
  6544. const auto res =
  6545. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  6546. ASSERT_EQ(res, CURLE_OK);
  6547. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  6548. }
  6549. {
  6550. buffer.push_back('\0');
  6551. ASSERT_STRCASEEQ(buffer.data(), reject);
  6552. }
  6553. }
  6554. }
  6555. #endif