test.cc 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863
  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(ServerRequestParsingTest, EmptyFieldValue) {
  4188. std::string out;
  4189. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  4190. "Test: \r\n\r\n",
  4191. &out);
  4192. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  4193. }
  4194. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4195. Server svr;
  4196. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4197. res.set_header("Cache-Control", "no-cache");
  4198. res.set_chunked_content_provider(
  4199. "text/event-stream", [](size_t offset, DataSink &sink) {
  4200. std::string s = "data:";
  4201. s += std::to_string(offset);
  4202. s += "\n\n";
  4203. auto ret = sink.write(s.data(), s.size());
  4204. EXPECT_TRUE(ret);
  4205. std::this_thread::sleep_for(std::chrono::seconds(1));
  4206. return true;
  4207. });
  4208. });
  4209. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4210. svr.wait_until_ready();
  4211. Client client(HOST, PORT);
  4212. const Headers headers = {{"Accept", "text/event-stream"}};
  4213. auto get_thread = std::thread([&client, &headers]() {
  4214. auto res = client.Get(
  4215. "/events", headers,
  4216. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4217. });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. get_thread.join();
  4221. listen_thread.join();
  4222. ASSERT_FALSE(svr.is_running());
  4223. });
  4224. // Give GET time to get a few messages.
  4225. std::this_thread::sleep_for(std::chrono::seconds(2));
  4226. }
  4227. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4228. httplib::Server svr;
  4229. svr.Post("/hi",
  4230. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4231. res.status = StatusCode::OK_200;
  4232. });
  4233. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4234. svr.wait_until_ready();
  4235. Client cli(HOST, PORT);
  4236. auto res = cli.Post("/hi", "data", "text/plain");
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(StatusCode::OK_200, res->status);
  4239. svr.stop();
  4240. thread.join();
  4241. ASSERT_FALSE(svr.is_running());
  4242. res = cli.Post("/hi", "data", "text/plain");
  4243. ASSERT_FALSE(res);
  4244. }
  4245. TEST(ServerStopTest, ListenFailure) {
  4246. Server svr;
  4247. auto t = thread([&]() {
  4248. auto ret = svr.listen("????", PORT);
  4249. EXPECT_FALSE(ret);
  4250. });
  4251. svr.wait_until_ready();
  4252. svr.stop();
  4253. t.join();
  4254. }
  4255. TEST(ServerStopTest, Decommision) {
  4256. Server svr;
  4257. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4258. for (int i = 0; i < 4; i++) {
  4259. auto is_even = !(i % 2);
  4260. std::thread t{[&] {
  4261. try {
  4262. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4263. if (is_even) {
  4264. throw std::runtime_error("Some thing that happens to go wrong.");
  4265. }
  4266. svr.listen(HOST, PORT);
  4267. } catch (...) { svr.decommission(); }
  4268. }};
  4269. svr.wait_until_ready();
  4270. // Server is up
  4271. {
  4272. Client cli(HOST, PORT);
  4273. auto res = cli.Get("/hi");
  4274. if (is_even) {
  4275. EXPECT_FALSE(res);
  4276. } else {
  4277. EXPECT_TRUE(res);
  4278. EXPECT_EQ("hi...", res->body);
  4279. }
  4280. }
  4281. svr.stop();
  4282. t.join();
  4283. // Server is down...
  4284. {
  4285. Client cli(HOST, PORT);
  4286. auto res = cli.Get("/hi");
  4287. EXPECT_FALSE(res);
  4288. }
  4289. }
  4290. }
  4291. TEST(StreamingTest, NoContentLengthStreaming) {
  4292. Server svr;
  4293. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4294. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4295. if (offset < 6) {
  4296. sink.os << (offset < 3 ? "a" : "b");
  4297. } else {
  4298. sink.done();
  4299. }
  4300. return true;
  4301. });
  4302. });
  4303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4304. auto listen_se = detail::scope_exit([&] {
  4305. svr.stop();
  4306. listen_thread.join();
  4307. ASSERT_FALSE(svr.is_running());
  4308. });
  4309. svr.wait_until_ready();
  4310. Client client(HOST, PORT);
  4311. auto get_thread = std::thread([&client]() {
  4312. std::string s;
  4313. auto res =
  4314. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4315. s += std::string(data, len);
  4316. return true;
  4317. });
  4318. EXPECT_EQ("aaabbb", s);
  4319. });
  4320. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4321. // Give GET time to get a few messages.
  4322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4323. }
  4324. TEST(MountTest, Unmount) {
  4325. Server svr;
  4326. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4327. auto se = detail::scope_exit([&] {
  4328. svr.stop();
  4329. listen_thread.join();
  4330. ASSERT_FALSE(svr.is_running());
  4331. });
  4332. svr.wait_until_ready();
  4333. Client cli("localhost", PORT);
  4334. svr.set_mount_point("/mount2", "./www2");
  4335. auto res = cli.Get("/");
  4336. ASSERT_TRUE(res);
  4337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4338. res = cli.Get("/mount2/dir/test.html");
  4339. ASSERT_TRUE(res);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. svr.set_mount_point("/", "./www");
  4342. res = cli.Get("/dir/");
  4343. ASSERT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. svr.remove_mount_point("/");
  4346. res = cli.Get("/dir/");
  4347. ASSERT_TRUE(res);
  4348. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4349. svr.remove_mount_point("/mount2");
  4350. res = cli.Get("/mount2/dir/test.html");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4353. }
  4354. TEST(MountTest, Redicect) {
  4355. Server svr;
  4356. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4357. auto se = detail::scope_exit([&] {
  4358. svr.stop();
  4359. listen_thread.join();
  4360. ASSERT_FALSE(svr.is_running());
  4361. });
  4362. svr.set_mount_point("/", "./www");
  4363. svr.wait_until_ready();
  4364. Client cli("localhost", PORT);
  4365. auto res = cli.Get("/dir/");
  4366. ASSERT_TRUE(res);
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. res = cli.Get("/dir");
  4369. ASSERT_TRUE(res);
  4370. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4371. res = cli.Get("/file");
  4372. ASSERT_TRUE(res);
  4373. EXPECT_EQ(StatusCode::OK_200, res->status);
  4374. res = cli.Get("/file/");
  4375. ASSERT_TRUE(res);
  4376. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4377. cli.set_follow_location(true);
  4378. res = cli.Get("/dir");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4383. TEST(ExceptionTest, ThrowExceptionInHandler) {
  4384. Server svr;
  4385. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4386. throw std::runtime_error("exception...");
  4387. });
  4388. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4389. throw std::runtime_error("exception\r\n...");
  4390. });
  4391. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4392. auto se = detail::scope_exit([&] {
  4393. svr.stop();
  4394. listen_thread.join();
  4395. ASSERT_FALSE(svr.is_running());
  4396. });
  4397. svr.wait_until_ready();
  4398. Client cli("localhost", PORT);
  4399. {
  4400. auto res = cli.Get("/exception");
  4401. ASSERT_TRUE(res);
  4402. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4403. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4404. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  4405. }
  4406. {
  4407. auto res = cli.Get("/unknown");
  4408. ASSERT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4410. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4411. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  4412. }
  4413. }
  4414. #endif
  4415. TEST(KeepAliveTest, ReadTimeout) {
  4416. Server svr;
  4417. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4418. std::this_thread::sleep_for(std::chrono::seconds(2));
  4419. res.set_content("a", "text/plain");
  4420. });
  4421. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4422. res.set_content("b", "text/plain");
  4423. });
  4424. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4425. auto se = detail::scope_exit([&] {
  4426. svr.stop();
  4427. listen_thread.join();
  4428. ASSERT_FALSE(svr.is_running());
  4429. });
  4430. svr.wait_until_ready();
  4431. Client cli("localhost", PORT);
  4432. cli.set_keep_alive(true);
  4433. cli.set_read_timeout(std::chrono::seconds(1));
  4434. auto resa = cli.Get("/a");
  4435. ASSERT_FALSE(resa);
  4436. EXPECT_EQ(Error::Read, resa.error());
  4437. auto resb = cli.Get("/b");
  4438. ASSERT_TRUE(resb);
  4439. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4440. EXPECT_EQ("b", resb->body);
  4441. }
  4442. TEST(KeepAliveTest, Issue1041) {
  4443. Server svr;
  4444. svr.set_keep_alive_timeout(3);
  4445. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4446. res.set_content("Hello World!", "text/plain");
  4447. });
  4448. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. listen_thread.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. Client cli(HOST, PORT);
  4456. cli.set_keep_alive(true);
  4457. auto result = cli.Get("/hi");
  4458. ASSERT_TRUE(result);
  4459. EXPECT_EQ(StatusCode::OK_200, result->status);
  4460. std::this_thread::sleep_for(std::chrono::seconds(5));
  4461. result = cli.Get("/hi");
  4462. ASSERT_TRUE(result);
  4463. EXPECT_EQ(StatusCode::OK_200, result->status);
  4464. }
  4465. TEST(KeepAliveTest, Issue1959) {
  4466. Server svr;
  4467. svr.set_keep_alive_timeout(5);
  4468. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4469. res.set_content("a", "text/plain");
  4470. });
  4471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4472. auto se = detail::scope_exit([&] {
  4473. if (!svr.is_running()) return;
  4474. svr.stop();
  4475. listen_thread.join();
  4476. ASSERT_FALSE(svr.is_running());
  4477. });
  4478. svr.wait_until_ready();
  4479. Client cli("localhost", PORT);
  4480. cli.set_keep_alive(true);
  4481. using namespace std::chrono;
  4482. auto start = steady_clock::now();
  4483. cli.Get("/a");
  4484. svr.stop();
  4485. listen_thread.join();
  4486. auto end = steady_clock::now();
  4487. auto elapsed = duration_cast<milliseconds>(end - start).count();
  4488. EXPECT_LT(elapsed, 5000);
  4489. }
  4490. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4491. TEST(KeepAliveTest, SSLClientReconnection) {
  4492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4493. ASSERT_TRUE(svr.is_valid());
  4494. svr.set_keep_alive_timeout(1);
  4495. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4496. res.set_content("Hello World!", "text/plain");
  4497. });
  4498. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. listen_thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. SSLClient cli(HOST, PORT);
  4506. cli.enable_server_certificate_verification(false);
  4507. cli.set_keep_alive(true);
  4508. auto result = cli.Get("/hi");
  4509. ASSERT_TRUE(result);
  4510. EXPECT_EQ(StatusCode::OK_200, result->status);
  4511. result = cli.Get("/hi");
  4512. ASSERT_TRUE(result);
  4513. EXPECT_EQ(StatusCode::OK_200, result->status);
  4514. std::this_thread::sleep_for(std::chrono::seconds(2));
  4515. // Recoonect
  4516. result = cli.Get("/hi");
  4517. ASSERT_TRUE(result);
  4518. EXPECT_EQ(StatusCode::OK_200, result->status);
  4519. result = cli.Get("/hi");
  4520. ASSERT_TRUE(result);
  4521. EXPECT_EQ(StatusCode::OK_200, result->status);
  4522. }
  4523. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4525. ASSERT_TRUE(svr.is_valid());
  4526. svr.set_keep_alive_timeout(1);
  4527. std::string content = "reconnect";
  4528. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4529. res.set_content("Hello World!", "text/plain");
  4530. });
  4531. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4532. auto se = detail::scope_exit([&] {
  4533. svr.stop();
  4534. listen_thread.join();
  4535. ASSERT_FALSE(svr.is_running());
  4536. });
  4537. svr.wait_until_ready();
  4538. SSLClient cli(HOST, PORT);
  4539. cli.enable_server_certificate_verification(false);
  4540. cli.set_keep_alive(true);
  4541. auto result = cli.Post(
  4542. "/hi", content.size(),
  4543. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4544. sink.write(content.c_str(), content.size());
  4545. return true;
  4546. },
  4547. "text/plain");
  4548. ASSERT_TRUE(result);
  4549. EXPECT_EQ(200, result->status);
  4550. std::this_thread::sleep_for(std::chrono::seconds(2));
  4551. // Recoonect
  4552. result = cli.Post(
  4553. "/hi", content.size(),
  4554. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4555. sink.write(content.c_str(), content.size());
  4556. return true;
  4557. },
  4558. "text/plain");
  4559. ASSERT_TRUE(result);
  4560. EXPECT_EQ(200, result->status);
  4561. result = cli.Post(
  4562. "/hi", content.size(),
  4563. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4564. sink.write(content.c_str(), content.size());
  4565. return true;
  4566. },
  4567. "text/plain");
  4568. ASSERT_TRUE(result);
  4569. EXPECT_EQ(200, result->status);
  4570. }
  4571. #endif
  4572. TEST(ClientProblemDetectionTest, ContentProvider) {
  4573. Server svr;
  4574. size_t content_length = 1024 * 1024;
  4575. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4576. res.set_content_provider(
  4577. content_length, "text/plain",
  4578. [&](size_t offset, size_t length, DataSink &sink) {
  4579. auto out_len = std::min(length, static_cast<size_t>(1024));
  4580. std::string out(out_len, '@');
  4581. sink.write(out.data(), out_len);
  4582. return offset < 4096;
  4583. },
  4584. [](bool success) { ASSERT_FALSE(success); });
  4585. });
  4586. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4587. res.set_content_provider(
  4588. 0, "text/plain",
  4589. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4590. EXPECT_TRUE(false);
  4591. return true;
  4592. },
  4593. [](bool success) { ASSERT_FALSE(success); });
  4594. });
  4595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4596. auto se = detail::scope_exit([&] {
  4597. svr.stop();
  4598. listen_thread.join();
  4599. ASSERT_FALSE(svr.is_running());
  4600. });
  4601. svr.wait_until_ready();
  4602. Client cli("localhost", PORT);
  4603. {
  4604. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4605. size_t /*data_length*/) { return false; });
  4606. ASSERT_FALSE(res);
  4607. }
  4608. {
  4609. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4610. size_t /*data_length*/) { return false; });
  4611. ASSERT_TRUE(res);
  4612. }
  4613. }
  4614. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4615. Server svr;
  4616. svr.set_error_handler([](Request const &, Response &res) -> void {
  4617. res.set_chunked_content_provider(
  4618. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4619. sink.os << "hello";
  4620. sink.os << "world";
  4621. sink.done();
  4622. return true;
  4623. });
  4624. });
  4625. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4626. auto se = detail::scope_exit([&] {
  4627. svr.stop();
  4628. listen_thread.join();
  4629. ASSERT_FALSE(svr.is_running());
  4630. });
  4631. svr.wait_until_ready();
  4632. Client cli("localhost", PORT);
  4633. auto res = cli.Get("/");
  4634. ASSERT_TRUE(res);
  4635. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4636. EXPECT_EQ("helloworld", res->body);
  4637. }
  4638. TEST(LongPollingTest, ClientCloseDetection) {
  4639. Server svr;
  4640. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4641. res.set_chunked_content_provider(
  4642. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4643. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4644. sink.os << "hello";
  4645. auto count = 10;
  4646. while (count > 0 && sink.is_writable()) {
  4647. this_thread::sleep_for(chrono::milliseconds(10));
  4648. }
  4649. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4650. return true;
  4651. });
  4652. });
  4653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4654. auto se = detail::scope_exit([&] {
  4655. svr.stop();
  4656. listen_thread.join();
  4657. ASSERT_FALSE(svr.is_running());
  4658. });
  4659. svr.wait_until_ready();
  4660. Client cli("localhost", PORT);
  4661. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4662. EXPECT_EQ("hello", string(data, data_length));
  4663. return false; // close the socket immediately.
  4664. });
  4665. ASSERT_FALSE(res);
  4666. }
  4667. TEST(GetWithParametersTest, GetWithParameters) {
  4668. Server svr;
  4669. svr.Get("/", [&](const Request &req, Response &) {
  4670. EXPECT_EQ("world", req.get_param_value("hello"));
  4671. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4672. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4673. });
  4674. svr.Get("/params", [&](const Request &req, Response &) {
  4675. EXPECT_EQ("world", req.get_param_value("hello"));
  4676. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4677. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4678. });
  4679. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4680. EXPECT_EQ("resource-id", req.matches[1]);
  4681. EXPECT_EQ("foo", req.get_param_value("param1"));
  4682. EXPECT_EQ("bar", req.get_param_value("param2"));
  4683. });
  4684. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4685. EXPECT_EQ("user-id", req.path_params.at("id"));
  4686. EXPECT_EQ("foo", req.get_param_value("param1"));
  4687. EXPECT_EQ("bar", req.get_param_value("param2"));
  4688. });
  4689. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. listen_thread.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. {
  4697. Client cli(HOST, PORT);
  4698. Params params;
  4699. params.emplace("hello", "world");
  4700. params.emplace("hello2", "world2");
  4701. params.emplace("hello3", "world3");
  4702. auto res = cli.Get("/", params, Headers{});
  4703. ASSERT_TRUE(res);
  4704. EXPECT_EQ(StatusCode::OK_200, res->status);
  4705. }
  4706. {
  4707. Client cli(HOST, PORT);
  4708. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4709. ASSERT_TRUE(res);
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. }
  4712. {
  4713. Client cli(HOST, PORT);
  4714. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4715. ASSERT_TRUE(res);
  4716. EXPECT_EQ(StatusCode::OK_200, res->status);
  4717. }
  4718. {
  4719. Client cli(HOST, PORT);
  4720. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4721. ASSERT_TRUE(res);
  4722. EXPECT_EQ(StatusCode::OK_200, res->status);
  4723. }
  4724. }
  4725. TEST(GetWithParametersTest, GetWithParameters2) {
  4726. Server svr;
  4727. svr.Get("/", [&](const Request &req, Response &res) {
  4728. auto text = req.get_param_value("hello");
  4729. res.set_content(text, "text/plain");
  4730. });
  4731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4732. auto se = detail::scope_exit([&] {
  4733. svr.stop();
  4734. listen_thread.join();
  4735. ASSERT_FALSE(svr.is_running());
  4736. });
  4737. svr.wait_until_ready();
  4738. Client cli("localhost", PORT);
  4739. Params params;
  4740. params.emplace("hello", "world");
  4741. std::string body;
  4742. auto res = cli.Get("/", params, Headers{},
  4743. [&](const char *data, size_t data_length) {
  4744. body.append(data, data_length);
  4745. return true;
  4746. });
  4747. ASSERT_TRUE(res);
  4748. EXPECT_EQ(StatusCode::OK_200, res->status);
  4749. EXPECT_EQ("world", body);
  4750. }
  4751. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4752. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4753. auto host = "httpbin.org";
  4754. auto path = std::string{"/range/32"};
  4755. #else
  4756. auto host = "nghttp2.org";
  4757. auto path = std::string{"/httpbin/range/32"};
  4758. #endif
  4759. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4760. SSLClient cli(host);
  4761. #else
  4762. Client cli(host);
  4763. #endif
  4764. cli.set_default_headers({make_range_header({{1, 10}})});
  4765. cli.set_connection_timeout(5);
  4766. {
  4767. auto res = cli.Get(path);
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ("bcdefghijk", res->body);
  4770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4771. }
  4772. {
  4773. auto res = cli.Get(path);
  4774. ASSERT_TRUE(res);
  4775. EXPECT_EQ("bcdefghijk", res->body);
  4776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4777. }
  4778. }
  4779. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4780. Server svr;
  4781. svr.set_default_headers({{"Hello", "World"}});
  4782. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4783. res.set_content("ok", "text/plain");
  4784. });
  4785. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4786. auto se = detail::scope_exit([&] {
  4787. svr.stop();
  4788. listen_thread.join();
  4789. ASSERT_FALSE(svr.is_running());
  4790. });
  4791. svr.wait_until_ready();
  4792. Client cli("localhost", PORT);
  4793. auto res = cli.Get("/");
  4794. ASSERT_TRUE(res);
  4795. EXPECT_EQ(StatusCode::OK_200, res->status);
  4796. EXPECT_EQ("ok", res->body);
  4797. EXPECT_EQ("World", res->get_header_value("Hello"));
  4798. }
  4799. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4800. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4802. ASSERT_TRUE(svr.is_valid());
  4803. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4804. std::this_thread::sleep_for(std::chrono::seconds(2));
  4805. res.set_content("a", "text/plain");
  4806. });
  4807. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4808. res.set_content("b", "text/plain");
  4809. });
  4810. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4811. auto se = detail::scope_exit([&] {
  4812. svr.stop();
  4813. listen_thread.join();
  4814. ASSERT_FALSE(svr.is_running());
  4815. });
  4816. svr.wait_until_ready();
  4817. SSLClient cli("localhost", PORT);
  4818. cli.enable_server_certificate_verification(false);
  4819. cli.set_keep_alive(true);
  4820. cli.set_read_timeout(std::chrono::seconds(1));
  4821. auto resa = cli.Get("/a");
  4822. ASSERT_TRUE(!resa);
  4823. EXPECT_EQ(Error::Read, resa.error());
  4824. auto resb = cli.Get("/b");
  4825. ASSERT_TRUE(resb);
  4826. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4827. EXPECT_EQ("b", resb->body);
  4828. }
  4829. #endif
  4830. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4831. protected:
  4832. ServerTestWithAI_PASSIVE()
  4833. : cli_(HOST, PORT)
  4834. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4835. ,
  4836. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4837. #endif
  4838. {
  4839. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4840. cli_.enable_server_certificate_verification(false);
  4841. #endif
  4842. }
  4843. virtual void SetUp() {
  4844. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4845. res.set_content("Hello World!", "text/plain");
  4846. });
  4847. t_ = thread(
  4848. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4849. svr_.wait_until_ready();
  4850. }
  4851. virtual void TearDown() {
  4852. svr_.stop();
  4853. t_.join();
  4854. }
  4855. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4856. SSLClient cli_;
  4857. SSLServer svr_;
  4858. #else
  4859. Client cli_;
  4860. Server svr_;
  4861. #endif
  4862. thread t_;
  4863. };
  4864. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4865. auto res = cli_.Get("/hi");
  4866. ASSERT_TRUE(res);
  4867. EXPECT_EQ(StatusCode::OK_200, res->status);
  4868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4869. EXPECT_EQ("Hello World!", res->body);
  4870. }
  4871. class ServerUpDownTest : public ::testing::Test {
  4872. protected:
  4873. ServerUpDownTest() : cli_(HOST, PORT) {}
  4874. virtual void SetUp() {
  4875. t_ = thread([&]() {
  4876. svr_.bind_to_any_port(HOST);
  4877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4878. ASSERT_TRUE(svr_.listen_after_bind());
  4879. });
  4880. svr_.wait_until_ready();
  4881. }
  4882. virtual void TearDown() {
  4883. svr_.stop();
  4884. t_.join();
  4885. }
  4886. Client cli_;
  4887. Server svr_;
  4888. thread t_;
  4889. };
  4890. TEST_F(ServerUpDownTest, QuickStartStop) {
  4891. // Should not crash, especially when run with
  4892. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4893. }
  4894. class PayloadMaxLengthTest : public ::testing::Test {
  4895. protected:
  4896. PayloadMaxLengthTest()
  4897. : cli_(HOST, PORT)
  4898. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4899. ,
  4900. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4901. #endif
  4902. {
  4903. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4904. cli_.enable_server_certificate_verification(false);
  4905. #endif
  4906. }
  4907. virtual void SetUp() {
  4908. svr_.set_payload_max_length(8);
  4909. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4910. res.set_content("test", "text/plain");
  4911. });
  4912. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4913. svr_.wait_until_ready();
  4914. }
  4915. virtual void TearDown() {
  4916. svr_.stop();
  4917. t_.join();
  4918. }
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. SSLClient cli_;
  4921. SSLServer svr_;
  4922. #else
  4923. Client cli_;
  4924. Server svr_;
  4925. #endif
  4926. thread t_;
  4927. };
  4928. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4929. auto res = cli_.Post("/test", "123456789", "text/plain");
  4930. ASSERT_TRUE(res);
  4931. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4932. res = cli_.Post("/test", "12345678", "text/plain");
  4933. ASSERT_TRUE(res);
  4934. EXPECT_EQ(StatusCode::OK_200, res->status);
  4935. }
  4936. TEST(HostAndPortPropertiesTest, NoSSL) {
  4937. httplib::Client cli("www.google.com", 1234);
  4938. ASSERT_EQ("www.google.com", cli.host());
  4939. ASSERT_EQ(1234, cli.port());
  4940. }
  4941. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4942. httplib::Client cli("www.google.com:1234");
  4943. ASSERT_EQ("www.google.com", cli.host());
  4944. ASSERT_EQ(1234, cli.port());
  4945. }
  4946. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4947. TEST(HostAndPortPropertiesTest, SSL) {
  4948. httplib::SSLClient cli("www.google.com");
  4949. ASSERT_EQ("www.google.com", cli.host());
  4950. ASSERT_EQ(443, cli.port());
  4951. }
  4952. #endif
  4953. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4954. TEST(SSLClientTest, UpdateCAStore) {
  4955. httplib::SSLClient httplib_client("www.google.com");
  4956. auto ca_store_1 = X509_STORE_new();
  4957. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4958. nullptr);
  4959. httplib_client.set_ca_cert_store(ca_store_1);
  4960. auto ca_store_2 = X509_STORE_new();
  4961. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4962. nullptr);
  4963. httplib_client.set_ca_cert_store(ca_store_2);
  4964. }
  4965. TEST(SSLClientTest, ServerNameIndication_Online) {
  4966. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4967. auto host = "httpbin.org";
  4968. auto path = std::string{"/get"};
  4969. #else
  4970. auto host = "nghttp2.org";
  4971. auto path = std::string{"/httpbin/get"};
  4972. #endif
  4973. SSLClient cli(host, 443);
  4974. auto res = cli.Get(path);
  4975. ASSERT_TRUE(res);
  4976. ASSERT_EQ(StatusCode::OK_200, res->status);
  4977. }
  4978. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4979. Client cli("https://google.com");
  4980. auto res = cli.Get("/");
  4981. ASSERT_TRUE(res);
  4982. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4983. }
  4984. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4985. SSLClient cli("google.com");
  4986. cli.enable_server_certificate_verification(true);
  4987. cli.set_ca_cert_path("hello");
  4988. auto res = cli.Get("/");
  4989. ASSERT_TRUE(!res);
  4990. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4991. }
  4992. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4993. SSLClient cli("google.com");
  4994. cli.set_ca_cert_path(CA_CERT_FILE);
  4995. auto res = cli.Get("/");
  4996. ASSERT_TRUE(res);
  4997. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4998. }
  4999. TEST(SSLClientTest, ServerCertificateVerification4) {
  5000. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5001. ASSERT_TRUE(svr.is_valid());
  5002. svr.Get("/test", [&](const Request &, Response &res) {
  5003. res.set_content("test", "text/plain");
  5004. svr.stop();
  5005. ASSERT_TRUE(true);
  5006. });
  5007. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5008. auto se = detail::scope_exit([&] {
  5009. t.join();
  5010. ASSERT_FALSE(svr.is_running());
  5011. });
  5012. svr.wait_until_ready();
  5013. SSLClient cli("127.0.0.1", PORT);
  5014. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5015. cli.enable_server_certificate_verification(true);
  5016. cli.set_connection_timeout(30);
  5017. auto res = cli.Get("/test");
  5018. ASSERT_TRUE(res);
  5019. ASSERT_EQ(StatusCode::OK_200, res->status);
  5020. }
  5021. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  5022. std::string cert;
  5023. detail::read_file(CA_CERT_FILE, cert);
  5024. SSLClient cli("google.com");
  5025. cli.load_ca_cert_store(cert.data(), cert.size());
  5026. const auto res = cli.Get("/");
  5027. ASSERT_TRUE(res);
  5028. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5029. }
  5030. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  5031. // clang-format off
  5032. static constexpr char cert[] =
  5033. "GlobalSign Root CA\n"
  5034. "==================\n"
  5035. "-----BEGIN CERTIFICATE-----\n"
  5036. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  5037. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  5038. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  5039. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  5040. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  5041. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  5042. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  5043. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  5044. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  5045. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  5046. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  5047. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  5048. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5049. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5050. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5051. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5052. "-----END CERTIFICATE-----\n";
  5053. // clang-format on
  5054. SSLClient cli("google.com");
  5055. cli.load_ca_cert_store(cert, sizeof(cert));
  5056. const auto res = cli.Get("/");
  5057. ASSERT_TRUE(res);
  5058. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5059. }
  5060. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5061. SSLClient cli("www.youtube.com");
  5062. cli.set_ca_cert_path(CA_CERT_FILE);
  5063. cli.enable_server_certificate_verification(true);
  5064. cli.set_follow_location(true);
  5065. auto res = cli.Get("/");
  5066. ASSERT_TRUE(res);
  5067. ASSERT_EQ(StatusCode::OK_200, res->status);
  5068. }
  5069. #if 0
  5070. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5071. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5072. ASSERT_TRUE(cli != nullptr);
  5073. cli->set_address_family(AF_INET6);
  5074. cli->set_interface("en0");
  5075. auto res = cli->Get("/get");
  5076. ASSERT_TRUE(res);
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. #endif
  5080. void ClientCertPresent(
  5081. const std::string &client_cert_file,
  5082. const std::string &client_private_key_file,
  5083. const std::string &client_encrypted_private_key_pass = std::string()) {
  5084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5085. CLIENT_CA_CERT_DIR);
  5086. ASSERT_TRUE(svr.is_valid());
  5087. svr.Get("/test", [&](const Request &req, Response &res) {
  5088. res.set_content("test", "text/plain");
  5089. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5090. ASSERT_TRUE(peer_cert != nullptr);
  5091. auto subject_name = X509_get_subject_name(peer_cert);
  5092. ASSERT_TRUE(subject_name != nullptr);
  5093. std::string common_name;
  5094. {
  5095. char name[BUFSIZ];
  5096. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5097. name, sizeof(name));
  5098. common_name.assign(name, static_cast<size_t>(name_len));
  5099. }
  5100. EXPECT_EQ("Common Name", common_name);
  5101. X509_free(peer_cert);
  5102. });
  5103. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. t.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5111. client_encrypted_private_key_pass);
  5112. cli.enable_server_certificate_verification(false);
  5113. cli.set_connection_timeout(30);
  5114. auto res = cli.Get("/test");
  5115. ASSERT_TRUE(res);
  5116. ASSERT_EQ(StatusCode::OK_200, res->status);
  5117. }
  5118. TEST(SSLClientServerTest, ClientCertPresent) {
  5119. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5120. }
  5121. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5122. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5123. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5124. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5125. }
  5126. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5127. void MemoryClientCertPresent(
  5128. const std::string &client_cert_file,
  5129. const std::string &client_private_key_file,
  5130. const std::string &client_encrypted_private_key_pass = std::string()) {
  5131. auto f = fopen(SERVER_CERT_FILE, "r+");
  5132. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5133. fclose(f);
  5134. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5135. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5136. fclose(f);
  5137. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5138. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5139. auto client_ca_cert_store = X509_STORE_new();
  5140. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5141. X509_free(client_cert);
  5142. fclose(f);
  5143. f = fopen(client_cert_file.c_str(), "r+");
  5144. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5145. fclose(f);
  5146. f = fopen(client_private_key_file.c_str(), "r+");
  5147. auto client_private_key = PEM_read_PrivateKey(
  5148. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5149. fclose(f);
  5150. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5151. ASSERT_TRUE(svr.is_valid());
  5152. svr.Get("/test", [&](const Request &req, Response &res) {
  5153. res.set_content("test", "text/plain");
  5154. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5155. ASSERT_TRUE(peer_cert != nullptr);
  5156. auto subject_name = X509_get_subject_name(peer_cert);
  5157. ASSERT_TRUE(subject_name != nullptr);
  5158. std::string common_name;
  5159. {
  5160. char name[BUFSIZ];
  5161. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5162. name, sizeof(name));
  5163. common_name.assign(name, static_cast<size_t>(name_len));
  5164. }
  5165. EXPECT_EQ("Common Name", common_name);
  5166. X509_free(peer_cert);
  5167. });
  5168. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5169. auto se = detail::scope_exit([&] {
  5170. svr.stop();
  5171. t.join();
  5172. ASSERT_FALSE(svr.is_running());
  5173. });
  5174. svr.wait_until_ready();
  5175. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5176. client_encrypted_private_key_pass);
  5177. cli.enable_server_certificate_verification(false);
  5178. cli.set_connection_timeout(30);
  5179. auto res = cli.Get("/test");
  5180. ASSERT_TRUE(res);
  5181. ASSERT_EQ(StatusCode::OK_200, res->status);
  5182. X509_free(server_cert);
  5183. EVP_PKEY_free(server_private_key);
  5184. X509_free(client_cert);
  5185. EVP_PKEY_free(client_private_key);
  5186. }
  5187. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5188. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5189. }
  5190. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5191. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5192. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5193. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5194. }
  5195. #endif
  5196. TEST(SSLClientServerTest, ClientCertMissing) {
  5197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5198. CLIENT_CA_CERT_DIR);
  5199. ASSERT_TRUE(svr.is_valid());
  5200. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5201. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5202. auto se = detail::scope_exit([&] {
  5203. svr.stop();
  5204. t.join();
  5205. ASSERT_FALSE(svr.is_running());
  5206. });
  5207. svr.wait_until_ready();
  5208. SSLClient cli(HOST, PORT);
  5209. auto res = cli.Get("/test");
  5210. cli.set_connection_timeout(30);
  5211. ASSERT_TRUE(!res);
  5212. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5213. }
  5214. TEST(SSLClientServerTest, TrustDirOptional) {
  5215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5216. ASSERT_TRUE(svr.is_valid());
  5217. svr.Get("/test", [&](const Request &, Response &res) {
  5218. res.set_content("test", "text/plain");
  5219. });
  5220. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5221. auto se = detail::scope_exit([&] {
  5222. svr.stop();
  5223. t.join();
  5224. ASSERT_FALSE(svr.is_running());
  5225. });
  5226. svr.wait_until_ready();
  5227. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5228. cli.enable_server_certificate_verification(false);
  5229. cli.set_connection_timeout(30);
  5230. auto res = cli.Get("/test");
  5231. ASSERT_TRUE(res);
  5232. ASSERT_EQ(StatusCode::OK_200, res->status);
  5233. }
  5234. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5235. class NoListenSSLServer : public SSLServer {
  5236. public:
  5237. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5238. const char *client_ca_cert_file_path,
  5239. const char *client_ca_cert_dir_path = nullptr)
  5240. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5241. client_ca_cert_dir_path),
  5242. stop_(false) {}
  5243. std::atomic_bool stop_;
  5244. private:
  5245. bool process_and_close_socket(socket_t /*sock*/) override {
  5246. // Don't create SSL context
  5247. while (!stop_.load()) {
  5248. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5249. }
  5250. return true;
  5251. }
  5252. };
  5253. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5254. CLIENT_CA_CERT_FILE);
  5255. ASSERT_TRUE(svr.is_valid());
  5256. svr.Get("/test", [&](const Request &, Response &res) {
  5257. res.set_content("test", "text/plain");
  5258. });
  5259. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5260. auto se = detail::scope_exit([&] {
  5261. svr.stop_ = true;
  5262. svr.stop();
  5263. t.join();
  5264. ASSERT_FALSE(svr.is_running());
  5265. });
  5266. svr.wait_until_ready();
  5267. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5268. cli.enable_server_certificate_verification(false);
  5269. cli.set_connection_timeout(1);
  5270. auto res = cli.Get("/test");
  5271. ASSERT_TRUE(!res);
  5272. EXPECT_EQ(Error::SSLConnection, res.error());
  5273. }
  5274. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5275. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5276. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5277. SSL_CTX_set_options(&ssl_ctx,
  5278. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5279. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5280. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5281. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5282. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5283. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5284. "ECDHE-DSS-AES128-SHA256:"
  5285. "ECDHE-RSA-AES256-SHA256:"
  5286. "ECDHE-DSS-AES256-SHA256:";
  5287. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5288. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5289. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5290. SSL_FILETYPE_PEM) != 1) {
  5291. return false;
  5292. }
  5293. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5294. CLIENT_CA_CERT_DIR);
  5295. SSL_CTX_set_verify(
  5296. &ssl_ctx,
  5297. SSL_VERIFY_PEER |
  5298. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5299. nullptr);
  5300. return true;
  5301. };
  5302. SSLServer svr(setup_ssl_ctx_callback);
  5303. ASSERT_TRUE(svr.is_valid());
  5304. svr.Get("/test", [&](const Request &req, Response &res) {
  5305. res.set_content("test", "text/plain");
  5306. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5307. ASSERT_TRUE(peer_cert != nullptr);
  5308. auto subject_name = X509_get_subject_name(peer_cert);
  5309. ASSERT_TRUE(subject_name != nullptr);
  5310. std::string common_name;
  5311. {
  5312. char name[BUFSIZ];
  5313. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5314. name, sizeof(name));
  5315. common_name.assign(name, static_cast<size_t>(name_len));
  5316. }
  5317. EXPECT_EQ("Common Name", common_name);
  5318. X509_free(peer_cert);
  5319. });
  5320. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. t.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5328. cli.enable_server_certificate_verification(false);
  5329. cli.set_connection_timeout(30);
  5330. auto res = cli.Get("/test");
  5331. ASSERT_TRUE(res);
  5332. ASSERT_EQ(StatusCode::OK_200, res->status);
  5333. }
  5334. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5335. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5336. // prepare large data
  5337. std::random_device seed_gen;
  5338. std::mt19937 random(seed_gen());
  5339. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5340. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5341. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5342. // server
  5343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5344. ASSERT_TRUE(svr.is_valid());
  5345. svr.Post("/binary", [&](const Request &req, Response &res) {
  5346. EXPECT_EQ(large_size_byte, req.body.size());
  5347. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5348. res.set_content(req.body, "application/octet-stream");
  5349. });
  5350. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5351. auto se = detail::scope_exit([&] {
  5352. svr.stop();
  5353. listen_thread.join();
  5354. ASSERT_FALSE(svr.is_running());
  5355. });
  5356. svr.wait_until_ready();
  5357. // client POST
  5358. SSLClient cli("localhost", PORT);
  5359. cli.enable_server_certificate_verification(false);
  5360. cli.set_read_timeout(std::chrono::seconds(100));
  5361. cli.set_write_timeout(std::chrono::seconds(100));
  5362. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5363. large_size_byte, "application/octet-stream");
  5364. // compare
  5365. EXPECT_EQ(StatusCode::OK_200, res->status);
  5366. EXPECT_EQ(large_size_byte, res->body.size());
  5367. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5368. }
  5369. #endif
  5370. #ifdef _WIN32
  5371. TEST(CleanupTest, WSACleanup) {
  5372. int ret = WSACleanup();
  5373. ASSERT_EQ(0, ret);
  5374. }
  5375. #endif
  5376. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5377. TEST(NoSSLSupport, SimpleInterface) {
  5378. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5379. }
  5380. #endif
  5381. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5382. TEST(InvalidScheme, SimpleInterface) {
  5383. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5384. }
  5385. #endif
  5386. TEST(NoScheme, SimpleInterface) {
  5387. Client cli("yahoo.com:80");
  5388. ASSERT_TRUE(cli.is_valid());
  5389. }
  5390. TEST(SendAPI, SimpleInterface_Online) {
  5391. Client cli("http://yahoo.com");
  5392. Request req;
  5393. req.method = "GET";
  5394. req.path = "/";
  5395. auto res = cli.send(req);
  5396. ASSERT_TRUE(res);
  5397. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5398. }
  5399. TEST(ClientImplMethods, GetSocketTest) {
  5400. httplib::Server svr;
  5401. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5402. res.status = StatusCode::OK_200;
  5403. });
  5404. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5405. auto se = detail::scope_exit([&] {
  5406. svr.stop();
  5407. thread.join();
  5408. ASSERT_FALSE(svr.is_running());
  5409. });
  5410. svr.wait_until_ready();
  5411. {
  5412. httplib::Client cli("http://127.0.0.1:3333");
  5413. cli.set_keep_alive(true);
  5414. // Use the behavior of cpp-httplib of opening the connection
  5415. // only when the first request happens. If that changes,
  5416. // this test would be obsolete.
  5417. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5418. // This also implicitly tests the server. But other tests would fail much
  5419. // earlier than this one to be considered.
  5420. auto res = cli.Get("/");
  5421. ASSERT_TRUE(res);
  5422. EXPECT_EQ(StatusCode::OK_200, res->status);
  5423. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5424. }
  5425. }
  5426. // Disabled due to out-of-memory problem on GitHub Actions
  5427. #ifdef _WIN64
  5428. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5429. // allocate content size larger than 2GB in memory
  5430. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5431. char *content = (char *)malloc(content_size);
  5432. ASSERT_TRUE(content);
  5433. Server svr;
  5434. svr.Get("/foo",
  5435. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5436. res.set_content(content, content_size, "application/octet-stream");
  5437. });
  5438. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5439. auto se = detail::scope_exit([&] {
  5440. svr.stop();
  5441. listen_thread.join();
  5442. if (content) free(content);
  5443. ASSERT_FALSE(svr.is_running());
  5444. });
  5445. svr.wait_until_ready();
  5446. Client cli(HOST, PORT);
  5447. auto res = cli.Get("/foo");
  5448. ASSERT_TRUE(res);
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. EXPECT_EQ(content_size, res->body.length());
  5451. }
  5452. #endif
  5453. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5454. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5455. Client cli("http://yahoo.com");
  5456. auto res = cli.Get("/");
  5457. ASSERT_TRUE(res);
  5458. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5459. cli.set_follow_location(true);
  5460. res = cli.Get("/");
  5461. ASSERT_TRUE(res);
  5462. EXPECT_EQ(StatusCode::OK_200, res->status);
  5463. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5464. }
  5465. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5466. Client cli("https://yahoo.com");
  5467. auto res = cli.Get("/");
  5468. ASSERT_TRUE(res);
  5469. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5470. cli.set_follow_location(true);
  5471. res = cli.Get("/");
  5472. ASSERT_TRUE(res);
  5473. EXPECT_EQ(StatusCode::OK_200, res->status);
  5474. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5475. }
  5476. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5477. Client cli("https://yahoo.com");
  5478. auto res = cli.Get("/");
  5479. ASSERT_TRUE(res);
  5480. ASSERT_FALSE(!res);
  5481. ASSERT_TRUE(res);
  5482. ASSERT_FALSE(res == nullptr);
  5483. ASSERT_TRUE(res != nullptr);
  5484. EXPECT_EQ(Error::Success, res.error());
  5485. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5486. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5487. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5488. cli.set_follow_location(true);
  5489. res = cli.Get("/");
  5490. ASSERT_TRUE(res);
  5491. EXPECT_EQ(Error::Success, res.error());
  5492. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5493. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5496. }
  5497. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5498. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5499. Client cli("https://cdnjs.cloudflare.com");
  5500. auto res =
  5501. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5502. ASSERT_TRUE(res);
  5503. EXPECT_EQ(StatusCode::OK_200, res->status);
  5504. EXPECT_EQ(287630U, res->body.size());
  5505. EXPECT_EQ("application/javascript; charset=utf-8",
  5506. res->get_header_value("Content-Type"));
  5507. }
  5508. #endif
  5509. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5510. Client cli("https://nghttp2.org");
  5511. cli.set_follow_location(true);
  5512. auto res =
  5513. cli.Get("/httpbin/"
  5514. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5515. ASSERT_TRUE(res);
  5516. EXPECT_EQ(StatusCode::OK_200, res->status);
  5517. }
  5518. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5519. Client cli("https://nghttp2.org");
  5520. cli.set_follow_location(true);
  5521. Params params;
  5522. params.emplace("url", "http://www.google.com");
  5523. params.emplace("status_code", "302");
  5524. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5525. ASSERT_TRUE(res);
  5526. EXPECT_EQ(StatusCode::OK_200, res->status);
  5527. }
  5528. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5529. Client cli("https://nghttp2.org");
  5530. cli.set_follow_location(true);
  5531. Params params;
  5532. params.emplace("url", "http://www.google.com");
  5533. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5534. ASSERT_TRUE(res);
  5535. EXPECT_EQ(StatusCode::OK_200, res->status);
  5536. }
  5537. TEST(HttpToHttpsRedirectTest, CertFile) {
  5538. Server svr;
  5539. ASSERT_TRUE(svr.is_valid());
  5540. svr.Get("/index", [&](const Request &, Response &res) {
  5541. res.set_redirect("https://127.0.0.1:1235/index");
  5542. svr.stop();
  5543. });
  5544. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5545. ASSERT_TRUE(ssl_svr.is_valid());
  5546. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5547. res.set_content("test", "text/plain");
  5548. ssl_svr.stop();
  5549. });
  5550. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5551. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5552. auto se = detail::scope_exit([&] {
  5553. t2.join();
  5554. t.join();
  5555. ASSERT_FALSE(svr.is_running());
  5556. });
  5557. svr.wait_until_ready();
  5558. ssl_svr.wait_until_ready();
  5559. Client cli("127.0.0.1", PORT);
  5560. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5561. cli.enable_server_certificate_verification(true);
  5562. cli.set_follow_location(true);
  5563. cli.set_connection_timeout(30);
  5564. auto res = cli.Get("/index");
  5565. ASSERT_TRUE(res);
  5566. ASSERT_EQ(StatusCode::OK_200, res->status);
  5567. }
  5568. TEST(MultipartFormDataTest, LargeData) {
  5569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5570. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5571. const ContentReader &content_reader) {
  5572. if (req.is_multipart_form_data()) {
  5573. MultipartFormDataItems files;
  5574. content_reader(
  5575. [&](const MultipartFormData &file) {
  5576. files.push_back(file);
  5577. return true;
  5578. },
  5579. [&](const char *data, size_t data_length) {
  5580. files.back().content.append(data, data_length);
  5581. return true;
  5582. });
  5583. EXPECT_TRUE(std::string(files[0].name) == "document");
  5584. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5585. EXPECT_TRUE(files[0].filename == "2MB_data");
  5586. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5587. EXPECT_TRUE(files[1].name == "hello");
  5588. EXPECT_TRUE(files[1].content == "world");
  5589. EXPECT_TRUE(files[1].filename == "");
  5590. EXPECT_TRUE(files[1].content_type == "");
  5591. } else {
  5592. std::string body;
  5593. content_reader([&](const char *data, size_t data_length) {
  5594. body.append(data, data_length);
  5595. return true;
  5596. });
  5597. }
  5598. });
  5599. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5600. auto se = detail::scope_exit([&] {
  5601. svr.stop();
  5602. t.join();
  5603. ASSERT_FALSE(svr.is_running());
  5604. });
  5605. svr.wait_until_ready();
  5606. {
  5607. std::string data(1024 * 1024 * 2, '.');
  5608. std::stringstream buffer;
  5609. buffer << data;
  5610. Client cli("https://localhost:8080");
  5611. cli.enable_server_certificate_verification(false);
  5612. MultipartFormDataItems items{
  5613. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5614. {"hello", "world", "", ""},
  5615. };
  5616. auto res = cli.Post("/post", items);
  5617. ASSERT_TRUE(res);
  5618. ASSERT_EQ(StatusCode::OK_200, res->status);
  5619. }
  5620. }
  5621. TEST(MultipartFormDataTest, DataProviderItems) {
  5622. std::random_device seed_gen;
  5623. std::mt19937 random(seed_gen());
  5624. std::string rand1;
  5625. rand1.resize(1000);
  5626. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5627. std::string rand2;
  5628. rand2.resize(3000);
  5629. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5631. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5632. const ContentReader &content_reader) {
  5633. ASSERT_FALSE(req.is_multipart_form_data());
  5634. std::string body;
  5635. content_reader([&](const char *data, size_t data_length) {
  5636. body.append(data, data_length);
  5637. return true;
  5638. });
  5639. EXPECT_EQ(body, "");
  5640. });
  5641. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5642. const ContentReader &content_reader) {
  5643. ASSERT_TRUE(req.is_multipart_form_data());
  5644. MultipartFormDataItems files;
  5645. content_reader(
  5646. [&](const MultipartFormData &file) {
  5647. files.push_back(file);
  5648. return true;
  5649. },
  5650. [&](const char *data, size_t data_length) {
  5651. files.back().content.append(data, data_length);
  5652. return true;
  5653. });
  5654. ASSERT_TRUE(files.size() == 2);
  5655. EXPECT_EQ(std::string(files[0].name), "name1");
  5656. EXPECT_EQ(files[0].content, "Testing123");
  5657. EXPECT_EQ(files[0].filename, "filename1");
  5658. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5659. EXPECT_EQ(files[1].name, "name2");
  5660. EXPECT_EQ(files[1].content, "Testing456");
  5661. EXPECT_EQ(files[1].filename, "");
  5662. EXPECT_EQ(files[1].content_type, "");
  5663. });
  5664. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5665. const ContentReader &content_reader) {
  5666. ASSERT_TRUE(req.is_multipart_form_data());
  5667. MultipartFormDataItems files;
  5668. content_reader(
  5669. [&](const MultipartFormData &file) {
  5670. files.push_back(file);
  5671. return true;
  5672. },
  5673. [&](const char *data, size_t data_length) {
  5674. files.back().content.append(data, data_length);
  5675. return true;
  5676. });
  5677. ASSERT_TRUE(files.size() == 2);
  5678. EXPECT_EQ(files[0].name, "name3");
  5679. EXPECT_EQ(files[0].content, rand1);
  5680. EXPECT_EQ(files[0].filename, "filename3");
  5681. EXPECT_EQ(files[0].content_type, "");
  5682. EXPECT_EQ(files[1].name, "name4");
  5683. EXPECT_EQ(files[1].content, rand2);
  5684. EXPECT_EQ(files[1].filename, "filename4");
  5685. EXPECT_EQ(files[1].content_type, "");
  5686. });
  5687. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5688. const ContentReader &content_reader) {
  5689. ASSERT_TRUE(req.is_multipart_form_data());
  5690. MultipartFormDataItems files;
  5691. content_reader(
  5692. [&](const MultipartFormData &file) {
  5693. files.push_back(file);
  5694. return true;
  5695. },
  5696. [&](const char *data, size_t data_length) {
  5697. files.back().content.append(data, data_length);
  5698. return true;
  5699. });
  5700. ASSERT_TRUE(files.size() == 4);
  5701. EXPECT_EQ(std::string(files[0].name), "name1");
  5702. EXPECT_EQ(files[0].content, "Testing123");
  5703. EXPECT_EQ(files[0].filename, "filename1");
  5704. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5705. EXPECT_EQ(files[1].name, "name2");
  5706. EXPECT_EQ(files[1].content, "Testing456");
  5707. EXPECT_EQ(files[1].filename, "");
  5708. EXPECT_EQ(files[1].content_type, "");
  5709. EXPECT_EQ(files[2].name, "name3");
  5710. EXPECT_EQ(files[2].content, rand1);
  5711. EXPECT_EQ(files[2].filename, "filename3");
  5712. EXPECT_EQ(files[2].content_type, "");
  5713. EXPECT_EQ(files[3].name, "name4");
  5714. EXPECT_EQ(files[3].content, rand2);
  5715. EXPECT_EQ(files[3].filename, "filename4");
  5716. EXPECT_EQ(files[3].content_type, "");
  5717. });
  5718. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5719. auto se = detail::scope_exit([&] {
  5720. svr.stop();
  5721. t.join();
  5722. ASSERT_FALSE(svr.is_running());
  5723. });
  5724. svr.wait_until_ready();
  5725. {
  5726. Client cli("https://localhost:8080");
  5727. cli.enable_server_certificate_verification(false);
  5728. MultipartFormDataItems items{
  5729. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5730. {"name2", "Testing456", "", ""}, // not a file
  5731. };
  5732. {
  5733. auto res = cli.Post("/post-none", {}, {}, {});
  5734. ASSERT_TRUE(res);
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. }
  5737. MultipartFormDataProviderItems providers;
  5738. {
  5739. auto res =
  5740. cli.Post("/post-items", {}, items, providers); // empty providers
  5741. ASSERT_TRUE(res);
  5742. ASSERT_EQ(StatusCode::OK_200, res->status);
  5743. }
  5744. providers.push_back({"name3",
  5745. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5746. // test the offset is given correctly at each step
  5747. if (!offset)
  5748. sink.os.write(rand1.data(), 30);
  5749. else if (offset == 30)
  5750. sink.os.write(rand1.data() + 30, 300);
  5751. else if (offset == 330)
  5752. sink.os.write(rand1.data() + 330, 670);
  5753. else if (offset == rand1.size())
  5754. sink.done();
  5755. return true;
  5756. },
  5757. "filename3",
  5758. {}});
  5759. providers.push_back({"name4",
  5760. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5761. // test the offset is given correctly at each step
  5762. if (!offset)
  5763. sink.os.write(rand2.data(), 2000);
  5764. else if (offset == 2000)
  5765. sink.os.write(rand2.data() + 2000, 1);
  5766. else if (offset == 2001)
  5767. sink.os.write(rand2.data() + 2001, 999);
  5768. else if (offset == rand2.size())
  5769. sink.done();
  5770. return true;
  5771. },
  5772. "filename4",
  5773. {}});
  5774. {
  5775. auto res = cli.Post("/post-providers", {}, {}, providers);
  5776. ASSERT_TRUE(res);
  5777. ASSERT_EQ(StatusCode::OK_200, res->status);
  5778. }
  5779. {
  5780. auto res = cli.Post("/post-both", {}, items, providers);
  5781. ASSERT_TRUE(res);
  5782. ASSERT_EQ(StatusCode::OK_200, res->status);
  5783. }
  5784. }
  5785. }
  5786. TEST(MultipartFormDataTest, BadHeader) {
  5787. Server svr;
  5788. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5789. res.set_content("ok", "text/plain");
  5790. });
  5791. thread t = thread([&] { svr.listen(HOST, PORT); });
  5792. auto se = detail::scope_exit([&] {
  5793. svr.stop();
  5794. t.join();
  5795. ASSERT_FALSE(svr.is_running());
  5796. });
  5797. svr.wait_until_ready();
  5798. const std::string body =
  5799. "This is the preamble. It is to be ignored, though it\r\n"
  5800. "is a handy place for composition agents to include an\r\n"
  5801. "explanatory note to non-MIME conformant readers.\r\n"
  5802. "\r\n"
  5803. "\r\n"
  5804. "--simple boundary\r\n"
  5805. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5806. ": BAD...\r\n"
  5807. "\r\n"
  5808. "value1\r\n"
  5809. "--simple boundary\r\n"
  5810. "Content-Disposition: form-data; name=\"field2\"; "
  5811. "filename=\"example.txt\"\r\n"
  5812. "\r\n"
  5813. "value2\r\n"
  5814. "--simple boundary--\r\n"
  5815. "This is the epilogue. It is also to be ignored.\r\n";
  5816. std::string content_type =
  5817. R"(multipart/form-data; boundary="simple boundary")";
  5818. Client cli(HOST, PORT);
  5819. auto res = cli.Post("/post", body, content_type.c_str());
  5820. ASSERT_TRUE(res);
  5821. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5822. }
  5823. TEST(MultipartFormDataTest, WithPreamble) {
  5824. Server svr;
  5825. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5826. res.set_content("ok", "text/plain");
  5827. });
  5828. thread t = thread([&] { svr.listen(HOST, PORT); });
  5829. auto se = detail::scope_exit([&] {
  5830. svr.stop();
  5831. t.join();
  5832. ASSERT_FALSE(svr.is_running());
  5833. });
  5834. svr.wait_until_ready();
  5835. const std::string body =
  5836. "This is the preamble. It is to be ignored, though it\r\n"
  5837. "is a handy place for composition agents to include an\r\n"
  5838. "explanatory note to non-MIME conformant readers.\r\n"
  5839. "\r\n"
  5840. "\r\n"
  5841. "--simple boundary\r\n"
  5842. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5843. "\r\n"
  5844. "value1\r\n"
  5845. "--simple boundary\r\n"
  5846. "Content-Disposition: form-data; name=\"field2\"; "
  5847. "filename=\"example.txt\"\r\n"
  5848. "\r\n"
  5849. "value2\r\n"
  5850. "--simple boundary--\r\n"
  5851. "This is the epilogue. It is also to be ignored.\r\n";
  5852. std::string content_type =
  5853. R"(multipart/form-data; boundary="simple boundary")";
  5854. Client cli(HOST, PORT);
  5855. auto res = cli.Post("/post", body, content_type.c_str());
  5856. ASSERT_TRUE(res);
  5857. EXPECT_EQ(StatusCode::OK_200, res->status);
  5858. }
  5859. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5860. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5861. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5862. const ContentReader &content_reader) {
  5863. if (req.is_multipart_form_data()) {
  5864. MultipartFormDataItems files;
  5865. content_reader(
  5866. [&](const MultipartFormData &file) {
  5867. files.push_back(file);
  5868. return true;
  5869. },
  5870. [&](const char *data, size_t data_length) {
  5871. files.back().content.append(data, data_length);
  5872. return true;
  5873. });
  5874. EXPECT_TRUE(std::string(files[0].name) == "document");
  5875. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5876. EXPECT_TRUE(files[0].filename == "2MB_data");
  5877. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5878. EXPECT_TRUE(files[1].name == "hello");
  5879. EXPECT_TRUE(files[1].content == "world");
  5880. EXPECT_TRUE(files[1].filename == "");
  5881. EXPECT_TRUE(files[1].content_type == "");
  5882. } else {
  5883. std::string body;
  5884. content_reader([&](const char *data, size_t data_length) {
  5885. body.append(data, data_length);
  5886. return true;
  5887. });
  5888. }
  5889. });
  5890. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5891. auto se = detail::scope_exit([&] {
  5892. svr.stop();
  5893. t.join();
  5894. ASSERT_FALSE(svr.is_running());
  5895. });
  5896. svr.wait_until_ready();
  5897. {
  5898. std::string data(1024 * 1024 * 2, '.');
  5899. std::stringstream buffer;
  5900. buffer << data;
  5901. Client cli("https://localhost:8080");
  5902. cli.enable_server_certificate_verification(false);
  5903. MultipartFormDataItems items{
  5904. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5905. {"hello", "world", "", ""},
  5906. };
  5907. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5908. ASSERT_TRUE(res);
  5909. ASSERT_EQ(StatusCode::OK_200, res->status);
  5910. }
  5911. }
  5912. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5913. std::string data(1024 * 1024 * 2, '&');
  5914. std::stringstream buffer;
  5915. buffer << data;
  5916. Client cli("https://localhost:8080");
  5917. MultipartFormDataItems items{
  5918. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5919. {"hello", "world", "", ""},
  5920. };
  5921. for (const char &c : " \t\r\n") {
  5922. auto res =
  5923. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5924. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5925. ASSERT_FALSE(res);
  5926. }
  5927. }
  5928. TEST(MultipartFormDataTest, PutFormData) {
  5929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5930. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5931. const ContentReader &content_reader) {
  5932. if (req.is_multipart_form_data()) {
  5933. MultipartFormDataItems files;
  5934. content_reader(
  5935. [&](const MultipartFormData &file) {
  5936. files.push_back(file);
  5937. return true;
  5938. },
  5939. [&](const char *data, size_t data_length) {
  5940. files.back().content.append(data, data_length);
  5941. return true;
  5942. });
  5943. EXPECT_TRUE(std::string(files[0].name) == "document");
  5944. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5945. EXPECT_TRUE(files[0].filename == "2MB_data");
  5946. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5947. EXPECT_TRUE(files[1].name == "hello");
  5948. EXPECT_TRUE(files[1].content == "world");
  5949. EXPECT_TRUE(files[1].filename == "");
  5950. EXPECT_TRUE(files[1].content_type == "");
  5951. } else {
  5952. std::string body;
  5953. content_reader([&](const char *data, size_t data_length) {
  5954. body.append(data, data_length);
  5955. return true;
  5956. });
  5957. }
  5958. });
  5959. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5960. auto se = detail::scope_exit([&] {
  5961. svr.stop();
  5962. t.join();
  5963. ASSERT_FALSE(svr.is_running());
  5964. });
  5965. svr.wait_until_ready();
  5966. {
  5967. std::string data(1024 * 1024 * 2, '&');
  5968. std::stringstream buffer;
  5969. buffer << data;
  5970. Client cli("https://localhost:8080");
  5971. cli.enable_server_certificate_verification(false);
  5972. MultipartFormDataItems items{
  5973. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5974. {"hello", "world", "", ""},
  5975. };
  5976. auto res = cli.Put("/put", items);
  5977. ASSERT_TRUE(res);
  5978. ASSERT_EQ(StatusCode::OK_200, res->status);
  5979. }
  5980. }
  5981. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5983. svr.Put("/put_customboundary",
  5984. [&](const Request &req, const Response & /*res*/,
  5985. const ContentReader &content_reader) {
  5986. if (req.is_multipart_form_data()) {
  5987. MultipartFormDataItems files;
  5988. content_reader(
  5989. [&](const MultipartFormData &file) {
  5990. files.push_back(file);
  5991. return true;
  5992. },
  5993. [&](const char *data, size_t data_length) {
  5994. files.back().content.append(data, data_length);
  5995. return true;
  5996. });
  5997. EXPECT_TRUE(std::string(files[0].name) == "document");
  5998. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5999. EXPECT_TRUE(files[0].filename == "2MB_data");
  6000. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  6001. EXPECT_TRUE(files[1].name == "hello");
  6002. EXPECT_TRUE(files[1].content == "world");
  6003. EXPECT_TRUE(files[1].filename == "");
  6004. EXPECT_TRUE(files[1].content_type == "");
  6005. } else {
  6006. std::string body;
  6007. content_reader([&](const char *data, size_t data_length) {
  6008. body.append(data, data_length);
  6009. return true;
  6010. });
  6011. }
  6012. });
  6013. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  6014. auto se = detail::scope_exit([&] {
  6015. svr.stop();
  6016. t.join();
  6017. ASSERT_FALSE(svr.is_running());
  6018. });
  6019. svr.wait_until_ready();
  6020. {
  6021. std::string data(1024 * 1024 * 2, '&');
  6022. std::stringstream buffer;
  6023. buffer << data;
  6024. Client cli("https://localhost:8080");
  6025. cli.enable_server_certificate_verification(false);
  6026. MultipartFormDataItems items{
  6027. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6028. {"hello", "world", "", ""},
  6029. };
  6030. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  6031. ASSERT_TRUE(res);
  6032. ASSERT_EQ(StatusCode::OK_200, res->status);
  6033. }
  6034. }
  6035. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  6036. std::string data(1024 * 1024 * 2, '&');
  6037. std::stringstream buffer;
  6038. buffer << data;
  6039. Client cli("https://localhost:8080");
  6040. cli.enable_server_certificate_verification(false);
  6041. MultipartFormDataItems items{
  6042. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  6043. {"hello", "world", "", ""},
  6044. };
  6045. for (const char &c : " \t\r\n") {
  6046. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  6047. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  6048. ASSERT_FALSE(res);
  6049. }
  6050. }
  6051. TEST(MultipartFormDataTest, AlternateFilename) {
  6052. auto handled = false;
  6053. Server svr;
  6054. svr.Post("/test", [&](const Request &req, Response &res) {
  6055. ASSERT_EQ(3u, req.files.size());
  6056. auto it = req.files.begin();
  6057. ASSERT_EQ("file1", it->second.name);
  6058. ASSERT_EQ("A.txt", it->second.filename);
  6059. ASSERT_EQ("text/plain", it->second.content_type);
  6060. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6061. ++it;
  6062. ASSERT_EQ("file2", it->second.name);
  6063. ASSERT_EQ("a.html", it->second.filename);
  6064. ASSERT_EQ("text/html", it->second.content_type);
  6065. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6066. it->second.content);
  6067. ++it;
  6068. ASSERT_EQ("text", it->second.name);
  6069. ASSERT_EQ("", it->second.filename);
  6070. ASSERT_EQ("", it->second.content_type);
  6071. ASSERT_EQ("text default", it->second.content);
  6072. res.set_content("ok", "text/plain");
  6073. handled = true;
  6074. });
  6075. thread t = thread([&] { svr.listen(HOST, PORT); });
  6076. auto se = detail::scope_exit([&] {
  6077. svr.stop();
  6078. t.join();
  6079. ASSERT_FALSE(svr.is_running());
  6080. ASSERT_TRUE(handled);
  6081. });
  6082. svr.wait_until_ready();
  6083. auto req = "POST /test HTTP/1.1\r\n"
  6084. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6085. "Content-Length: 399\r\n"
  6086. "\r\n"
  6087. "----------\r\n"
  6088. "Content-Disposition: form-data; name=\"text\"\r\n"
  6089. "\r\n"
  6090. "text default\r\n"
  6091. "----------\r\n"
  6092. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6093. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6094. "Content-Type: text/plain\r\n"
  6095. "\r\n"
  6096. "Content of a.txt.\r\n"
  6097. "\r\n"
  6098. "----------\r\n"
  6099. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6100. "\"a.html\"\r\n"
  6101. "Content-Type: text/html\r\n"
  6102. "\r\n"
  6103. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6104. "\r\n"
  6105. "------------\r\n";
  6106. ASSERT_TRUE(send_request(1, req));
  6107. }
  6108. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6109. auto handled = false;
  6110. Server svr;
  6111. svr.Post("/test", [&](const Request &req, Response &) {
  6112. ASSERT_EQ(2u, req.files.size());
  6113. auto it = req.files.begin();
  6114. ASSERT_EQ("text1", it->second.name);
  6115. ASSERT_EQ("text1", it->second.content);
  6116. ++it;
  6117. ASSERT_EQ("text2", it->second.name);
  6118. ASSERT_EQ("text2", it->second.content);
  6119. handled = true;
  6120. });
  6121. thread t = thread([&] { svr.listen(HOST, PORT); });
  6122. auto se = detail::scope_exit([&] {
  6123. svr.stop();
  6124. t.join();
  6125. ASSERT_FALSE(svr.is_running());
  6126. ASSERT_TRUE(handled);
  6127. });
  6128. svr.wait_until_ready();
  6129. auto req = "POST /test HTTP/1.1\r\n"
  6130. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6131. "Content-Length: 146\r\n"
  6132. "\r\n----------\r\n"
  6133. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6134. "\r\n"
  6135. "text1"
  6136. "\r\n----------\r\n"
  6137. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6138. "\r\n"
  6139. "text2"
  6140. "\r\n------------";
  6141. std::string resonse;
  6142. ASSERT_TRUE(send_request(1, req, &resonse));
  6143. ASSERT_EQ("200", resonse.substr(9, 3));
  6144. }
  6145. TEST(MultipartFormDataTest, ContentLength) {
  6146. auto handled = false;
  6147. Server svr;
  6148. svr.Post("/test", [&](const Request &req, Response &) {
  6149. ASSERT_EQ(2u, req.files.size());
  6150. auto it = req.files.begin();
  6151. ASSERT_EQ("text1", it->second.name);
  6152. ASSERT_EQ("text1", it->second.content);
  6153. ++it;
  6154. ASSERT_EQ("text2", it->second.name);
  6155. ASSERT_EQ("text2", it->second.content);
  6156. handled = true;
  6157. });
  6158. thread t = thread([&] { svr.listen(HOST, PORT); });
  6159. auto se = detail::scope_exit([&] {
  6160. svr.stop();
  6161. t.join();
  6162. ASSERT_FALSE(svr.is_running());
  6163. ASSERT_TRUE(handled);
  6164. });
  6165. svr.wait_until_ready();
  6166. auto req = "POST /test HTTP/1.1\r\n"
  6167. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6168. "Content-Length: 167\r\n"
  6169. "\r\n----------\r\n"
  6170. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6171. "Content-Length: 5\r\n"
  6172. "\r\n"
  6173. "text1"
  6174. "\r\n----------\r\n"
  6175. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6176. "\r\n"
  6177. "text2"
  6178. "\r\n------------\r\n";
  6179. std::string resonse;
  6180. ASSERT_TRUE(send_request(1, req, &resonse));
  6181. ASSERT_EQ("200", resonse.substr(9, 3));
  6182. }
  6183. #endif
  6184. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6185. static constexpr unsigned int number_of_tasks{1000000};
  6186. std::atomic_uint count{0};
  6187. std::unique_ptr<TaskQueue> task_queue{
  6188. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6189. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6190. auto queued = task_queue->enqueue(
  6191. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6192. EXPECT_TRUE(queued);
  6193. }
  6194. EXPECT_NO_THROW(task_queue->shutdown());
  6195. EXPECT_EQ(number_of_tasks, count.load());
  6196. }
  6197. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6198. static constexpr unsigned int number_of_tasks{1000000};
  6199. static constexpr unsigned int qlimit{2};
  6200. unsigned int queued_count{0};
  6201. std::atomic_uint count{0};
  6202. std::unique_ptr<TaskQueue> task_queue{
  6203. new ThreadPool{/*num_threads=*/1, qlimit}};
  6204. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6205. if (task_queue->enqueue(
  6206. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6207. queued_count++;
  6208. }
  6209. }
  6210. EXPECT_NO_THROW(task_queue->shutdown());
  6211. EXPECT_EQ(queued_count, count.load());
  6212. EXPECT_TRUE(queued_count <= number_of_tasks);
  6213. EXPECT_TRUE(queued_count >= qlimit);
  6214. }
  6215. TEST(TaskQueueTest, MaxQueuedRequests) {
  6216. static constexpr unsigned int qlimit{3};
  6217. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6218. std::condition_variable sem_cv;
  6219. std::mutex sem_mtx;
  6220. int credits = 0;
  6221. bool queued;
  6222. /* Fill up the queue with tasks that will block until we give them credits to
  6223. * complete. */
  6224. for (unsigned int n = 0; n <= qlimit;) {
  6225. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6226. std::unique_lock<std::mutex> lock(sem_mtx);
  6227. while (credits <= 0) {
  6228. sem_cv.wait(lock);
  6229. }
  6230. /* Consume the credit and signal the test code if they are all gone. */
  6231. if (--credits == 0) { sem_cv.notify_one(); }
  6232. });
  6233. if (n < qlimit) {
  6234. /* The first qlimit enqueues must succeed. */
  6235. EXPECT_TRUE(queued);
  6236. } else {
  6237. /* The last one will succeed only when the worker thread
  6238. * starts and dequeues the first blocking task. Although
  6239. * not necessary for the correctness of this test, we sleep for
  6240. * a short while to avoid busy waiting. */
  6241. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6242. }
  6243. if (queued) { n++; }
  6244. }
  6245. /* Further enqueues must fail since the queue is full. */
  6246. for (auto i = 0; i < 4; i++) {
  6247. queued = task_queue->enqueue([] {});
  6248. EXPECT_FALSE(queued);
  6249. }
  6250. /* Give the credits to allow the previous tasks to complete. */
  6251. {
  6252. std::unique_lock<std::mutex> lock(sem_mtx);
  6253. credits += qlimit + 1;
  6254. }
  6255. sem_cv.notify_all();
  6256. /* Wait for all the credits to be consumed. */
  6257. {
  6258. std::unique_lock<std::mutex> lock(sem_mtx);
  6259. while (credits > 0) {
  6260. sem_cv.wait(lock);
  6261. }
  6262. }
  6263. /* Check that we are able again to enqueue at least qlimit tasks. */
  6264. for (unsigned int i = 0; i < qlimit; i++) {
  6265. queued = task_queue->enqueue([] {});
  6266. EXPECT_TRUE(queued);
  6267. }
  6268. EXPECT_NO_THROW(task_queue->shutdown());
  6269. }
  6270. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6271. Server svr;
  6272. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6273. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6274. });
  6275. svr.Get("/hello", [](const Request &req, Response &res) {
  6276. res.set_content(req.get_param_value("key"), "text/plain");
  6277. });
  6278. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6279. auto se = detail::scope_exit([&] {
  6280. svr.stop();
  6281. thread.join();
  6282. ASSERT_FALSE(svr.is_running());
  6283. });
  6284. svr.wait_until_ready();
  6285. {
  6286. Client cli(HOST, PORT);
  6287. cli.set_follow_location(true);
  6288. auto res = cli.Get("/");
  6289. ASSERT_TRUE(res);
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("val&key2=val2", res->body);
  6292. }
  6293. }
  6294. TEST(VulnerabilityTest, CRLFInjection) {
  6295. Server svr;
  6296. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6297. res.set_content("Hello 1", "text/plain");
  6298. });
  6299. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6300. res.set_content("Hello 2", "text/plain");
  6301. });
  6302. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6303. res.set_content("Hello 3", "text/plain");
  6304. });
  6305. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6306. res.set_content("Hello 4", "text/plain");
  6307. });
  6308. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6309. for (const auto &x : req.headers) {
  6310. auto key = x.first;
  6311. EXPECT_STRNE("evil", key.c_str());
  6312. }
  6313. });
  6314. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6315. auto se = detail::scope_exit([&] {
  6316. svr.stop();
  6317. thread.join();
  6318. ASSERT_FALSE(svr.is_running());
  6319. });
  6320. svr.wait_until_ready();
  6321. {
  6322. Client cli(HOST, PORT);
  6323. cli.Post("/test1", "A=B",
  6324. "application/x-www-form-urlencoded\r\nevil: hello1");
  6325. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6326. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6327. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6328. }
  6329. }
  6330. TEST(PathParamsTest, StaticMatch) {
  6331. const auto pattern = "/users/all";
  6332. detail::PathParamsMatcher matcher(pattern);
  6333. Request request;
  6334. request.path = "/users/all";
  6335. ASSERT_TRUE(matcher.match(request));
  6336. std::unordered_map<std::string, std::string> expected_params = {};
  6337. EXPECT_EQ(request.path_params, expected_params);
  6338. }
  6339. TEST(PathParamsTest, StaticMismatch) {
  6340. const auto pattern = "/users/all";
  6341. detail::PathParamsMatcher matcher(pattern);
  6342. Request request;
  6343. request.path = "/users/1";
  6344. ASSERT_FALSE(matcher.match(request));
  6345. }
  6346. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6347. const auto pattern = "/users/:id/subscriptions";
  6348. detail::PathParamsMatcher matcher(pattern);
  6349. Request request;
  6350. request.path = "/users/42/subscriptions";
  6351. ASSERT_TRUE(matcher.match(request));
  6352. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6353. EXPECT_EQ(request.path_params, expected_params);
  6354. }
  6355. TEST(PathParamsTest, SingleParamInTheEnd) {
  6356. const auto pattern = "/users/:id";
  6357. detail::PathParamsMatcher matcher(pattern);
  6358. Request request;
  6359. request.path = "/users/24";
  6360. ASSERT_TRUE(matcher.match(request));
  6361. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6362. EXPECT_EQ(request.path_params, expected_params);
  6363. }
  6364. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6365. const auto pattern = "/users/:id/";
  6366. detail::PathParamsMatcher matcher(pattern);
  6367. Request request;
  6368. request.path = "/users/42/";
  6369. ASSERT_TRUE(matcher.match(request));
  6370. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6371. EXPECT_EQ(request.path_params, expected_params);
  6372. }
  6373. TEST(PathParamsTest, EmptyParam) {
  6374. const auto pattern = "/users/:id/";
  6375. detail::PathParamsMatcher matcher(pattern);
  6376. Request request;
  6377. request.path = "/users//";
  6378. ASSERT_TRUE(matcher.match(request));
  6379. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6380. EXPECT_EQ(request.path_params, expected_params);
  6381. }
  6382. TEST(PathParamsTest, FragmentMismatch) {
  6383. const auto pattern = "/users/:id/";
  6384. detail::PathParamsMatcher matcher(pattern);
  6385. Request request;
  6386. request.path = "/admins/24/";
  6387. ASSERT_FALSE(matcher.match(request));
  6388. }
  6389. TEST(PathParamsTest, ExtraFragments) {
  6390. const auto pattern = "/users/:id";
  6391. detail::PathParamsMatcher matcher(pattern);
  6392. Request request;
  6393. request.path = "/users/42/subscriptions";
  6394. ASSERT_FALSE(matcher.match(request));
  6395. }
  6396. TEST(PathParamsTest, MissingTrailingParam) {
  6397. const auto pattern = "/users/:id";
  6398. detail::PathParamsMatcher matcher(pattern);
  6399. Request request;
  6400. request.path = "/users";
  6401. ASSERT_FALSE(matcher.match(request));
  6402. }
  6403. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6404. const auto pattern = "/users/:id/subscriptions";
  6405. detail::PathParamsMatcher matcher(pattern);
  6406. Request request;
  6407. request.path = "/users/subscriptions";
  6408. ASSERT_FALSE(matcher.match(request));
  6409. }
  6410. TEST(PathParamsTest, MultipleParams) {
  6411. const auto pattern = "/users/:userid/subscriptions/:subid";
  6412. detail::PathParamsMatcher matcher(pattern);
  6413. Request request;
  6414. request.path = "/users/42/subscriptions/2";
  6415. ASSERT_TRUE(matcher.match(request));
  6416. std::unordered_map<std::string, std::string> expected_params = {
  6417. {"userid", "42"}, {"subid", "2"}};
  6418. EXPECT_EQ(request.path_params, expected_params);
  6419. }
  6420. TEST(PathParamsTest, SequenceOfParams) {
  6421. const auto pattern = "/values/:x/:y/:z";
  6422. detail::PathParamsMatcher matcher(pattern);
  6423. Request request;
  6424. request.path = "/values/1/2/3";
  6425. ASSERT_TRUE(matcher.match(request));
  6426. std::unordered_map<std::string, std::string> expected_params = {
  6427. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6428. EXPECT_EQ(request.path_params, expected_params);
  6429. }
  6430. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6431. const auto pattern = "/prefix:suffix";
  6432. detail::PathParamsMatcher matcher(pattern);
  6433. Request request;
  6434. request.path = "/prefix:suffix";
  6435. ASSERT_TRUE(matcher.match(request));
  6436. const std::unordered_map<std::string, std::string> expected_params = {};
  6437. EXPECT_EQ(request.path_params, expected_params);
  6438. }
  6439. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6440. // If ipv6 regex working, regex match codepath is taken.
  6441. // else port will default to 80 in Client impl
  6442. int clientImplMagicPort = 80;
  6443. int port = 4321;
  6444. // above ports must be different to avoid false negative
  6445. EXPECT_NE(clientImplMagicPort, port);
  6446. std::string ipV6TestURL = "http://[ff06::c3]";
  6447. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6448. CLIENT_PRIVATE_KEY_FILE);
  6449. EXPECT_EQ(cli.port(), port);
  6450. }
  6451. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6452. auto file_path = "./www/dir/index.html";
  6453. auto dir_path = "./www/dir";
  6454. detail::FileStat stat_file(file_path);
  6455. EXPECT_TRUE(stat_file.is_file());
  6456. EXPECT_FALSE(stat_file.is_dir());
  6457. detail::FileStat stat_dir(dir_path);
  6458. EXPECT_FALSE(stat_dir.is_file());
  6459. EXPECT_TRUE(stat_dir.is_dir());
  6460. }
  6461. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6462. Server svr;
  6463. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6464. EXPECT_EQ(res.status, 400);
  6465. });
  6466. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6467. auto se = detail::scope_exit([&] {
  6468. svr.stop();
  6469. thread.join();
  6470. ASSERT_FALSE(svr.is_running());
  6471. });
  6472. svr.wait_until_ready();
  6473. Client cli(HOST, PORT);
  6474. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6475. }
  6476. #ifndef _WIN32
  6477. TEST(Expect100ContinueTest, ServerClosesConnection) {
  6478. static constexpr char reject[] = "Unauthorized";
  6479. static constexpr char accept[] = "Upload accepted";
  6480. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  6481. Server svr;
  6482. svr.set_expect_100_continue_handler(
  6483. [](const Request & /*req*/, Response &res) {
  6484. res.status = StatusCode::Unauthorized_401;
  6485. res.set_content(reject, "text/plain");
  6486. return res.status;
  6487. });
  6488. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  6489. res.set_content(accept, "text/plain");
  6490. });
  6491. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6492. auto se = detail::scope_exit([&] {
  6493. svr.stop();
  6494. thread.join();
  6495. ASSERT_FALSE(svr.is_running());
  6496. });
  6497. svr.wait_until_ready();
  6498. {
  6499. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  6500. curl_easy_init(), &curl_easy_cleanup};
  6501. ASSERT_NE(curl, nullptr);
  6502. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  6503. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  6504. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  6505. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  6506. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  6507. &curl_slist_free_all};
  6508. ASSERT_NE(list, nullptr);
  6509. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  6510. struct read_data {
  6511. size_t read_size;
  6512. size_t total_size;
  6513. } data = {0, total_size};
  6514. using read_callback_t =
  6515. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6516. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  6517. void *userdata) -> size_t {
  6518. read_data *data = (read_data *)userdata;
  6519. if (!userdata || data->read_size >= data->total_size) { return 0; }
  6520. std::fill_n(ptr, size * nmemb, 'A');
  6521. data->read_size += size * nmemb;
  6522. return size * nmemb;
  6523. };
  6524. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  6525. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  6526. std::vector<char> buffer;
  6527. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  6528. using write_callback_t =
  6529. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6530. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  6531. void *userdata) -> size_t {
  6532. std::vector<char> *buffer = (std::vector<char> *)userdata;
  6533. buffer->reserve(buffer->size() + size * nmemb + 1);
  6534. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  6535. return size * nmemb;
  6536. };
  6537. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  6538. {
  6539. const auto res = curl_easy_perform(curl.get());
  6540. ASSERT_EQ(res, CURLE_OK);
  6541. }
  6542. {
  6543. auto response_code = long{};
  6544. const auto res =
  6545. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  6546. ASSERT_EQ(res, CURLE_OK);
  6547. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  6548. }
  6549. {
  6550. auto dl = curl_off_t{};
  6551. const auto res =
  6552. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  6553. ASSERT_EQ(res, CURLE_OK);
  6554. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  6555. }
  6556. {
  6557. buffer.push_back('\0');
  6558. ASSERT_STRCASEEQ(buffer.data(), reject);
  6559. }
  6560. }
  6561. }
  6562. #endif