test.cc 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <memory>
  8. #include <sstream>
  9. #include <stdexcept>
  10. #include <thread>
  11. #include <type_traits>
  12. #define SERVER_CERT_FILE "./cert.pem"
  13. #define SERVER_CERT2_FILE "./cert2.pem"
  14. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  15. #define CA_CERT_FILE "./ca-bundle.crt"
  16. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  17. #define CLIENT_CA_CERT_DIR "."
  18. #define CLIENT_CERT_FILE "./client.cert.pem"
  19. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  20. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  21. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  22. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  23. using namespace std;
  24. using namespace httplib;
  25. const char *HOST = "localhost";
  26. const int PORT = 1234;
  27. const string LONG_QUERY_VALUE = string(25000, '@');
  28. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  29. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  30. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  31. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  32. const char *key) {
  33. auto it = std::find_if(
  34. files.begin(), files.end(),
  35. [&](const MultipartFormData &file) { return file.name == key; });
  36. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  37. return *it;
  38. #else
  39. if (it != files.end()) { return *it; }
  40. throw std::runtime_error("invalid mulitpart form data name error");
  41. #endif
  42. }
  43. TEST(ConstructorTest, MoveConstructible) {
  44. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  45. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  46. }
  47. #ifdef _WIN32
  48. TEST(StartupTest, WSAStartup) {
  49. WSADATA wsaData;
  50. int ret = WSAStartup(0x0002, &wsaData);
  51. ASSERT_EQ(0, ret);
  52. }
  53. #endif
  54. TEST(DecodeURLTest, PercentCharacter) {
  55. EXPECT_EQ(
  56. detail::decode_url(
  57. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  58. false),
  59. R"(descrip=Gastos áéíóúñÑ 6)");
  60. }
  61. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  62. string unescapedCharacters = "-_.!~*'()";
  63. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  64. }
  65. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  66. string reservedCharacters = ";,/?:@&=+$";
  67. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  68. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  69. }
  70. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  71. string chineseCharacters = "中国語";
  72. string russianCharacters = "дом";
  73. string brazilianCharacters = "óculos";
  74. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  75. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  76. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  77. "%D0%B4%D0%BE%D0%BC");
  78. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  79. }
  80. TEST(TrimTests, TrimStringTests) {
  81. EXPECT_EQ("abc", detail::trim_copy("abc"));
  82. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  83. EXPECT_TRUE(detail::trim_copy("").empty());
  84. }
  85. TEST(SplitTest, ParseQueryString) {
  86. string s = "key1=val1&key2=val2&key3=val3";
  87. Params dic;
  88. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  89. [&](const char *b, const char *e) {
  90. string key, val;
  91. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  92. if (key.empty()) {
  93. key.assign(b2, e2);
  94. } else {
  95. val.assign(b2, e2);
  96. }
  97. });
  98. dic.emplace(key, val);
  99. });
  100. EXPECT_EQ("val1", dic.find("key1")->second);
  101. EXPECT_EQ("val2", dic.find("key2")->second);
  102. EXPECT_EQ("val3", dic.find("key3")->second);
  103. }
  104. TEST(SplitTest, ParseInvalidQueryTests) {
  105. {
  106. string s = " ";
  107. Params dict;
  108. detail::parse_query_text(s, dict);
  109. EXPECT_TRUE(dict.empty());
  110. }
  111. {
  112. string s = " = =";
  113. Params dict;
  114. detail::parse_query_text(s, dict);
  115. EXPECT_TRUE(dict.empty());
  116. }
  117. }
  118. TEST(ParseQueryTest, ParseQueryString) {
  119. string s = "key1=val1&key2=val2&key3=val3";
  120. Params dic;
  121. detail::parse_query_text(s, dic);
  122. EXPECT_EQ("val1", dic.find("key1")->second);
  123. EXPECT_EQ("val2", dic.find("key2")->second);
  124. EXPECT_EQ("val3", dic.find("key3")->second);
  125. }
  126. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  127. Params dic;
  128. EXPECT_EQ(detail::params_to_query_str(dic), "");
  129. dic.emplace("key1", "val1");
  130. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  131. dic.emplace("key2", "val2");
  132. dic.emplace("key3", "val3");
  133. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  134. }
  135. TEST(GetHeaderValueTest, DefaultValue) {
  136. Headers headers = {{"Dummy", "Dummy"}};
  137. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  138. EXPECT_STREQ("text/plain", val);
  139. }
  140. TEST(GetHeaderValueTest, DefaultValueInt) {
  141. Headers headers = {{"Dummy", "Dummy"}};
  142. auto val =
  143. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 100);
  144. EXPECT_EQ(100ull, val);
  145. }
  146. TEST(GetHeaderValueTest, RegularValue) {
  147. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  148. auto val = detail::get_header_value(headers, "Content-Type", 0, "text/plain");
  149. EXPECT_STREQ("text/html", val);
  150. }
  151. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  152. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  153. auto val = detail::get_header_value(headers, "content-type", 0, "text/plain");
  154. EXPECT_STREQ("text/html", val);
  155. }
  156. TEST(GetHeaderValueTest, SetContent) {
  157. Response res;
  158. res.set_content("html", "text/html");
  159. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  160. res.set_content("text", "text/plain");
  161. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  162. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  163. }
  164. TEST(GetHeaderValueTest, RegularValueInt) {
  165. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  166. auto val =
  167. detail::get_header_value<uint64_t>(headers, "Content-Length", 0, 0);
  168. EXPECT_EQ(100ull, val);
  169. }
  170. TEST(GetHeaderValueTest, Range) {
  171. {
  172. Headers headers = {make_range_header({{1, -1}})};
  173. auto val = detail::get_header_value(headers, "Range", 0, 0);
  174. EXPECT_STREQ("bytes=1-", val);
  175. }
  176. {
  177. Headers headers = {make_range_header({{-1, 1}})};
  178. auto val = detail::get_header_value(headers, "Range", 0, 0);
  179. EXPECT_STREQ("bytes=-1", val);
  180. }
  181. {
  182. Headers headers = {make_range_header({{1, 10}})};
  183. auto val = detail::get_header_value(headers, "Range", 0, 0);
  184. EXPECT_STREQ("bytes=1-10", val);
  185. }
  186. {
  187. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  188. auto val = detail::get_header_value(headers, "Range", 0, 0);
  189. EXPECT_STREQ("bytes=1-10, 100-", val);
  190. }
  191. {
  192. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  193. auto val = detail::get_header_value(headers, "Range", 0, 0);
  194. EXPECT_STREQ("bytes=1-10, 100-200", val);
  195. }
  196. {
  197. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  198. auto val = detail::get_header_value(headers, "Range", 0, 0);
  199. EXPECT_STREQ("bytes=0-0, -1", val);
  200. }
  201. }
  202. TEST(ParseHeaderValueTest, Range) {
  203. {
  204. Ranges ranges;
  205. auto ret = detail::parse_range_header("bytes=1-", ranges);
  206. EXPECT_TRUE(ret);
  207. EXPECT_EQ(1u, ranges.size());
  208. EXPECT_EQ(1u, ranges[0].first);
  209. EXPECT_EQ(-1, ranges[0].second);
  210. }
  211. {
  212. Ranges ranges;
  213. auto ret = detail::parse_range_header("bytes=-1", ranges);
  214. EXPECT_TRUE(ret);
  215. EXPECT_EQ(1u, ranges.size());
  216. EXPECT_EQ(-1, ranges[0].first);
  217. EXPECT_EQ(1u, ranges[0].second);
  218. }
  219. {
  220. Ranges ranges;
  221. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  222. EXPECT_TRUE(ret);
  223. EXPECT_EQ(1u, ranges.size());
  224. EXPECT_EQ(1u, ranges[0].first);
  225. EXPECT_EQ(10u, ranges[0].second);
  226. }
  227. {
  228. Ranges ranges;
  229. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  230. EXPECT_FALSE(ret);
  231. }
  232. {
  233. Ranges ranges;
  234. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  235. EXPECT_TRUE(ret);
  236. EXPECT_EQ(2u, ranges.size());
  237. EXPECT_EQ(1u, ranges[0].first);
  238. EXPECT_EQ(10u, ranges[0].second);
  239. EXPECT_EQ(100u, ranges[1].first);
  240. EXPECT_EQ(-1, ranges[1].second);
  241. }
  242. {
  243. Ranges ranges;
  244. auto ret =
  245. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  246. EXPECT_TRUE(ret);
  247. EXPECT_EQ(3u, ranges.size());
  248. EXPECT_EQ(1u, ranges[0].first);
  249. EXPECT_EQ(10u, ranges[0].second);
  250. EXPECT_EQ(100u, ranges[1].first);
  251. EXPECT_EQ(200u, ranges[1].second);
  252. EXPECT_EQ(300u, ranges[2].first);
  253. EXPECT_EQ(400u, ranges[2].second);
  254. }
  255. }
  256. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  257. Request req;
  258. req.set_header("Accept-Encoding", "gzip");
  259. Response res;
  260. res.set_header("Content-Type", "text/plain");
  261. auto ret = detail::encoding_type(req, res);
  262. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  263. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  264. #else
  265. EXPECT_TRUE(ret == detail::EncodingType::None);
  266. #endif
  267. }
  268. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  269. Request req;
  270. req.set_header("Accept-Encoding", "gzip, deflate, br");
  271. Response res;
  272. res.set_header("Content-Type", "text/plain");
  273. auto ret = detail::encoding_type(req, res);
  274. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  275. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  276. #elif CPPHTTPLIB_ZLIB_SUPPORT
  277. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  278. #else
  279. EXPECT_TRUE(ret == detail::EncodingType::None);
  280. #endif
  281. }
  282. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  283. Request req;
  284. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  285. Response res;
  286. res.set_header("Content-Type", "text/plain");
  287. auto ret = detail::encoding_type(req, res);
  288. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  289. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  290. #elif CPPHTTPLIB_ZLIB_SUPPORT
  291. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  292. #else
  293. EXPECT_TRUE(ret == detail::EncodingType::None);
  294. #endif
  295. }
  296. TEST(BufferStreamTest, read) {
  297. detail::BufferStream strm1;
  298. Stream &strm = strm1;
  299. EXPECT_EQ(5, strm.write("hello"));
  300. char buf[512];
  301. EXPECT_EQ(2, strm.read(buf, 2));
  302. EXPECT_EQ('h', buf[0]);
  303. EXPECT_EQ('e', buf[1]);
  304. EXPECT_EQ(2, strm.read(buf, 2));
  305. EXPECT_EQ('l', buf[0]);
  306. EXPECT_EQ('l', buf[1]);
  307. EXPECT_EQ(1, strm.read(buf, 1));
  308. EXPECT_EQ('o', buf[0]);
  309. EXPECT_EQ(0, strm.read(buf, 1));
  310. }
  311. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  312. auto host = "www.httpwatch.com";
  313. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  314. auto port = 443;
  315. SSLClient cli(host, port);
  316. #else
  317. auto port = 80;
  318. Client cli(host, port);
  319. #endif
  320. cli.set_connection_timeout(2);
  321. auto res =
  322. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  323. ASSERT_TRUE(res);
  324. std::string out;
  325. detail::read_file("./image.jpg", out);
  326. EXPECT_EQ(200, res->status);
  327. EXPECT_EQ(out, res->body);
  328. }
  329. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  330. auto host = "www.httpwatch.com";
  331. auto ip = hosted_at(host);
  332. EXPECT_EQ("191.236.16.12", ip);
  333. std::vector<std::string> addrs;
  334. hosted_at(host, addrs);
  335. EXPECT_EQ(1u, addrs.size());
  336. }
  337. #if 0 // It depends on each test environment...
  338. TEST(HostnameToIPConversionTest, YouTube_Online) {
  339. auto host = "www.youtube.com";
  340. std::vector<std::string> addrs;
  341. hosted_at(host, addrs);
  342. EXPECT_EQ(20u, addrs.size());
  343. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  344. EXPECT_TRUE(it != addrs.end());
  345. }
  346. #endif
  347. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  348. auto host = "www.httpwatch.com";
  349. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  350. auto port = 443;
  351. SSLClient cli(host, port);
  352. #else
  353. auto port = 80;
  354. Client cli(host, port);
  355. #endif
  356. cli.set_connection_timeout(2);
  357. std::string body;
  358. auto res =
  359. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  360. [&](const char *data, size_t data_length) {
  361. body.append(data, data_length);
  362. return true;
  363. });
  364. ASSERT_TRUE(res);
  365. std::string out;
  366. detail::read_file("./image.jpg", out);
  367. EXPECT_EQ(200, res->status);
  368. EXPECT_EQ(out, body);
  369. }
  370. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  371. auto host = "www.httpwatch.com";
  372. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  373. auto port = 443;
  374. SSLClient cli(host, port);
  375. #else
  376. auto port = 80;
  377. Client cli(host, port);
  378. #endif
  379. cli.set_connection_timeout(2);
  380. std::string body;
  381. auto res = cli.Get(
  382. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  383. [&](const Response &response) {
  384. EXPECT_EQ(200, response.status);
  385. return true;
  386. },
  387. [&](const char *data, size_t data_length) {
  388. body.append(data, data_length);
  389. return true;
  390. });
  391. ASSERT_TRUE(res);
  392. std::string out;
  393. detail::read_file("./image.jpg", out);
  394. EXPECT_EQ(200, res->status);
  395. EXPECT_EQ(out, body);
  396. }
  397. TEST(RangeTest, FromHTTPBin_Online) {
  398. auto host = "httpbin.org";
  399. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  400. auto port = 443;
  401. SSLClient cli(host, port);
  402. #else
  403. auto port = 80;
  404. Client cli(host, port);
  405. #endif
  406. cli.set_connection_timeout(5);
  407. {
  408. auto res = cli.Get("/range/32");
  409. ASSERT_TRUE(res);
  410. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  411. EXPECT_EQ(200, res->status);
  412. }
  413. {
  414. Headers headers = {make_range_header({{1, -1}})};
  415. auto res = cli.Get("/range/32", headers);
  416. ASSERT_TRUE(res);
  417. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  418. EXPECT_EQ(206, res->status);
  419. }
  420. {
  421. Headers headers = {make_range_header({{1, 10}})};
  422. auto res = cli.Get("/range/32", headers);
  423. ASSERT_TRUE(res);
  424. EXPECT_EQ("bcdefghijk", res->body);
  425. EXPECT_EQ(206, res->status);
  426. }
  427. {
  428. Headers headers = {make_range_header({{0, 31}})};
  429. auto res = cli.Get("/range/32", headers);
  430. ASSERT_TRUE(res);
  431. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  432. EXPECT_EQ(200, res->status);
  433. }
  434. {
  435. Headers headers = {make_range_header({{0, -1}})};
  436. auto res = cli.Get("/range/32", headers);
  437. ASSERT_TRUE(res);
  438. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  439. EXPECT_EQ(200, res->status);
  440. }
  441. {
  442. Headers headers = {make_range_header({{0, 32}})};
  443. auto res = cli.Get("/range/32", headers);
  444. ASSERT_TRUE(res);
  445. EXPECT_EQ(416, res->status);
  446. }
  447. }
  448. TEST(ConnectionErrorTest, InvalidHost) {
  449. auto host = "-abcde.com";
  450. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  451. auto port = 443;
  452. SSLClient cli(host, port);
  453. #else
  454. auto port = 80;
  455. Client cli(host, port);
  456. #endif
  457. cli.set_connection_timeout(std::chrono::seconds(2));
  458. auto res = cli.Get("/");
  459. ASSERT_TRUE(!res);
  460. EXPECT_EQ(Error::Connection, res.error());
  461. }
  462. TEST(ConnectionErrorTest, InvalidHost2) {
  463. auto host = "httpbin.org/";
  464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  465. SSLClient cli(host);
  466. #else
  467. Client cli(host);
  468. #endif
  469. cli.set_connection_timeout(std::chrono::seconds(2));
  470. auto res = cli.Get("/");
  471. ASSERT_TRUE(!res);
  472. EXPECT_EQ(Error::Connection, res.error());
  473. }
  474. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  475. auto host = "httpbin.org/";
  476. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  477. SSLClient cli(host);
  478. #else
  479. Client cli(host);
  480. #endif
  481. cli.set_connection_timeout(std::chrono::seconds(2));
  482. auto res = cli.Get("/");
  483. ASSERT_TRUE(!res);
  484. stringstream s;
  485. s << "error code: " << res.error();
  486. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  487. }
  488. TEST(ConnectionErrorTest, InvalidPort) {
  489. auto host = "localhost";
  490. auto port = 44380;
  491. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  492. SSLClient cli(host, port);
  493. #else
  494. Client cli(host, port);
  495. #endif
  496. cli.set_connection_timeout(std::chrono::seconds(2));
  497. auto res = cli.Get("/");
  498. ASSERT_TRUE(!res);
  499. EXPECT_TRUE(Error::Connection == res.error() ||
  500. Error::ConnectionTimeout == res.error());
  501. }
  502. TEST(ConnectionErrorTest, Timeout_Online) {
  503. auto host = "google.com";
  504. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  505. auto port = 44380;
  506. SSLClient cli(host, port);
  507. #else
  508. auto port = 8080;
  509. Client cli(host, port);
  510. #endif
  511. cli.set_connection_timeout(std::chrono::seconds(2));
  512. // only probe one address type so that the error reason
  513. // correlates to the timed-out IPv4, not the unsupported
  514. // IPv6 connection attempt
  515. cli.set_address_family(AF_INET);
  516. auto res = cli.Get("/");
  517. ASSERT_TRUE(!res);
  518. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  519. }
  520. TEST(CancelTest, NoCancel_Online) {
  521. auto host = "httpbin.org";
  522. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  523. auto port = 443;
  524. SSLClient cli(host, port);
  525. #else
  526. auto port = 80;
  527. Client cli(host, port);
  528. #endif
  529. cli.set_connection_timeout(std::chrono::seconds(5));
  530. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return true; });
  531. ASSERT_TRUE(res);
  532. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  533. EXPECT_EQ(200, res->status);
  534. }
  535. TEST(CancelTest, WithCancelSmallPayload_Online) {
  536. auto host = "httpbin.org";
  537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  538. auto port = 443;
  539. SSLClient cli(host, port);
  540. #else
  541. auto port = 80;
  542. Client cli(host, port);
  543. #endif
  544. auto res = cli.Get("/range/32", [](uint64_t, uint64_t) { return false; });
  545. cli.set_connection_timeout(std::chrono::seconds(5));
  546. ASSERT_TRUE(!res);
  547. EXPECT_EQ(Error::Canceled, res.error());
  548. }
  549. TEST(CancelTest, WithCancelLargePayload_Online) {
  550. auto host = "httpbin.org";
  551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  552. auto port = 443;
  553. SSLClient cli(host, port);
  554. #else
  555. auto port = 80;
  556. Client cli(host, port);
  557. #endif
  558. cli.set_connection_timeout(std::chrono::seconds(5));
  559. uint32_t count = 0;
  560. auto res = cli.Get("/range/65536",
  561. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  562. ASSERT_TRUE(!res);
  563. EXPECT_EQ(Error::Canceled, res.error());
  564. }
  565. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  566. auto host = "httpbin.org";
  567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  568. auto port = 443;
  569. SSLClient cli(host, port);
  570. #else
  571. auto port = 80;
  572. Client cli(host, port);
  573. #endif
  574. {
  575. auto res = cli.Get("/basic-auth/hello/world");
  576. ASSERT_TRUE(res);
  577. EXPECT_EQ(401, res->status);
  578. }
  579. {
  580. auto res = cli.Get("/basic-auth/hello/world",
  581. {make_basic_authentication_header("hello", "world")});
  582. ASSERT_TRUE(res);
  583. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  584. res->body);
  585. EXPECT_EQ(200, res->status);
  586. }
  587. {
  588. cli.set_basic_auth("hello", "world");
  589. auto res = cli.Get("/basic-auth/hello/world");
  590. ASSERT_TRUE(res);
  591. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  592. res->body);
  593. EXPECT_EQ(200, res->status);
  594. }
  595. {
  596. cli.set_basic_auth("hello", "bad");
  597. auto res = cli.Get("/basic-auth/hello/world");
  598. ASSERT_TRUE(res);
  599. EXPECT_EQ(401, res->status);
  600. }
  601. {
  602. cli.set_basic_auth("bad", "world");
  603. auto res = cli.Get("/basic-auth/hello/world");
  604. ASSERT_TRUE(res);
  605. EXPECT_EQ(401, res->status);
  606. }
  607. }
  608. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  609. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  610. auto host = "httpbin.org";
  611. auto port = 443;
  612. SSLClient cli(host, port);
  613. {
  614. auto res = cli.Get("/digest-auth/auth/hello/world");
  615. ASSERT_TRUE(res);
  616. EXPECT_EQ(401, res->status);
  617. }
  618. {
  619. std::vector<std::string> paths = {
  620. "/digest-auth/auth/hello/world/MD5",
  621. "/digest-auth/auth/hello/world/SHA-256",
  622. "/digest-auth/auth/hello/world/SHA-512",
  623. "/digest-auth/auth-int/hello/world/MD5",
  624. };
  625. cli.set_digest_auth("hello", "world");
  626. for (auto path : paths) {
  627. auto res = cli.Get(path.c_str());
  628. ASSERT_TRUE(res);
  629. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  630. res->body);
  631. EXPECT_EQ(200, res->status);
  632. }
  633. cli.set_digest_auth("hello", "bad");
  634. for (auto path : paths) {
  635. auto res = cli.Get(path.c_str());
  636. ASSERT_TRUE(res);
  637. EXPECT_EQ(401, res->status);
  638. }
  639. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  640. // out. Plese see https://httpbin.org/digest-auth/auth/hello/world
  641. // cli.set_digest_auth("bad", "world");
  642. // for (auto path : paths) {
  643. // auto res = cli.Get(path.c_str());
  644. // ASSERT_TRUE(res);
  645. // EXPECT_EQ(400, res->status);
  646. // }
  647. }
  648. }
  649. #endif
  650. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  651. auto host = "google.com";
  652. auto another_host = "example.com";
  653. auto wrong_ip = "0.0.0.0";
  654. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  655. SSLClient cli(host);
  656. #else
  657. Client cli(host);
  658. #endif
  659. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  660. auto res = cli.Get("/");
  661. ASSERT_TRUE(res);
  662. ASSERT_EQ(301, res->status);
  663. }
  664. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  665. auto host = "google.com";
  666. auto wrong_ip = "0.0.0.0";
  667. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  668. SSLClient cli(host);
  669. #else
  670. Client cli(host);
  671. #endif
  672. cli.set_hostname_addr_map({{host, wrong_ip}});
  673. auto res = cli.Get("/");
  674. ASSERT_TRUE(!res);
  675. EXPECT_EQ(Error::Connection, res.error());
  676. }
  677. TEST(AbsoluteRedirectTest, Redirect_Online) {
  678. auto host = "nghttp2.org";
  679. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  680. SSLClient cli(host);
  681. #else
  682. Client cli(host);
  683. #endif
  684. cli.set_follow_location(true);
  685. auto res = cli.Get("/httpbin/absolute-redirect/3");
  686. ASSERT_TRUE(res);
  687. EXPECT_EQ(200, res->status);
  688. }
  689. TEST(RedirectTest, Redirect_Online) {
  690. auto host = "nghttp2.org";
  691. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  692. SSLClient cli(host);
  693. #else
  694. Client cli(host);
  695. #endif
  696. cli.set_follow_location(true);
  697. auto res = cli.Get("/httpbin/redirect/3");
  698. ASSERT_TRUE(res);
  699. EXPECT_EQ(200, res->status);
  700. }
  701. TEST(RelativeRedirectTest, Redirect_Online) {
  702. auto host = "nghttp2.org";
  703. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  704. SSLClient cli(host);
  705. #else
  706. Client cli(host);
  707. #endif
  708. cli.set_follow_location(true);
  709. auto res = cli.Get("/httpbin/relative-redirect/3");
  710. ASSERT_TRUE(res);
  711. EXPECT_EQ(200, res->status);
  712. }
  713. TEST(TooManyRedirectTest, Redirect_Online) {
  714. auto host = "nghttp2.org";
  715. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  716. SSLClient cli(host);
  717. #else
  718. Client cli(host);
  719. #endif
  720. cli.set_follow_location(true);
  721. auto res = cli.Get("/httpbin/redirect/21");
  722. ASSERT_TRUE(!res);
  723. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  724. }
  725. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  726. TEST(YahooRedirectTest, Redirect_Online) {
  727. Client cli("yahoo.com");
  728. auto res = cli.Get("/");
  729. ASSERT_TRUE(res);
  730. EXPECT_EQ(301, res->status);
  731. cli.set_follow_location(true);
  732. res = cli.Get("/");
  733. ASSERT_TRUE(res);
  734. EXPECT_EQ(200, res->status);
  735. EXPECT_EQ("https://yahoo.com/", res->location);
  736. }
  737. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  738. SSLClient cli("nghttp2.org");
  739. cli.set_follow_location(true);
  740. auto res = cli.Get(
  741. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  742. ASSERT_TRUE(res);
  743. EXPECT_EQ(200, res->status);
  744. }
  745. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  746. SSLClient cli("nghttp2.org");
  747. cli.set_follow_location(true);
  748. Params params;
  749. params.emplace("url", "http://www.google.com");
  750. params.emplace("status_code", "302");
  751. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  752. ASSERT_TRUE(res);
  753. EXPECT_EQ(200, res->status);
  754. }
  755. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  756. SSLClient cli("nghttp2.org");
  757. cli.set_follow_location(true);
  758. Params params;
  759. params.emplace("url", "http://www.google.com");
  760. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  761. ASSERT_TRUE(res);
  762. EXPECT_EQ(200, res->status);
  763. }
  764. TEST(UrlWithSpace, Redirect_Online) {
  765. SSLClient cli("edge.forgecdn.net");
  766. cli.set_follow_location(true);
  767. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  768. ASSERT_TRUE(res);
  769. EXPECT_EQ(200, res->status);
  770. EXPECT_EQ(18527U, res->get_header_value<uint64_t>("Content-Length"));
  771. }
  772. #endif
  773. #if !defined(_WIN32) && !defined(_WIN64)
  774. TEST(ReceiveSignals, Signal) {
  775. auto setupSignalHandlers = []() {
  776. struct sigaction act;
  777. sigemptyset(&act.sa_mask);
  778. act.sa_flags = SA_SIGINFO;
  779. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  780. switch (sig) {
  781. case SIGINT:
  782. default: break;
  783. }
  784. };
  785. ::sigaction(SIGINT, &act, nullptr);
  786. };
  787. Server svr;
  788. int port = 0;
  789. auto thread = std::thread([&]() {
  790. setupSignalHandlers();
  791. port = svr.bind_to_any_port("localhost");
  792. svr.listen_after_bind();
  793. });
  794. while (!svr.is_running()) {
  795. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  796. }
  797. ASSERT_TRUE(svr.is_running());
  798. pthread_kill(thread.native_handle(), SIGINT);
  799. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  800. ASSERT_TRUE(svr.is_running());
  801. svr.stop();
  802. thread.join();
  803. ASSERT_FALSE(svr.is_running());
  804. }
  805. #endif
  806. TEST(RedirectToDifferentPort, Redirect) {
  807. Server svr1;
  808. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  809. res.set_content("Hello World!", "text/plain");
  810. });
  811. int svr1_port = 0;
  812. auto thread1 = std::thread([&]() {
  813. svr1_port = svr1.bind_to_any_port("localhost");
  814. svr1.listen_after_bind();
  815. });
  816. Server svr2;
  817. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  818. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  819. });
  820. int svr2_port = 0;
  821. auto thread2 = std::thread([&]() {
  822. svr2_port = svr2.bind_to_any_port("localhost");
  823. svr2.listen_after_bind();
  824. });
  825. while (!svr1.is_running() || !svr2.is_running()) {
  826. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  827. }
  828. // Give GET time to get a few messages.
  829. std::this_thread::sleep_for(std::chrono::seconds(1));
  830. Client cli("localhost", svr2_port);
  831. cli.set_follow_location(true);
  832. auto res = cli.Get("/2");
  833. ASSERT_TRUE(res);
  834. EXPECT_EQ(200, res->status);
  835. EXPECT_EQ("Hello World!", res->body);
  836. svr1.stop();
  837. svr2.stop();
  838. thread1.join();
  839. thread2.join();
  840. ASSERT_FALSE(svr1.is_running());
  841. ASSERT_FALSE(svr2.is_running());
  842. }
  843. TEST(RedirectFromPageWithContent, Redirect) {
  844. Server svr;
  845. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  846. res.set_content("___", "text/plain");
  847. res.set_redirect("/2");
  848. });
  849. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  850. res.set_content("Hello World!", "text/plain");
  851. });
  852. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  853. while (!svr.is_running()) {
  854. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  855. }
  856. // Give GET time to get a few messages.
  857. std::this_thread::sleep_for(std::chrono::seconds(1));
  858. {
  859. Client cli("localhost", PORT);
  860. cli.set_follow_location(true);
  861. std::string body;
  862. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  863. body.append(data, data_length);
  864. return true;
  865. });
  866. ASSERT_TRUE(res);
  867. EXPECT_EQ(200, res->status);
  868. EXPECT_EQ("Hello World!", body);
  869. }
  870. {
  871. Client cli("localhost", PORT);
  872. std::string body;
  873. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  874. body.append(data, data_length);
  875. return true;
  876. });
  877. ASSERT_TRUE(res);
  878. EXPECT_EQ(302, res->status);
  879. EXPECT_EQ("___", body);
  880. }
  881. svr.stop();
  882. th.join();
  883. ASSERT_FALSE(svr.is_running());
  884. }
  885. TEST(RedirectFromPageWithContentIP6, Redirect) {
  886. Server svr;
  887. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  888. res.set_content("___", "text/plain");
  889. // res.set_redirect("/2");
  890. res.set_redirect("http://[::1]:1234/2");
  891. });
  892. svr.Get("/2", [&](const Request &req, Response &res) {
  893. auto host_header = req.headers.find("Host");
  894. ASSERT_TRUE(host_header != req.headers.end());
  895. EXPECT_EQ("[::1]:1234", host_header->second);
  896. res.set_content("Hello World!", "text/plain");
  897. });
  898. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  899. // When IPV6 support isn't available svr.listen("::1", 1234) never
  900. // actually starts anything, so the condition !svr.is_running() will
  901. // always remain true, and the loop never stops.
  902. // This basically counts how many milliseconds have passed since the
  903. // call to svr.listen(), and if after 5 seconds nothing started yet
  904. // aborts the test.
  905. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  906. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  907. ASSERT_LT(milliseconds, 5000U);
  908. }
  909. // Give GET time to get a few messages.
  910. std::this_thread::sleep_for(std::chrono::seconds(1));
  911. {
  912. Client cli("http://[::1]:1234");
  913. cli.set_follow_location(true);
  914. std::string body;
  915. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  916. body.append(data, data_length);
  917. return true;
  918. });
  919. ASSERT_TRUE(res);
  920. EXPECT_EQ(200, res->status);
  921. EXPECT_EQ("Hello World!", body);
  922. }
  923. {
  924. Client cli("http://[::1]:1234");
  925. std::string body;
  926. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  927. body.append(data, data_length);
  928. return true;
  929. });
  930. ASSERT_TRUE(res);
  931. EXPECT_EQ(302, res->status);
  932. EXPECT_EQ("___", body);
  933. }
  934. svr.stop();
  935. th.join();
  936. ASSERT_FALSE(svr.is_running());
  937. }
  938. TEST(PathUrlEncodeTest, PathUrlEncode) {
  939. Server svr;
  940. svr.Get("/foo", [](const Request &req, Response &res) {
  941. auto a = req.params.find("a");
  942. if (a != req.params.end()) {
  943. res.set_content((*a).second, "text/plain");
  944. res.status = 200;
  945. } else {
  946. res.status = 400;
  947. }
  948. });
  949. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  950. // Give GET time to get a few messages.
  951. std::this_thread::sleep_for(std::chrono::seconds(1));
  952. {
  953. Client cli(HOST, PORT);
  954. cli.set_url_encode(false);
  955. auto res = cli.Get("/foo?a=explicitly+encoded");
  956. ASSERT_TRUE(res);
  957. EXPECT_EQ(200, res->status);
  958. // This expects it back with a space, as the `+` won't have been
  959. // url-encoded, and server-side the params get decoded turning `+`
  960. // into spaces.
  961. EXPECT_EQ("explicitly encoded", res->body);
  962. }
  963. svr.stop();
  964. thread.join();
  965. ASSERT_FALSE(svr.is_running());
  966. }
  967. TEST(BindServerTest, BindDualStack) {
  968. Server svr;
  969. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  970. res.set_content("Hello World!", "text/plain");
  971. });
  972. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  973. // Give GET time to get a few messages.
  974. std::this_thread::sleep_for(std::chrono::seconds(1));
  975. {
  976. Client cli("127.0.0.1", PORT);
  977. auto res = cli.Get("/1");
  978. ASSERT_TRUE(res);
  979. EXPECT_EQ(200, res->status);
  980. EXPECT_EQ("Hello World!", res->body);
  981. }
  982. {
  983. Client cli("::1", PORT);
  984. auto res = cli.Get("/1");
  985. ASSERT_TRUE(res);
  986. EXPECT_EQ(200, res->status);
  987. EXPECT_EQ("Hello World!", res->body);
  988. }
  989. svr.stop();
  990. thread.join();
  991. ASSERT_FALSE(svr.is_running());
  992. }
  993. TEST(BindServerTest, BindAndListenSeparately) {
  994. Server svr;
  995. int port = svr.bind_to_any_port("0.0.0.0");
  996. ASSERT_TRUE(svr.is_valid());
  997. ASSERT_TRUE(port > 0);
  998. svr.stop();
  999. }
  1000. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1001. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1003. CLIENT_CA_CERT_DIR);
  1004. int port = svr.bind_to_any_port("0.0.0.0");
  1005. ASSERT_TRUE(svr.is_valid());
  1006. ASSERT_TRUE(port > 0);
  1007. svr.stop();
  1008. }
  1009. #endif
  1010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1011. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1012. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1013. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1014. int port = svr.bind_to_any_port("0.0.0.0");
  1015. ASSERT_TRUE(svr.is_valid());
  1016. ASSERT_TRUE(port > 0);
  1017. svr.stop();
  1018. }
  1019. #endif
  1020. TEST(ErrorHandlerTest, ContentLength) {
  1021. Server svr;
  1022. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1023. res.status = 200;
  1024. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1025. "text/html"); // <= Content-Length still 13
  1026. });
  1027. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1028. res.set_content("Hello World!\n", "text/plain");
  1029. res.status = 524;
  1030. });
  1031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1032. // Give GET time to get a few messages.
  1033. std::this_thread::sleep_for(std::chrono::seconds(1));
  1034. {
  1035. Client cli(HOST, PORT);
  1036. auto res = cli.Get("/hi");
  1037. ASSERT_TRUE(res);
  1038. EXPECT_EQ(200, res->status);
  1039. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1040. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1041. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1042. }
  1043. svr.stop();
  1044. thread.join();
  1045. ASSERT_FALSE(svr.is_running());
  1046. }
  1047. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1048. TEST(ExceptionHandlerTest, ContentLength) {
  1049. Server svr;
  1050. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1051. std::exception_ptr ep) {
  1052. EXPECT_FALSE(ep == nullptr);
  1053. try {
  1054. std::rethrow_exception(ep);
  1055. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1056. res.status = 500;
  1057. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1058. "text/html"); // <= Content-Length still 13 at this point
  1059. });
  1060. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1061. res.set_content("Hello World!\n", "text/plain");
  1062. throw std::runtime_error("abc");
  1063. });
  1064. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1065. // Give GET time to get a few messages.
  1066. std::this_thread::sleep_for(std::chrono::seconds(1));
  1067. for (size_t i = 0; i < 10; i++) {
  1068. Client cli(HOST, PORT);
  1069. for (size_t j = 0; j < 100; j++) {
  1070. auto res = cli.Get("/hi");
  1071. ASSERT_TRUE(res);
  1072. EXPECT_EQ(500, res->status);
  1073. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1074. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1075. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1076. }
  1077. cli.set_keep_alive(true);
  1078. for (size_t j = 0; j < 100; j++) {
  1079. auto res = cli.Get("/hi");
  1080. ASSERT_TRUE(res);
  1081. EXPECT_EQ(500, res->status);
  1082. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1083. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1084. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1085. }
  1086. }
  1087. svr.stop();
  1088. thread.join();
  1089. ASSERT_FALSE(svr.is_running());
  1090. }
  1091. #endif
  1092. TEST(NoContentTest, ContentLength) {
  1093. Server svr;
  1094. svr.Get("/hi",
  1095. [](const Request & /*req*/, Response &res) { res.status = 204; });
  1096. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1097. // Give GET time to get a few messages.
  1098. std::this_thread::sleep_for(std::chrono::seconds(1));
  1099. {
  1100. Client cli(HOST, PORT);
  1101. auto res = cli.Get("/hi");
  1102. ASSERT_TRUE(res);
  1103. EXPECT_EQ(204, res->status);
  1104. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1105. }
  1106. svr.stop();
  1107. thread.join();
  1108. ASSERT_FALSE(svr.is_running());
  1109. }
  1110. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1113. ASSERT_TRUE(svr.is_valid());
  1114. #else
  1115. Server svr;
  1116. #endif
  1117. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1118. if (req.path == "/routing_handler") {
  1119. res.set_header("PRE_ROUTING", "on");
  1120. res.set_content("Routing Handler", "text/plain");
  1121. return httplib::Server::HandlerResponse::Handled;
  1122. }
  1123. return httplib::Server::HandlerResponse::Unhandled;
  1124. });
  1125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1126. res.set_content("Error", "text/html");
  1127. });
  1128. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1129. if (req.path == "/routing_handler") {
  1130. res.set_header("POST_ROUTING", "on");
  1131. }
  1132. });
  1133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1134. res.set_content("Hello World!\n", "text/plain");
  1135. });
  1136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1137. // Give GET time to get a few messages.
  1138. std::this_thread::sleep_for(std::chrono::seconds(1));
  1139. {
  1140. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1141. SSLClient cli(HOST, PORT);
  1142. cli.enable_server_certificate_verification(false);
  1143. #else
  1144. Client cli(HOST, PORT);
  1145. #endif
  1146. auto res = cli.Get("/routing_handler");
  1147. ASSERT_TRUE(res);
  1148. EXPECT_EQ(200, res->status);
  1149. EXPECT_EQ("Routing Handler", res->body);
  1150. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1151. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1152. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1153. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1154. }
  1155. {
  1156. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1157. SSLClient cli(HOST, PORT);
  1158. cli.enable_server_certificate_verification(false);
  1159. #else
  1160. Client cli(HOST, PORT);
  1161. #endif
  1162. auto res = cli.Get("/hi");
  1163. ASSERT_TRUE(res);
  1164. EXPECT_EQ(200, res->status);
  1165. EXPECT_EQ("Hello World!\n", res->body);
  1166. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1167. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1168. }
  1169. {
  1170. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1171. SSLClient cli(HOST, PORT);
  1172. cli.enable_server_certificate_verification(false);
  1173. #else
  1174. Client cli(HOST, PORT);
  1175. #endif
  1176. auto res = cli.Get("/aaa");
  1177. ASSERT_TRUE(res);
  1178. EXPECT_EQ(404, res->status);
  1179. EXPECT_EQ("Error", res->body);
  1180. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1181. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1182. }
  1183. svr.stop();
  1184. thread.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. }
  1187. TEST(InvalidFormatTest, StatusCode) {
  1188. Server svr;
  1189. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1190. res.set_content("Hello World!\n", "text/plain");
  1191. res.status = 9999; // Status should be a three-digit code...
  1192. });
  1193. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1194. // Give GET time to get a few messages.
  1195. std::this_thread::sleep_for(std::chrono::seconds(1));
  1196. {
  1197. Client cli(HOST, PORT);
  1198. auto res = cli.Get("/hi");
  1199. ASSERT_FALSE(res);
  1200. }
  1201. svr.stop();
  1202. thread.join();
  1203. ASSERT_FALSE(svr.is_running());
  1204. }
  1205. TEST(URLFragmentTest, WithFragment) {
  1206. Server svr;
  1207. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1208. EXPECT_TRUE(req.target == "/hi");
  1209. });
  1210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1211. std::this_thread::sleep_for(std::chrono::seconds(1));
  1212. {
  1213. Client cli(HOST, PORT);
  1214. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1215. EXPECT_TRUE(res);
  1216. EXPECT_EQ(200, res->status);
  1217. res = cli.Get("/hi%23key1=val1=key2=val2");
  1218. EXPECT_TRUE(res);
  1219. EXPECT_EQ(404, res->status);
  1220. }
  1221. svr.stop();
  1222. thread.join();
  1223. ASSERT_FALSE(svr.is_running());
  1224. }
  1225. class ServerTest : public ::testing::Test {
  1226. protected:
  1227. ServerTest()
  1228. : cli_(HOST, PORT)
  1229. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1230. ,
  1231. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1232. #endif
  1233. {
  1234. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1235. cli_.enable_server_certificate_verification(false);
  1236. #endif
  1237. }
  1238. virtual void SetUp() {
  1239. svr_.set_mount_point("/", "./www");
  1240. svr_.set_mount_point("/mount", "./www2");
  1241. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1242. svr_.Get("/hi",
  1243. [&](const Request & /*req*/, Response &res) {
  1244. res.set_content("Hello World!", "text/plain");
  1245. })
  1246. .Get("/http_response_splitting",
  1247. [&](const Request & /*req*/, Response &res) {
  1248. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1249. EXPECT_EQ(0U, res.headers.size());
  1250. EXPECT_FALSE(res.has_header("a"));
  1251. res.set_header("a", "1\nSet-Cookie: a=1");
  1252. EXPECT_EQ(0U, res.headers.size());
  1253. EXPECT_FALSE(res.has_header("a"));
  1254. res.set_header("a", "1\rSet-Cookie: a=1");
  1255. EXPECT_EQ(0U, res.headers.size());
  1256. EXPECT_FALSE(res.has_header("a"));
  1257. res.set_header("a\r\nb", "0");
  1258. EXPECT_EQ(0U, res.headers.size());
  1259. EXPECT_FALSE(res.has_header("a"));
  1260. res.set_header("a\rb", "0");
  1261. EXPECT_EQ(0U, res.headers.size());
  1262. EXPECT_FALSE(res.has_header("a"));
  1263. res.set_header("a\nb", "0");
  1264. EXPECT_EQ(0U, res.headers.size());
  1265. EXPECT_FALSE(res.has_header("a"));
  1266. res.set_redirect("1\r\nSet-Cookie: a=1");
  1267. EXPECT_EQ(0U, res.headers.size());
  1268. EXPECT_FALSE(res.has_header("Location"));
  1269. })
  1270. .Get("/slow",
  1271. [&](const Request & /*req*/, Response &res) {
  1272. std::this_thread::sleep_for(std::chrono::seconds(2));
  1273. res.set_content("slow", "text/plain");
  1274. })
  1275. #if 0
  1276. .Post("/slowpost",
  1277. [&](const Request & /*req*/, Response &res) {
  1278. std::this_thread::sleep_for(std::chrono::seconds(2));
  1279. res.set_content("slow", "text/plain");
  1280. })
  1281. #endif
  1282. .Get("/remote_addr",
  1283. [&](const Request &req, Response &res) {
  1284. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1285. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1286. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1287. EXPECT_EQ(req.remote_port,
  1288. std::stoi(req.get_header_value("REMOTE_PORT")));
  1289. res.set_content(remote_addr.c_str(), "text/plain");
  1290. })
  1291. .Get("/local_addr",
  1292. [&](const Request &req, Response &res) {
  1293. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1294. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1295. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1296. auto local_port = req.get_header_value("LOCAL_PORT");
  1297. EXPECT_EQ(req.local_addr, local_addr);
  1298. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1299. res.set_content(local_addr.append(":").append(local_port),
  1300. "text/plain");
  1301. })
  1302. .Get("/endwith%",
  1303. [&](const Request & /*req*/, Response &res) {
  1304. res.set_content("Hello World!", "text/plain");
  1305. })
  1306. .Get("/a\\+\\+b",
  1307. [&](const Request &req, Response &res) {
  1308. ASSERT_TRUE(req.has_param("a +b"));
  1309. auto val = req.get_param_value("a +b");
  1310. res.set_content(val, "text/plain");
  1311. })
  1312. .Get("/", [&](const Request & /*req*/,
  1313. Response &res) { res.set_redirect("/hi"); })
  1314. .Post("/1", [](const Request & /*req*/,
  1315. Response &res) { res.set_redirect("/2", 303); })
  1316. .Get("/2",
  1317. [](const Request & /*req*/, Response &res) {
  1318. res.set_content("redirected.", "text/plain");
  1319. res.status = 200;
  1320. })
  1321. .Post("/person",
  1322. [&](const Request &req, Response &res) {
  1323. if (req.has_param("name") && req.has_param("note")) {
  1324. persons_[req.get_param_value("name")] =
  1325. req.get_param_value("note");
  1326. } else {
  1327. res.status = 400;
  1328. }
  1329. })
  1330. .Put("/person",
  1331. [&](const Request &req, Response &res) {
  1332. if (req.has_param("name") && req.has_param("note")) {
  1333. persons_[req.get_param_value("name")] =
  1334. req.get_param_value("note");
  1335. } else {
  1336. res.status = 400;
  1337. }
  1338. })
  1339. .Get("/person/(.*)",
  1340. [&](const Request &req, Response &res) {
  1341. string name = req.matches[1];
  1342. if (persons_.find(name) != persons_.end()) {
  1343. auto note = persons_[name];
  1344. res.set_content(note, "text/plain");
  1345. } else {
  1346. res.status = 404;
  1347. }
  1348. })
  1349. .Post("/x-www-form-urlencoded-json",
  1350. [&](const Request &req, Response &res) {
  1351. auto json = req.get_param_value("json");
  1352. ASSERT_EQ(JSON_DATA, json);
  1353. res.set_content(json, "appliation/json");
  1354. res.status = 200;
  1355. })
  1356. .Get("/streamed-chunked",
  1357. [&](const Request & /*req*/, Response &res) {
  1358. res.set_chunked_content_provider(
  1359. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1360. sink.os << "123";
  1361. sink.os << "456";
  1362. sink.os << "789";
  1363. sink.done();
  1364. return true;
  1365. });
  1366. })
  1367. .Get("/streamed-chunked2",
  1368. [&](const Request & /*req*/, Response &res) {
  1369. auto i = new int(0);
  1370. res.set_chunked_content_provider(
  1371. "text/plain",
  1372. [i](size_t /*offset*/, DataSink &sink) {
  1373. switch (*i) {
  1374. case 0: sink.os << "123"; break;
  1375. case 1: sink.os << "456"; break;
  1376. case 2: sink.os << "789"; break;
  1377. case 3: sink.done(); break;
  1378. }
  1379. (*i)++;
  1380. return true;
  1381. },
  1382. [i](bool success) {
  1383. EXPECT_TRUE(success);
  1384. delete i;
  1385. });
  1386. })
  1387. .Get("/streamed",
  1388. [&](const Request & /*req*/, Response &res) {
  1389. res.set_content_provider(
  1390. 6, "text/plain",
  1391. [](size_t offset, size_t /*length*/, DataSink &sink) {
  1392. sink.os << (offset < 3 ? "a" : "b");
  1393. return true;
  1394. });
  1395. })
  1396. .Get("/streamed-with-range",
  1397. [&](const Request & /*req*/, Response &res) {
  1398. auto data = new std::string("abcdefg");
  1399. res.set_content_provider(
  1400. data->size(), "text/plain",
  1401. [data](size_t offset, size_t length, DataSink &sink) {
  1402. size_t DATA_CHUNK_SIZE = 4;
  1403. const auto &d = *data;
  1404. auto out_len =
  1405. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  1406. auto ret =
  1407. sink.write(&d[static_cast<size_t>(offset)], out_len);
  1408. EXPECT_TRUE(ret);
  1409. return true;
  1410. },
  1411. [data](bool success) {
  1412. EXPECT_TRUE(success);
  1413. delete data;
  1414. });
  1415. })
  1416. .Get("/streamed-cancel",
  1417. [&](const Request & /*req*/, Response &res) {
  1418. res.set_content_provider(
  1419. size_t(-1), "text/plain",
  1420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  1421. sink.os << "data_chunk";
  1422. return true;
  1423. });
  1424. })
  1425. .Get("/with-range",
  1426. [&](const Request & /*req*/, Response &res) {
  1427. res.set_content("abcdefg", "text/plain");
  1428. })
  1429. .Post("/chunked",
  1430. [&](const Request &req, Response & /*res*/) {
  1431. EXPECT_EQ(req.body, "dechunked post body");
  1432. })
  1433. .Post("/large-chunked",
  1434. [&](const Request &req, Response & /*res*/) {
  1435. std::string expected(6 * 30 * 1024u, 'a');
  1436. EXPECT_EQ(req.body, expected);
  1437. })
  1438. .Post("/multipart",
  1439. [&](const Request &req, Response & /*res*/) {
  1440. EXPECT_EQ(6u, req.files.size());
  1441. ASSERT_TRUE(!req.has_file("???"));
  1442. ASSERT_TRUE(req.body.empty());
  1443. {
  1444. const auto &file = req.get_file_value("text1");
  1445. EXPECT_TRUE(file.filename.empty());
  1446. EXPECT_EQ("text default", file.content);
  1447. }
  1448. {
  1449. const auto &file = req.get_file_value("text2");
  1450. EXPECT_TRUE(file.filename.empty());
  1451. EXPECT_EQ("aωb", file.content);
  1452. }
  1453. {
  1454. const auto &file = req.get_file_value("file1");
  1455. EXPECT_EQ("hello.txt", file.filename);
  1456. EXPECT_EQ("text/plain", file.content_type);
  1457. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1458. }
  1459. {
  1460. const auto &file = req.get_file_value("file3");
  1461. EXPECT_TRUE(file.filename.empty());
  1462. EXPECT_EQ("application/octet-stream", file.content_type);
  1463. EXPECT_EQ(0u, file.content.size());
  1464. }
  1465. {
  1466. const auto &file = req.get_file_value("file4");
  1467. EXPECT_TRUE(file.filename.empty());
  1468. EXPECT_EQ(0u, file.content.size());
  1469. EXPECT_EQ("application/json tmp-string", file.content_type);
  1470. }
  1471. })
  1472. .Post("/multipart/multi_file_values",
  1473. [&](const Request &req, Response & /*res*/) {
  1474. EXPECT_EQ(5u, req.files.size());
  1475. ASSERT_TRUE(!req.has_file("???"));
  1476. ASSERT_TRUE(req.body.empty());
  1477. {
  1478. const auto &text_value = req.get_file_values("text");
  1479. EXPECT_EQ(text_value.size(), 1);
  1480. auto &text = text_value[0];
  1481. EXPECT_TRUE(text.filename.empty());
  1482. EXPECT_EQ("defalut text", text.content);
  1483. }
  1484. {
  1485. const auto &text1_values = req.get_file_values("multi_text1");
  1486. EXPECT_EQ(text1_values.size(), 2);
  1487. EXPECT_EQ("aaaaa", text1_values[0].content);
  1488. EXPECT_EQ("bbbbb", text1_values[1].content);
  1489. }
  1490. {
  1491. const auto &file1_values = req.get_file_values("multi_file1");
  1492. EXPECT_EQ(file1_values.size(), 2);
  1493. auto file1 = file1_values[0];
  1494. EXPECT_EQ(file1.filename, "hello.txt");
  1495. EXPECT_EQ(file1.content_type, "text/plain");
  1496. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  1497. auto file2 = file1_values[1];
  1498. EXPECT_EQ(file2.filename, "world.json");
  1499. EXPECT_EQ(file2.content_type, "application/json");
  1500. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  1501. }
  1502. })
  1503. .Post("/empty",
  1504. [&](const Request &req, Response &res) {
  1505. EXPECT_EQ(req.body, "");
  1506. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  1507. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1508. res.set_content("empty", "text/plain");
  1509. })
  1510. .Post("/empty-no-content-type",
  1511. [&](const Request &req, Response &res) {
  1512. EXPECT_EQ(req.body, "");
  1513. EXPECT_FALSE(req.has_header("Content-Type"));
  1514. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1515. res.set_content("empty-no-content-type", "text/plain");
  1516. })
  1517. .Post("/path-only",
  1518. [&](const Request &req, Response &res) {
  1519. EXPECT_EQ(req.body, "");
  1520. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1521. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1522. res.set_content("path-only", "text/plain");
  1523. })
  1524. .Post("/path-headers-only",
  1525. [&](const Request &req, Response &res) {
  1526. EXPECT_EQ(req.body, "");
  1527. EXPECT_EQ("", req.get_header_value("Content-Type"));
  1528. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1529. EXPECT_EQ("world", req.get_header_value("hello"));
  1530. EXPECT_EQ("world2", req.get_header_value("hello2"));
  1531. res.set_content("path-headers-only", "text/plain");
  1532. })
  1533. .Post("/post-large",
  1534. [&](const Request &req, Response &res) {
  1535. EXPECT_EQ(req.body, LARGE_DATA);
  1536. res.set_content(req.body, "text/plain");
  1537. })
  1538. .Put("/empty-no-content-type",
  1539. [&](const Request &req, Response &res) {
  1540. EXPECT_EQ(req.body, "");
  1541. EXPECT_FALSE(req.has_header("Content-Type"));
  1542. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  1543. res.set_content("empty-no-content-type", "text/plain");
  1544. })
  1545. .Put("/put",
  1546. [&](const Request &req, Response &res) {
  1547. EXPECT_EQ(req.body, "PUT");
  1548. res.set_content(req.body, "text/plain");
  1549. })
  1550. .Put("/put-large",
  1551. [&](const Request &req, Response &res) {
  1552. EXPECT_EQ(req.body, LARGE_DATA);
  1553. res.set_content(req.body, "text/plain");
  1554. })
  1555. .Patch("/patch",
  1556. [&](const Request &req, Response &res) {
  1557. EXPECT_EQ(req.body, "PATCH");
  1558. res.set_content(req.body, "text/plain");
  1559. })
  1560. .Delete("/delete",
  1561. [&](const Request & /*req*/, Response &res) {
  1562. res.set_content("DELETE", "text/plain");
  1563. })
  1564. .Delete("/delete-body",
  1565. [&](const Request &req, Response &res) {
  1566. EXPECT_EQ(req.body, "content");
  1567. res.set_content(req.body, "text/plain");
  1568. })
  1569. .Options(R"(\*)",
  1570. [&](const Request & /*req*/, Response &res) {
  1571. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  1572. })
  1573. .Get("/request-target",
  1574. [&](const Request &req, Response & /*res*/) {
  1575. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  1576. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  1577. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  1578. })
  1579. .Get("/long-query-value",
  1580. [&](const Request &req, Response & /*res*/) {
  1581. EXPECT_EQ(LONG_QUERY_URL, req.target);
  1582. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  1583. })
  1584. .Get("/array-param",
  1585. [&](const Request &req, Response & /*res*/) {
  1586. EXPECT_EQ(3u, req.get_param_value_count("array"));
  1587. EXPECT_EQ("value1", req.get_param_value("array", 0));
  1588. EXPECT_EQ("value2", req.get_param_value("array", 1));
  1589. EXPECT_EQ("value3", req.get_param_value("array", 2));
  1590. })
  1591. .Post("/validate-no-multiple-headers",
  1592. [&](const Request &req, Response & /*res*/) {
  1593. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  1594. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  1595. })
  1596. .Post("/content_receiver",
  1597. [&](const Request &req, Response &res,
  1598. const ContentReader &content_reader) {
  1599. if (req.is_multipart_form_data()) {
  1600. MultipartFormDataItems files;
  1601. content_reader(
  1602. [&](const MultipartFormData &file) {
  1603. files.push_back(file);
  1604. return true;
  1605. },
  1606. [&](const char *data, size_t data_length) {
  1607. files.back().content.append(data, data_length);
  1608. return true;
  1609. });
  1610. EXPECT_EQ(5u, files.size());
  1611. {
  1612. const auto &file = get_file_value(files, "text1");
  1613. EXPECT_TRUE(file.filename.empty());
  1614. EXPECT_EQ("text default", file.content);
  1615. }
  1616. {
  1617. const auto &file = get_file_value(files, "text2");
  1618. EXPECT_TRUE(file.filename.empty());
  1619. EXPECT_EQ("aωb", file.content);
  1620. }
  1621. {
  1622. const auto &file = get_file_value(files, "file1");
  1623. EXPECT_EQ("hello.txt", file.filename);
  1624. EXPECT_EQ("text/plain", file.content_type);
  1625. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  1626. }
  1627. {
  1628. const auto &file = get_file_value(files, "file3");
  1629. EXPECT_TRUE(file.filename.empty());
  1630. EXPECT_EQ("application/octet-stream", file.content_type);
  1631. EXPECT_EQ(0u, file.content.size());
  1632. }
  1633. } else {
  1634. std::string body;
  1635. content_reader([&](const char *data, size_t data_length) {
  1636. EXPECT_EQ(7U, data_length);
  1637. body.append(data, data_length);
  1638. return true;
  1639. });
  1640. EXPECT_EQ(body, "content");
  1641. res.set_content(body, "text/plain");
  1642. }
  1643. })
  1644. .Put("/content_receiver",
  1645. [&](const Request & /*req*/, Response &res,
  1646. const ContentReader &content_reader) {
  1647. std::string body;
  1648. content_reader([&](const char *data, size_t data_length) {
  1649. body.append(data, data_length);
  1650. return true;
  1651. });
  1652. EXPECT_EQ(body, "content");
  1653. res.set_content(body, "text/plain");
  1654. })
  1655. .Patch("/content_receiver",
  1656. [&](const Request & /*req*/, Response &res,
  1657. const ContentReader &content_reader) {
  1658. std::string body;
  1659. content_reader([&](const char *data, size_t data_length) {
  1660. body.append(data, data_length);
  1661. return true;
  1662. });
  1663. EXPECT_EQ(body, "content");
  1664. res.set_content(body, "text/plain");
  1665. })
  1666. .Post("/query-string-and-body",
  1667. [&](const Request &req, Response & /*res*/) {
  1668. ASSERT_TRUE(req.has_param("key"));
  1669. EXPECT_EQ(req.get_param_value("key"), "value");
  1670. EXPECT_EQ(req.body, "content");
  1671. })
  1672. .Get("/last-request",
  1673. [&](const Request &req, Response & /*res*/) {
  1674. EXPECT_EQ("close", req.get_header_value("Connection"));
  1675. })
  1676. .Get(R"(/redirect/(\d+))",
  1677. [&](const Request &req, Response &res) {
  1678. auto num = std::stoi(req.matches[1]) + 1;
  1679. std::string url = "/redirect/" + std::to_string(num);
  1680. res.set_redirect(url);
  1681. })
  1682. .Post("/binary",
  1683. [&](const Request &req, Response &res) {
  1684. EXPECT_EQ(4U, req.body.size());
  1685. EXPECT_EQ("application/octet-stream",
  1686. req.get_header_value("Content-Type"));
  1687. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1688. res.set_content(req.body, "application/octet-stream");
  1689. })
  1690. .Put("/binary",
  1691. [&](const Request &req, Response &res) {
  1692. EXPECT_EQ(4U, req.body.size());
  1693. EXPECT_EQ("application/octet-stream",
  1694. req.get_header_value("Content-Type"));
  1695. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1696. res.set_content(req.body, "application/octet-stream");
  1697. })
  1698. .Patch("/binary",
  1699. [&](const Request &req, Response &res) {
  1700. EXPECT_EQ(4U, req.body.size());
  1701. EXPECT_EQ("application/octet-stream",
  1702. req.get_header_value("Content-Type"));
  1703. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1704. res.set_content(req.body, "application/octet-stream");
  1705. })
  1706. .Delete("/binary",
  1707. [&](const Request &req, Response &res) {
  1708. EXPECT_EQ(4U, req.body.size());
  1709. EXPECT_EQ("application/octet-stream",
  1710. req.get_header_value("Content-Type"));
  1711. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  1712. res.set_content(req.body, "application/octet-stream");
  1713. })
  1714. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  1715. .Get("/compress",
  1716. [&](const Request & /*req*/, Response &res) {
  1717. res.set_content(
  1718. "12345678901234567890123456789012345678901234567890123456789"
  1719. "01234567890123456789012345678901234567890",
  1720. "text/plain");
  1721. })
  1722. .Get("/nocompress",
  1723. [&](const Request & /*req*/, Response &res) {
  1724. res.set_content(
  1725. "12345678901234567890123456789012345678901234567890123456789"
  1726. "01234567890123456789012345678901234567890",
  1727. "application/octet-stream");
  1728. })
  1729. .Post("/compress-multipart",
  1730. [&](const Request &req, Response & /*res*/) {
  1731. EXPECT_EQ(2u, req.files.size());
  1732. ASSERT_TRUE(!req.has_file("???"));
  1733. {
  1734. const auto &file = req.get_file_value("key1");
  1735. EXPECT_TRUE(file.filename.empty());
  1736. EXPECT_EQ("test", file.content);
  1737. }
  1738. {
  1739. const auto &file = req.get_file_value("key2");
  1740. EXPECT_TRUE(file.filename.empty());
  1741. EXPECT_EQ("--abcdefg123", file.content);
  1742. }
  1743. })
  1744. #endif
  1745. ;
  1746. persons_["john"] = "programmer";
  1747. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1748. while (!svr_.is_running()) {
  1749. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1750. }
  1751. }
  1752. virtual void TearDown() {
  1753. svr_.stop();
  1754. if (!request_threads_.empty()) {
  1755. std::this_thread::sleep_for(std::chrono::seconds(1));
  1756. for (auto &t : request_threads_) {
  1757. t.join();
  1758. }
  1759. }
  1760. t_.join();
  1761. }
  1762. map<string, string> persons_;
  1763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1764. SSLClient cli_;
  1765. SSLServer svr_;
  1766. #else
  1767. Client cli_;
  1768. Server svr_;
  1769. #endif
  1770. thread t_;
  1771. std::vector<thread> request_threads_;
  1772. };
  1773. TEST_F(ServerTest, GetMethod200) {
  1774. auto res = cli_.Get("/hi");
  1775. ASSERT_TRUE(res);
  1776. EXPECT_EQ("HTTP/1.1", res->version);
  1777. EXPECT_EQ(200, res->status);
  1778. EXPECT_EQ("OK", res->reason);
  1779. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1780. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1781. EXPECT_EQ("Hello World!", res->body);
  1782. }
  1783. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  1784. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  1785. ASSERT_TRUE(res);
  1786. EXPECT_EQ("HTTP/1.1", res->version);
  1787. EXPECT_EQ(200, res->status);
  1788. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1789. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  1790. EXPECT_EQ("Hello World!", res->body);
  1791. }
  1792. TEST_F(ServerTest, GetMethod302) {
  1793. auto res = cli_.Get("/");
  1794. ASSERT_TRUE(res);
  1795. EXPECT_EQ(302, res->status);
  1796. EXPECT_EQ("/hi", res->get_header_value("Location"));
  1797. }
  1798. TEST_F(ServerTest, GetMethod302Redirect) {
  1799. cli_.set_follow_location(true);
  1800. auto res = cli_.Get("/");
  1801. ASSERT_TRUE(res);
  1802. EXPECT_EQ(200, res->status);
  1803. EXPECT_EQ("Hello World!", res->body);
  1804. EXPECT_EQ("/hi", res->location);
  1805. }
  1806. TEST_F(ServerTest, GetMethod404) {
  1807. auto res = cli_.Get("/invalid");
  1808. ASSERT_TRUE(res);
  1809. EXPECT_EQ(404, res->status);
  1810. }
  1811. TEST_F(ServerTest, HeadMethod200) {
  1812. auto res = cli_.Head("/hi");
  1813. ASSERT_TRUE(res);
  1814. EXPECT_EQ(200, res->status);
  1815. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1816. EXPECT_TRUE(res->body.empty());
  1817. }
  1818. TEST_F(ServerTest, HeadMethod200Static) {
  1819. auto res = cli_.Head("/mount/dir/index.html");
  1820. ASSERT_TRUE(res);
  1821. EXPECT_EQ(200, res->status);
  1822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1823. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  1824. EXPECT_TRUE(res->body.empty());
  1825. }
  1826. TEST_F(ServerTest, HeadMethod404) {
  1827. auto res = cli_.Head("/invalid");
  1828. ASSERT_TRUE(res);
  1829. EXPECT_EQ(404, res->status);
  1830. EXPECT_TRUE(res->body.empty());
  1831. }
  1832. TEST_F(ServerTest, GetMethodPersonJohn) {
  1833. auto res = cli_.Get("/person/john");
  1834. ASSERT_TRUE(res);
  1835. EXPECT_EQ(200, res->status);
  1836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  1837. EXPECT_EQ("programmer", res->body);
  1838. }
  1839. TEST_F(ServerTest, PostMethod1) {
  1840. auto res = cli_.Get("/person/john1");
  1841. ASSERT_TRUE(res);
  1842. ASSERT_EQ(404, res->status);
  1843. res = cli_.Post("/person", "name=john1&note=coder",
  1844. "application/x-www-form-urlencoded");
  1845. ASSERT_TRUE(res);
  1846. ASSERT_EQ(200, res->status);
  1847. res = cli_.Get("/person/john1");
  1848. ASSERT_TRUE(res);
  1849. ASSERT_EQ(200, res->status);
  1850. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1851. ASSERT_EQ("coder", res->body);
  1852. }
  1853. TEST_F(ServerTest, PostMethod2) {
  1854. auto res = cli_.Get("/person/john2");
  1855. ASSERT_TRUE(res);
  1856. ASSERT_EQ(404, res->status);
  1857. Params params;
  1858. params.emplace("name", "john2");
  1859. params.emplace("note", "coder");
  1860. res = cli_.Post("/person", params);
  1861. ASSERT_TRUE(res);
  1862. ASSERT_EQ(200, res->status);
  1863. res = cli_.Get("/person/john2");
  1864. ASSERT_TRUE(res);
  1865. ASSERT_EQ(200, res->status);
  1866. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1867. ASSERT_EQ("coder", res->body);
  1868. }
  1869. TEST_F(ServerTest, PutMethod3) {
  1870. auto res = cli_.Get("/person/john3");
  1871. ASSERT_TRUE(res);
  1872. ASSERT_EQ(404, res->status);
  1873. Params params;
  1874. params.emplace("name", "john3");
  1875. params.emplace("note", "coder");
  1876. res = cli_.Put("/person", params);
  1877. ASSERT_TRUE(res);
  1878. ASSERT_EQ(200, res->status);
  1879. res = cli_.Get("/person/john3");
  1880. ASSERT_TRUE(res);
  1881. ASSERT_EQ(200, res->status);
  1882. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  1883. ASSERT_EQ("coder", res->body);
  1884. }
  1885. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  1886. Params params;
  1887. params.emplace("json", JSON_DATA);
  1888. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  1889. ASSERT_TRUE(res);
  1890. ASSERT_EQ(200, res->status);
  1891. ASSERT_EQ(JSON_DATA, res->body);
  1892. }
  1893. TEST_F(ServerTest, PostEmptyContent) {
  1894. auto res = cli_.Post("/empty", "", "text/plain");
  1895. ASSERT_TRUE(res);
  1896. ASSERT_EQ(200, res->status);
  1897. ASSERT_EQ("empty", res->body);
  1898. }
  1899. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  1900. auto res = cli_.Post("/empty-no-content-type");
  1901. ASSERT_TRUE(res);
  1902. ASSERT_EQ(200, res->status);
  1903. ASSERT_EQ("empty-no-content-type", res->body);
  1904. }
  1905. TEST_F(ServerTest, PostPathOnly) {
  1906. auto res = cli_.Post("/path-only");
  1907. ASSERT_TRUE(res);
  1908. ASSERT_EQ(200, res->status);
  1909. ASSERT_EQ("path-only", res->body);
  1910. }
  1911. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  1912. auto res = cli_.Post("/path-headers-only",
  1913. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  1914. ASSERT_TRUE(res);
  1915. ASSERT_EQ(200, res->status);
  1916. ASSERT_EQ("path-headers-only", res->body);
  1917. }
  1918. TEST_F(ServerTest, PostLarge) {
  1919. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  1920. ASSERT_TRUE(res);
  1921. ASSERT_EQ(200, res->status);
  1922. EXPECT_EQ(LARGE_DATA, res->body);
  1923. }
  1924. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  1925. auto res = cli_.Put("/empty-no-content-type");
  1926. ASSERT_TRUE(res);
  1927. ASSERT_EQ(200, res->status);
  1928. ASSERT_EQ("empty-no-content-type", res->body);
  1929. }
  1930. TEST_F(ServerTest, GetMethodDir) {
  1931. auto res = cli_.Get("/dir/");
  1932. ASSERT_TRUE(res);
  1933. EXPECT_EQ(200, res->status);
  1934. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1935. auto body = R"(<html>
  1936. <head>
  1937. </head>
  1938. <body>
  1939. <a href="/dir/test.html">Test</a>
  1940. <a href="/hi">hi</a>
  1941. </body>
  1942. </html>
  1943. )";
  1944. EXPECT_EQ(body, res->body);
  1945. }
  1946. TEST_F(ServerTest, GetMethodDirTest) {
  1947. auto res = cli_.Get("/dir/test.html");
  1948. ASSERT_TRUE(res);
  1949. EXPECT_EQ(200, res->status);
  1950. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1951. EXPECT_EQ("test.html", res->body);
  1952. }
  1953. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  1954. auto res = cli_.Get("/dir/../dir/test.html");
  1955. ASSERT_TRUE(res);
  1956. EXPECT_EQ(200, res->status);
  1957. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1958. EXPECT_EQ("test.html", res->body);
  1959. }
  1960. TEST_F(ServerTest, GetMethodInvalidPath) {
  1961. auto res = cli_.Get("/dir/../test.html");
  1962. ASSERT_TRUE(res);
  1963. EXPECT_EQ(404, res->status);
  1964. }
  1965. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  1966. auto res = cli_.Get("/../www/dir/test.html");
  1967. ASSERT_TRUE(res);
  1968. EXPECT_EQ(404, res->status);
  1969. }
  1970. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  1971. auto res = cli_.Get("/dir/../../www/dir/test.html");
  1972. ASSERT_TRUE(res);
  1973. EXPECT_EQ(404, res->status);
  1974. }
  1975. TEST_F(ServerTest, GetMethodDirMountTest) {
  1976. auto res = cli_.Get("/mount/dir/test.html");
  1977. ASSERT_TRUE(res);
  1978. EXPECT_EQ(200, res->status);
  1979. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1980. EXPECT_EQ("test.html", res->body);
  1981. }
  1982. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  1983. auto res = cli_.Get("/mount/dir/../dir/test.html");
  1984. ASSERT_TRUE(res);
  1985. EXPECT_EQ(200, res->status);
  1986. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1987. EXPECT_EQ("test.html", res->body);
  1988. }
  1989. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  1990. auto res = cli_.Get("/mount/dir/../test.html");
  1991. ASSERT_TRUE(res);
  1992. EXPECT_EQ(404, res->status);
  1993. }
  1994. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  1995. auto res = cli_.Get("/mount/../www2/dir/test.html");
  1996. ASSERT_TRUE(res);
  1997. EXPECT_EQ(404, res->status);
  1998. }
  1999. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2000. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2001. ASSERT_TRUE(res);
  2002. EXPECT_EQ(404, res->status);
  2003. }
  2004. TEST_F(ServerTest, PostMethod303) {
  2005. auto res = cli_.Post("/1", "body", "text/plain");
  2006. ASSERT_TRUE(res);
  2007. EXPECT_EQ(303, res->status);
  2008. EXPECT_EQ("/2", res->get_header_value("Location"));
  2009. }
  2010. TEST_F(ServerTest, PostMethod303Redirect) {
  2011. cli_.set_follow_location(true);
  2012. auto res = cli_.Post("/1", "body", "text/plain");
  2013. ASSERT_TRUE(res);
  2014. EXPECT_EQ(200, res->status);
  2015. EXPECT_EQ("redirected.", res->body);
  2016. EXPECT_EQ("/2", res->location);
  2017. }
  2018. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2019. auto res = cli_.Get("/dir/test.abcde");
  2020. ASSERT_TRUE(res);
  2021. EXPECT_EQ(200, res->status);
  2022. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2023. EXPECT_EQ("abcde", res->body);
  2024. }
  2025. TEST_F(ServerTest, StaticFileRange) {
  2026. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2027. ASSERT_TRUE(res);
  2028. EXPECT_EQ(206, res->status);
  2029. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2030. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2031. EXPECT_EQ(true, res->has_header("Content-Range"));
  2032. EXPECT_EQ(std::string("cd"), res->body);
  2033. }
  2034. TEST_F(ServerTest, InvalidBaseDirMount) {
  2035. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2036. }
  2037. TEST_F(ServerTest, Binary) {
  2038. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2039. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2040. "application/octet-stream");
  2041. ASSERT_TRUE(res);
  2042. ASSERT_EQ(200, res->status);
  2043. ASSERT_EQ(4U, res->body.size());
  2044. res = cli_.Put("/binary", binary.data(), binary.size(),
  2045. "application/octet-stream");
  2046. ASSERT_TRUE(res);
  2047. ASSERT_EQ(200, res->status);
  2048. ASSERT_EQ(4U, res->body.size());
  2049. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2050. "application/octet-stream");
  2051. ASSERT_TRUE(res);
  2052. ASSERT_EQ(200, res->status);
  2053. ASSERT_EQ(4U, res->body.size());
  2054. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2055. "application/octet-stream");
  2056. ASSERT_TRUE(res);
  2057. ASSERT_EQ(200, res->status);
  2058. ASSERT_EQ(4U, res->body.size());
  2059. }
  2060. TEST_F(ServerTest, BinaryString) {
  2061. auto binary = std::string("\x00\x01\x02\x03", 4);
  2062. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2063. ASSERT_TRUE(res);
  2064. ASSERT_EQ(200, res->status);
  2065. ASSERT_EQ(4U, res->body.size());
  2066. res = cli_.Put("/binary", binary, "application/octet-stream");
  2067. ASSERT_TRUE(res);
  2068. ASSERT_EQ(200, res->status);
  2069. ASSERT_EQ(4U, res->body.size());
  2070. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2071. ASSERT_TRUE(res);
  2072. ASSERT_EQ(200, res->status);
  2073. ASSERT_EQ(4U, res->body.size());
  2074. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2075. ASSERT_TRUE(res);
  2076. ASSERT_EQ(200, res->status);
  2077. ASSERT_EQ(4U, res->body.size());
  2078. }
  2079. TEST_F(ServerTest, EmptyRequest) {
  2080. auto res = cli_.Get("");
  2081. ASSERT_TRUE(!res);
  2082. EXPECT_EQ(Error::Connection, res.error());
  2083. }
  2084. TEST_F(ServerTest, LongRequest) {
  2085. std::string request;
  2086. for (size_t i = 0; i < 545; i++) {
  2087. request += "/TooLongRequest";
  2088. }
  2089. request += "OK";
  2090. auto res = cli_.Get(request.c_str());
  2091. ASSERT_TRUE(res);
  2092. EXPECT_EQ(404, res->status);
  2093. }
  2094. TEST_F(ServerTest, TooLongRequest) {
  2095. std::string request;
  2096. for (size_t i = 0; i < 545; i++) {
  2097. request += "/TooLongRequest";
  2098. }
  2099. request += "_NG";
  2100. auto res = cli_.Get(request.c_str());
  2101. ASSERT_TRUE(res);
  2102. EXPECT_EQ(414, res->status);
  2103. }
  2104. TEST_F(ServerTest, LongHeader) {
  2105. Request req;
  2106. req.method = "GET";
  2107. req.path = "/hi";
  2108. std::string host_and_port;
  2109. host_and_port += HOST;
  2110. host_and_port += ":";
  2111. host_and_port += std::to_string(PORT);
  2112. req.headers.emplace("Host", host_and_port.c_str());
  2113. req.headers.emplace("Accept", "*/*");
  2114. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2115. req.headers.emplace(
  2116. "Header-Name",
  2117. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2118. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2119. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2120. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2121. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2122. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2123. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2145. "@@@@@@@@@@@@@@@@");
  2146. auto res = std::make_shared<Response>();
  2147. auto error = Error::Success;
  2148. auto ret = cli_.send(req, *res, error);
  2149. ASSERT_TRUE(ret);
  2150. EXPECT_EQ(200, res->status);
  2151. }
  2152. TEST_F(ServerTest, LongQueryValue) {
  2153. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2154. ASSERT_TRUE(res);
  2155. EXPECT_EQ(414, res->status);
  2156. }
  2157. TEST_F(ServerTest, TooLongHeader) {
  2158. Request req;
  2159. req.method = "GET";
  2160. req.path = "/hi";
  2161. std::string host_and_port;
  2162. host_and_port += HOST;
  2163. host_and_port += ":";
  2164. host_and_port += std::to_string(PORT);
  2165. req.headers.emplace("Host", host_and_port.c_str());
  2166. req.headers.emplace("Accept", "*/*");
  2167. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2168. req.headers.emplace(
  2169. "Header-Name",
  2170. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2171. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2172. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2173. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2174. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2175. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2176. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2177. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2178. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2198. "@@@@@@@@@@@@@@@@@");
  2199. auto res = std::make_shared<Response>();
  2200. auto error = Error::Success;
  2201. auto ret = cli_.send(req, *res, error);
  2202. ASSERT_TRUE(ret);
  2203. EXPECT_EQ(200, res->status);
  2204. }
  2205. TEST_F(ServerTest, PercentEncoding) {
  2206. auto res = cli_.Get("/e%6edwith%");
  2207. ASSERT_TRUE(res);
  2208. EXPECT_EQ(200, res->status);
  2209. }
  2210. TEST_F(ServerTest, PercentEncodingUnicode) {
  2211. auto res = cli_.Get("/e%u006edwith%");
  2212. ASSERT_TRUE(res);
  2213. EXPECT_EQ(200, res->status);
  2214. }
  2215. TEST_F(ServerTest, InvalidPercentEncoding) {
  2216. auto res = cli_.Get("/%endwith%");
  2217. ASSERT_TRUE(res);
  2218. EXPECT_EQ(404, res->status);
  2219. }
  2220. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2221. auto res = cli_.Get("/%uendwith%");
  2222. ASSERT_TRUE(res);
  2223. EXPECT_EQ(404, res->status);
  2224. }
  2225. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2226. auto res = cli_.Get("/hello?aaa=bbb%");
  2227. ASSERT_TRUE(res);
  2228. EXPECT_EQ(404, res->status);
  2229. }
  2230. TEST_F(ServerTest, PlusSignEncoding) {
  2231. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2232. ASSERT_TRUE(res);
  2233. EXPECT_EQ(200, res->status);
  2234. EXPECT_EQ("a +b", res->body);
  2235. }
  2236. TEST_F(ServerTest, MultipartFormData) {
  2237. MultipartFormDataItems items = {
  2238. {"text1", "text default", "", ""},
  2239. {"text2", "aωb", "", ""},
  2240. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2241. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2242. {"file3", "", "", "application/octet-stream"},
  2243. {"file4", "", "", " application/json tmp-string "}};
  2244. auto res = cli_.Post("/multipart", items);
  2245. ASSERT_TRUE(res);
  2246. EXPECT_EQ(200, res->status);
  2247. }
  2248. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2249. MultipartFormDataItems items = {
  2250. {"text", "defalut text", "", ""},
  2251. {"multi_text1", "aaaaa", "", ""},
  2252. {"multi_text1", "bbbbb", "", ""},
  2253. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2254. {"multi_file1", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2255. };
  2256. auto res = cli_.Post("/multipart/multi_file_values", items);
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(200, res->status);
  2259. }
  2260. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2261. auto res = cli_.Get("/hi");
  2262. ASSERT_TRUE(res);
  2263. EXPECT_EQ(200, res->status);
  2264. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2265. EXPECT_EQ("Hello World!", res->body);
  2266. }
  2267. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2268. Request req;
  2269. req.method = "POST";
  2270. req.path = "/chunked";
  2271. std::string host_and_port;
  2272. host_and_port += HOST;
  2273. host_and_port += ":";
  2274. host_and_port += std::to_string(PORT);
  2275. req.headers.emplace("Host", host_and_port.c_str());
  2276. req.headers.emplace("Accept", "*/*");
  2277. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2278. req.headers.emplace("Content-Type", "text/plain");
  2279. req.headers.emplace("Content-Length", "0");
  2280. req.headers.emplace(
  2281. "Transfer-Encoding",
  2282. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  2283. // Client does not chunk, so make a chunked body manually.
  2284. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  2285. auto res = std::make_shared<Response>();
  2286. auto error = Error::Success;
  2287. auto ret = cli_.send(req, *res, error);
  2288. ASSERT_TRUE(ret);
  2289. EXPECT_EQ(200, res->status);
  2290. }
  2291. TEST_F(ServerTest, GetStreamed2) {
  2292. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  2293. ASSERT_TRUE(res);
  2294. EXPECT_EQ(206, res->status);
  2295. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2296. EXPECT_EQ(std::string("ab"), res->body);
  2297. }
  2298. TEST_F(ServerTest, GetStreamed) {
  2299. auto res = cli_.Get("/streamed");
  2300. ASSERT_TRUE(res);
  2301. EXPECT_EQ(200, res->status);
  2302. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2303. EXPECT_EQ(std::string("aaabbb"), res->body);
  2304. }
  2305. TEST_F(ServerTest, GetStreamedWithRange1) {
  2306. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  2307. ASSERT_TRUE(res);
  2308. EXPECT_EQ(206, res->status);
  2309. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2310. EXPECT_EQ(true, res->has_header("Content-Range"));
  2311. EXPECT_EQ(std::string("def"), res->body);
  2312. }
  2313. TEST_F(ServerTest, GetStreamedWithRange2) {
  2314. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  2315. ASSERT_TRUE(res);
  2316. EXPECT_EQ(206, res->status);
  2317. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2318. EXPECT_EQ(true, res->has_header("Content-Range"));
  2319. EXPECT_EQ(std::string("bcdefg"), res->body);
  2320. }
  2321. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  2322. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  2323. ASSERT_TRUE(res);
  2324. EXPECT_EQ(206, res->status);
  2325. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2326. EXPECT_EQ(true, res->has_header("Content-Range"));
  2327. EXPECT_EQ(std::string("efg"), res->body);
  2328. }
  2329. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  2330. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-9999"}});
  2331. ASSERT_TRUE(res);
  2332. EXPECT_EQ(206, res->status);
  2333. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2334. EXPECT_EQ(true, res->has_header("Content-Range"));
  2335. EXPECT_EQ(std::string("abcdefg"), res->body);
  2336. }
  2337. TEST_F(ServerTest, GetStreamedWithRangeError) {
  2338. auto res = cli_.Get("/streamed-with-range",
  2339. {{"Range", "bytes=92233720368547758079223372036854775806-"
  2340. "92233720368547758079223372036854775807"}});
  2341. ASSERT_TRUE(res);
  2342. EXPECT_EQ(416, res->status);
  2343. }
  2344. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  2345. auto res =
  2346. cli_.Get("/with-range", {{"Range", "bytes=0-9223372036854775807"}});
  2347. EXPECT_EQ(206, res->status);
  2348. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  2349. EXPECT_EQ(true, res->has_header("Content-Range"));
  2350. EXPECT_EQ(std::string("abcdefg"), res->body);
  2351. }
  2352. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  2353. auto res =
  2354. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2355. ASSERT_TRUE(res);
  2356. EXPECT_EQ(206, res->status);
  2357. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2358. EXPECT_EQ(false, res->has_header("Content-Range"));
  2359. EXPECT_EQ(269U, res->body.size());
  2360. }
  2361. TEST_F(ServerTest, GetStreamedEndless) {
  2362. uint64_t offset = 0;
  2363. auto res = cli_.Get("/streamed-cancel",
  2364. [&](const char * /*data*/, uint64_t data_length) {
  2365. if (offset < 100) {
  2366. offset += data_length;
  2367. return true;
  2368. }
  2369. return false;
  2370. });
  2371. ASSERT_TRUE(!res);
  2372. EXPECT_EQ(Error::Canceled, res.error());
  2373. }
  2374. TEST_F(ServerTest, ClientStop) {
  2375. std::vector<std::thread> threads;
  2376. for (auto i = 0; i < 3; i++) {
  2377. threads.emplace_back(thread([&]() {
  2378. auto res = cli_.Get("/streamed-cancel",
  2379. [&](const char *, uint64_t) { return true; });
  2380. ASSERT_TRUE(!res);
  2381. EXPECT_TRUE(res.error() == Error::Canceled ||
  2382. res.error() == Error::Read || res.error() == Error::Write);
  2383. }));
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(2));
  2386. while (cli_.is_socket_open()) {
  2387. cli_.stop();
  2388. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2389. }
  2390. for (auto &t : threads) {
  2391. t.join();
  2392. }
  2393. }
  2394. TEST_F(ServerTest, GetWithRange1) {
  2395. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2396. ASSERT_TRUE(res);
  2397. EXPECT_EQ(206, res->status);
  2398. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2399. EXPECT_EQ(true, res->has_header("Content-Range"));
  2400. EXPECT_EQ(std::string("def"), res->body);
  2401. }
  2402. TEST_F(ServerTest, GetWithRange2) {
  2403. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2404. ASSERT_TRUE(res);
  2405. EXPECT_EQ(206, res->status);
  2406. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2407. EXPECT_EQ(true, res->has_header("Content-Range"));
  2408. EXPECT_EQ(std::string("bcdefg"), res->body);
  2409. }
  2410. TEST_F(ServerTest, GetWithRange3) {
  2411. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2412. ASSERT_TRUE(res);
  2413. EXPECT_EQ(206, res->status);
  2414. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2415. EXPECT_EQ(true, res->has_header("Content-Range"));
  2416. EXPECT_EQ(std::string("a"), res->body);
  2417. }
  2418. TEST_F(ServerTest, GetWithRange4) {
  2419. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2420. ASSERT_TRUE(res);
  2421. EXPECT_EQ(206, res->status);
  2422. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2423. EXPECT_EQ(true, res->has_header("Content-Range"));
  2424. EXPECT_EQ(std::string("fg"), res->body);
  2425. }
  2426. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2427. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2428. ASSERT_TRUE(res);
  2429. EXPECT_EQ(416, res->status);
  2430. }
  2431. TEST_F(ServerTest, GetWithRangeMultipart) {
  2432. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2433. ASSERT_TRUE(res);
  2434. EXPECT_EQ(206, res->status);
  2435. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2436. EXPECT_EQ(false, res->has_header("Content-Range"));
  2437. EXPECT_EQ(269U, res->body.size());
  2438. }
  2439. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2440. auto res =
  2441. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2442. ASSERT_TRUE(res);
  2443. EXPECT_EQ(416, res->status);
  2444. }
  2445. TEST_F(ServerTest, GetStreamedChunked) {
  2446. auto res = cli_.Get("/streamed-chunked");
  2447. ASSERT_TRUE(res);
  2448. EXPECT_EQ(200, res->status);
  2449. EXPECT_EQ(std::string("123456789"), res->body);
  2450. }
  2451. TEST_F(ServerTest, GetStreamedChunked2) {
  2452. auto res = cli_.Get("/streamed-chunked2");
  2453. ASSERT_TRUE(res);
  2454. EXPECT_EQ(200, res->status);
  2455. EXPECT_EQ(std::string("123456789"), res->body);
  2456. }
  2457. TEST_F(ServerTest, LargeChunkedPost) {
  2458. Request req;
  2459. req.method = "POST";
  2460. req.path = "/large-chunked";
  2461. std::string host_and_port;
  2462. host_and_port += HOST;
  2463. host_and_port += ":";
  2464. host_and_port += std::to_string(PORT);
  2465. req.headers.emplace("Host", host_and_port.c_str());
  2466. req.headers.emplace("Accept", "*/*");
  2467. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2468. req.headers.emplace("Content-Type", "text/plain");
  2469. req.headers.emplace("Content-Length", "0");
  2470. req.headers.emplace("Transfer-Encoding", "chunked");
  2471. std::string long_string(30 * 1024u, 'a');
  2472. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2473. // Attempt to make a large enough post to exceed OS buffers, to test that
  2474. // the server handles short reads if the full chunk data isn't available.
  2475. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2476. auto res = std::make_shared<Response>();
  2477. auto error = Error::Success;
  2478. auto ret = cli_.send(req, *res, error);
  2479. ASSERT_TRUE(ret);
  2480. EXPECT_EQ(200, res->status);
  2481. }
  2482. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2483. auto res = cli_.Get("/remote_addr");
  2484. ASSERT_TRUE(res);
  2485. EXPECT_EQ(200, res->status);
  2486. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2487. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2488. }
  2489. TEST_F(ServerTest, GetMethodLocalAddr) {
  2490. auto res = cli_.Get("/local_addr");
  2491. ASSERT_TRUE(res);
  2492. EXPECT_EQ(200, res->status);
  2493. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2494. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2495. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2496. }
  2497. TEST_F(ServerTest, HTTPResponseSplitting) {
  2498. auto res = cli_.Get("/http_response_splitting");
  2499. ASSERT_TRUE(res);
  2500. EXPECT_EQ(200, res->status);
  2501. }
  2502. TEST_F(ServerTest, SlowRequest) {
  2503. request_threads_.push_back(
  2504. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2505. request_threads_.push_back(
  2506. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2507. request_threads_.push_back(
  2508. std::thread([=]() { auto res = cli_.Get("/slow"); }));
  2509. }
  2510. #if 0
  2511. TEST_F(ServerTest, SlowPost) {
  2512. char buffer[64 * 1024];
  2513. memset(buffer, 0x42, sizeof(buffer));
  2514. auto res = cli_.Post(
  2515. "/slowpost", 64 * 1024 * 1024,
  2516. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2517. auto ret = sink.write(buffer, sizeof(buffer));
  2518. EXPECT_TRUE(ret);
  2519. return true;
  2520. },
  2521. "text/plain");
  2522. ASSERT_TRUE(res);
  2523. EXPECT_EQ(200, res->status);
  2524. }
  2525. TEST_F(ServerTest, SlowPostFail) {
  2526. char buffer[64 * 1024];
  2527. memset(buffer, 0x42, sizeof(buffer));
  2528. cli_.set_write_timeout(std::chrono::seconds(0));
  2529. auto res = cli_.Post(
  2530. "/slowpost", 64 * 1024 * 1024,
  2531. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2532. sink.write(buffer, sizeof(buffer));
  2533. return true;
  2534. },
  2535. "text/plain");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::Write, res.error());
  2538. }
  2539. #endif
  2540. TEST_F(ServerTest, Put) {
  2541. auto res = cli_.Put("/put", "PUT", "text/plain");
  2542. ASSERT_TRUE(res);
  2543. EXPECT_EQ(200, res->status);
  2544. EXPECT_EQ("PUT", res->body);
  2545. }
  2546. TEST_F(ServerTest, PutWithContentProvider) {
  2547. auto res = cli_.Put(
  2548. "/put", 3,
  2549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2550. sink.os << "PUT";
  2551. return true;
  2552. },
  2553. "text/plain");
  2554. ASSERT_TRUE(res);
  2555. EXPECT_EQ(200, res->status);
  2556. EXPECT_EQ("PUT", res->body);
  2557. }
  2558. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2559. auto res = cli_.Post(
  2560. "/post", 42,
  2561. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2562. return false;
  2563. },
  2564. "text/plain");
  2565. ASSERT_TRUE(!res);
  2566. EXPECT_EQ(Error::Canceled, res.error());
  2567. }
  2568. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2569. auto res = cli_.Put(
  2570. "/put",
  2571. [](size_t /*offset*/, DataSink &sink) {
  2572. sink.os << "PUT";
  2573. sink.done();
  2574. return true;
  2575. },
  2576. "text/plain");
  2577. ASSERT_TRUE(res);
  2578. EXPECT_EQ(200, res->status);
  2579. EXPECT_EQ("PUT", res->body);
  2580. }
  2581. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2582. auto res = cli_.Post(
  2583. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2584. "text/plain");
  2585. ASSERT_TRUE(!res);
  2586. EXPECT_EQ(Error::Canceled, res.error());
  2587. }
  2588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2589. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2590. cli_.set_compress(true);
  2591. auto res = cli_.Put(
  2592. "/put", 3,
  2593. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2594. sink.os << "PUT";
  2595. return true;
  2596. },
  2597. "text/plain");
  2598. ASSERT_TRUE(res);
  2599. EXPECT_EQ(200, res->status);
  2600. EXPECT_EQ("PUT", res->body);
  2601. }
  2602. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2603. cli_.set_compress(true);
  2604. auto res = cli_.Post(
  2605. "/post", 42,
  2606. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2607. return false;
  2608. },
  2609. "text/plain");
  2610. ASSERT_TRUE(!res);
  2611. EXPECT_EQ(Error::Canceled, res.error());
  2612. }
  2613. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2614. cli_.set_compress(true);
  2615. auto res = cli_.Put(
  2616. "/put",
  2617. [](size_t /*offset*/, DataSink &sink) {
  2618. sink.os << "PUT";
  2619. sink.done();
  2620. return true;
  2621. },
  2622. "text/plain");
  2623. ASSERT_TRUE(res);
  2624. EXPECT_EQ(200, res->status);
  2625. EXPECT_EQ("PUT", res->body);
  2626. }
  2627. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2628. cli_.set_compress(true);
  2629. auto res = cli_.Post(
  2630. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2631. "text/plain");
  2632. ASSERT_TRUE(!res);
  2633. EXPECT_EQ(Error::Canceled, res.error());
  2634. }
  2635. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2636. cli_.set_compress(true);
  2637. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2638. ASSERT_TRUE(res);
  2639. EXPECT_EQ(200, res->status);
  2640. EXPECT_EQ(LARGE_DATA, res->body);
  2641. }
  2642. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2643. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2644. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2645. Client cli(s.c_str());
  2646. cli.enable_server_certificate_verification(false);
  2647. #else
  2648. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2649. Client cli(s.c_str());
  2650. #endif
  2651. cli.set_compress(true);
  2652. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2653. ASSERT_TRUE(res);
  2654. EXPECT_EQ(200, res->status);
  2655. EXPECT_EQ(LARGE_DATA, res->body);
  2656. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2657. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2658. }
  2659. TEST_F(ServerTest, PutContentWithDeflate) {
  2660. cli_.set_compress(false);
  2661. Headers headers;
  2662. headers.emplace("Content-Encoding", "deflate");
  2663. // PUT in deflate format:
  2664. auto res = cli_.Put("/put", headers,
  2665. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(200, res->status);
  2668. EXPECT_EQ("PUT", res->body);
  2669. }
  2670. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2671. Headers headers;
  2672. headers.emplace("Accept-Encoding", "gzip, deflate");
  2673. auto res = cli_.Get("/streamed-chunked", headers);
  2674. ASSERT_TRUE(res);
  2675. EXPECT_EQ(200, res->status);
  2676. EXPECT_EQ(std::string("123456789"), res->body);
  2677. }
  2678. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2679. Headers headers;
  2680. headers.emplace("Accept-Encoding", "gzip, deflate");
  2681. auto res = cli_.Get("/streamed-chunked2", headers);
  2682. ASSERT_TRUE(res);
  2683. EXPECT_EQ(200, res->status);
  2684. EXPECT_EQ(std::string("123456789"), res->body);
  2685. }
  2686. TEST(GzipDecompressor, ChunkedDecompression) {
  2687. std::string data;
  2688. for (size_t i = 0; i < 32 * 1024; ++i) {
  2689. data.push_back(static_cast<char>('a' + i % 26));
  2690. }
  2691. std::string compressed_data;
  2692. {
  2693. httplib::detail::gzip_compressor compressor;
  2694. bool result = compressor.compress(
  2695. data.data(), data.size(),
  2696. /*last=*/true,
  2697. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2698. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2699. compressed_data_size);
  2700. return true;
  2701. });
  2702. ASSERT_TRUE(result);
  2703. }
  2704. std::string decompressed_data;
  2705. {
  2706. httplib::detail::gzip_decompressor decompressor;
  2707. // Chunk size is chosen specificaly to have a decompressed chunk size equal
  2708. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2709. size_t chunk_size = 130;
  2710. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2711. chunk_begin += chunk_size) {
  2712. size_t current_chunk_size =
  2713. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2714. bool result = decompressor.decompress(
  2715. compressed_data.data() + chunk_begin, current_chunk_size,
  2716. [&](const char *decompressed_data_chunk,
  2717. size_t decompressed_data_chunk_size) {
  2718. decompressed_data.insert(decompressed_data.size(),
  2719. decompressed_data_chunk,
  2720. decompressed_data_chunk_size);
  2721. return true;
  2722. });
  2723. ASSERT_TRUE(result);
  2724. }
  2725. }
  2726. ASSERT_EQ(data, decompressed_data);
  2727. }
  2728. #ifdef _WIN32
  2729. TEST(GzipDecompressor, LargeRandomData) {
  2730. // prepare large random data that is difficult to be compressed and is
  2731. // expected to have large size even when compressed
  2732. std::random_device seed_gen;
  2733. std::mt19937 random(seed_gen());
  2734. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2735. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2736. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2737. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2738. // compress data over 4GiB
  2739. std::string compressed_data;
  2740. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2741. httplib::detail::gzip_compressor compressor;
  2742. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2743. data.size() * sizeof(std::uint32_t), true,
  2744. [&](const char *data, size_t size) {
  2745. compressed_data.insert(
  2746. compressed_data.size(), data, size);
  2747. return true;
  2748. });
  2749. ASSERT_TRUE(result);
  2750. // FIXME: compressed data size is expected to be greater than 4GiB,
  2751. // but there is no guarantee
  2752. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2753. // decompress data over 4GiB
  2754. std::string decompressed_data;
  2755. decompressed_data.reserve(data_size);
  2756. httplib::detail::gzip_decompressor decompressor;
  2757. result = decompressor.decompress(
  2758. compressed_data.data(), compressed_data.size(),
  2759. [&](const char *data, size_t size) {
  2760. decompressed_data.insert(decompressed_data.size(), data, size);
  2761. return true;
  2762. });
  2763. ASSERT_TRUE(result);
  2764. // compare
  2765. ASSERT_EQ(data_size, decompressed_data.size());
  2766. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2767. 0);
  2768. }
  2769. #endif
  2770. #endif
  2771. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2773. Headers headers;
  2774. headers.emplace("Accept-Encoding", "br");
  2775. auto res = cli_.Get("/streamed-chunked", headers);
  2776. ASSERT_TRUE(res);
  2777. EXPECT_EQ(200, res->status);
  2778. EXPECT_EQ(std::string("123456789"), res->body);
  2779. }
  2780. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2781. Headers headers;
  2782. headers.emplace("Accept-Encoding", "br");
  2783. auto res = cli_.Get("/streamed-chunked2", headers);
  2784. ASSERT_TRUE(res);
  2785. EXPECT_EQ(200, res->status);
  2786. EXPECT_EQ(std::string("123456789"), res->body);
  2787. }
  2788. #endif
  2789. TEST_F(ServerTest, Patch) {
  2790. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2791. ASSERT_TRUE(res);
  2792. EXPECT_EQ(200, res->status);
  2793. EXPECT_EQ("PATCH", res->body);
  2794. }
  2795. TEST_F(ServerTest, Delete) {
  2796. auto res = cli_.Delete("/delete");
  2797. ASSERT_TRUE(res);
  2798. EXPECT_EQ(200, res->status);
  2799. EXPECT_EQ("DELETE", res->body);
  2800. }
  2801. TEST_F(ServerTest, DeleteContentReceiver) {
  2802. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2803. ASSERT_TRUE(res);
  2804. EXPECT_EQ(200, res->status);
  2805. EXPECT_EQ("content", res->body);
  2806. }
  2807. TEST_F(ServerTest, Options) {
  2808. auto res = cli_.Options("*");
  2809. ASSERT_TRUE(res);
  2810. EXPECT_EQ(200, res->status);
  2811. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2812. EXPECT_TRUE(res->body.empty());
  2813. }
  2814. TEST_F(ServerTest, URL) {
  2815. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2816. ASSERT_TRUE(res);
  2817. EXPECT_EQ(200, res->status);
  2818. }
  2819. TEST_F(ServerTest, ArrayParam) {
  2820. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2821. ASSERT_TRUE(res);
  2822. EXPECT_EQ(200, res->status);
  2823. }
  2824. TEST_F(ServerTest, NoMultipleHeaders) {
  2825. Headers headers = {{"Content-Length", "5"}};
  2826. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2827. "text/plain");
  2828. ASSERT_TRUE(res);
  2829. EXPECT_EQ(200, res->status);
  2830. }
  2831. TEST_F(ServerTest, PostContentReceiver) {
  2832. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2833. ASSERT_TRUE(res);
  2834. ASSERT_EQ(200, res->status);
  2835. ASSERT_EQ("content", res->body);
  2836. }
  2837. TEST_F(ServerTest, PostMulitpartFilsContentReceiver) {
  2838. MultipartFormDataItems items = {
  2839. {"text1", "text default", "", ""},
  2840. {"text2", "aωb", "", ""},
  2841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2842. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2843. {"file3", "", "", "application/octet-stream"},
  2844. };
  2845. auto res = cli_.Post("/content_receiver", items);
  2846. ASSERT_TRUE(res);
  2847. EXPECT_EQ(200, res->status);
  2848. }
  2849. TEST_F(ServerTest, PostMulitpartPlusBoundary) {
  2850. MultipartFormDataItems items = {
  2851. {"text1", "text default", "", ""},
  2852. {"text2", "aωb", "", ""},
  2853. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2854. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2855. {"file3", "", "", "application/octet-stream"},
  2856. };
  2857. auto boundary = std::string("+++++");
  2858. std::string body;
  2859. for (const auto &item : items) {
  2860. body += "--" + boundary + "\r\n";
  2861. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2862. if (!item.filename.empty()) {
  2863. body += "; filename=\"" + item.filename + "\"";
  2864. }
  2865. body += "\r\n";
  2866. if (!item.content_type.empty()) {
  2867. body += "Content-Type: " + item.content_type + "\r\n";
  2868. }
  2869. body += "\r\n";
  2870. body += item.content + "\r\n";
  2871. }
  2872. body += "--" + boundary + "--\r\n";
  2873. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2874. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2875. ASSERT_TRUE(res);
  2876. EXPECT_EQ(200, res->status);
  2877. }
  2878. TEST_F(ServerTest, PostContentReceiverGzip) {
  2879. cli_.set_compress(true);
  2880. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2881. ASSERT_TRUE(res);
  2882. ASSERT_EQ(200, res->status);
  2883. ASSERT_EQ("content", res->body);
  2884. }
  2885. TEST_F(ServerTest, PutContentReceiver) {
  2886. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2887. ASSERT_TRUE(res);
  2888. ASSERT_EQ(200, res->status);
  2889. ASSERT_EQ("content", res->body);
  2890. }
  2891. TEST_F(ServerTest, PatchContentReceiver) {
  2892. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2893. ASSERT_TRUE(res);
  2894. ASSERT_EQ(200, res->status);
  2895. ASSERT_EQ("content", res->body);
  2896. }
  2897. TEST_F(ServerTest, PostQueryStringAndBody) {
  2898. auto res =
  2899. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2900. ASSERT_TRUE(res);
  2901. ASSERT_EQ(200, res->status);
  2902. }
  2903. TEST_F(ServerTest, HTTP2Magic) {
  2904. Request req;
  2905. req.method = "PRI";
  2906. req.path = "*";
  2907. req.body = "SM";
  2908. auto res = std::make_shared<Response>();
  2909. auto error = Error::Success;
  2910. auto ret = cli_.send(req, *res, error);
  2911. ASSERT_TRUE(ret);
  2912. EXPECT_EQ(400, res->status);
  2913. }
  2914. TEST_F(ServerTest, KeepAlive) {
  2915. auto res = cli_.Get("/hi");
  2916. ASSERT_TRUE(res);
  2917. EXPECT_EQ(200, res->status);
  2918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2919. EXPECT_EQ("Hello World!", res->body);
  2920. res = cli_.Get("/hi");
  2921. ASSERT_TRUE(res);
  2922. EXPECT_EQ(200, res->status);
  2923. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2924. EXPECT_EQ("Hello World!", res->body);
  2925. res = cli_.Get("/hi");
  2926. ASSERT_TRUE(res);
  2927. EXPECT_EQ(200, res->status);
  2928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2929. EXPECT_EQ("Hello World!", res->body);
  2930. res = cli_.Get("/not-exist");
  2931. ASSERT_TRUE(res);
  2932. EXPECT_EQ(404, res->status);
  2933. res = cli_.Post("/empty", "", "text/plain");
  2934. ASSERT_TRUE(res);
  2935. EXPECT_EQ(200, res->status);
  2936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2937. EXPECT_EQ("empty", res->body);
  2938. EXPECT_EQ("close", res->get_header_value("Connection"));
  2939. res = cli_.Post(
  2940. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  2941. "text/plain");
  2942. ASSERT_TRUE(res);
  2943. EXPECT_EQ(200, res->status);
  2944. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2945. EXPECT_EQ("empty", res->body);
  2946. cli_.set_keep_alive(false);
  2947. res = cli_.Get("/last-request");
  2948. ASSERT_TRUE(res);
  2949. EXPECT_EQ(200, res->status);
  2950. EXPECT_EQ("close", res->get_header_value("Connection"));
  2951. }
  2952. TEST_F(ServerTest, TooManyRedirect) {
  2953. cli_.set_follow_location(true);
  2954. auto res = cli_.Get("/redirect/0");
  2955. ASSERT_TRUE(!res);
  2956. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2957. }
  2958. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2959. TEST_F(ServerTest, Gzip) {
  2960. Headers headers;
  2961. headers.emplace("Accept-Encoding", "gzip, deflate");
  2962. auto res = cli_.Get("/compress", headers);
  2963. ASSERT_TRUE(res);
  2964. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2965. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2966. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2967. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2968. "7890123456789012345678901234567890",
  2969. res->body);
  2970. EXPECT_EQ(200, res->status);
  2971. }
  2972. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  2973. auto res = cli_.Get("/compress");
  2974. ASSERT_TRUE(res);
  2975. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  2976. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2977. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  2978. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2979. "7890123456789012345678901234567890",
  2980. res->body);
  2981. EXPECT_EQ(200, res->status);
  2982. }
  2983. TEST_F(ServerTest, GzipWithContentReceiver) {
  2984. Headers headers;
  2985. headers.emplace("Accept-Encoding", "gzip, deflate");
  2986. std::string body;
  2987. auto res = cli_.Get("/compress", headers,
  2988. [&](const char *data, uint64_t data_length) {
  2989. EXPECT_EQ(100U, data_length);
  2990. body.append(data, data_length);
  2991. return true;
  2992. });
  2993. ASSERT_TRUE(res);
  2994. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  2995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2996. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  2997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  2998. "7890123456789012345678901234567890",
  2999. body);
  3000. EXPECT_EQ(200, res->status);
  3001. }
  3002. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3003. Headers headers;
  3004. headers.emplace("Accept-Encoding", "gzip, deflate");
  3005. cli_.set_decompress(false);
  3006. auto res = cli_.Get("/compress", headers);
  3007. ASSERT_TRUE(res);
  3008. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3010. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3011. EXPECT_EQ(33U, res->body.size());
  3012. EXPECT_EQ(200, res->status);
  3013. }
  3014. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3015. std::string body;
  3016. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3017. EXPECT_EQ(100U, data_length);
  3018. body.append(data, data_length);
  3019. return true;
  3020. });
  3021. ASSERT_TRUE(res);
  3022. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3024. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3025. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3026. "7890123456789012345678901234567890",
  3027. body);
  3028. EXPECT_EQ(200, res->status);
  3029. }
  3030. TEST_F(ServerTest, NoGzip) {
  3031. Headers headers;
  3032. headers.emplace("Accept-Encoding", "gzip, deflate");
  3033. auto res = cli_.Get("/nocompress", headers);
  3034. ASSERT_TRUE(res);
  3035. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3036. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3037. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3038. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3039. "7890123456789012345678901234567890",
  3040. res->body);
  3041. EXPECT_EQ(200, res->status);
  3042. }
  3043. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3044. Headers headers;
  3045. headers.emplace("Accept-Encoding", "gzip, deflate");
  3046. std::string body;
  3047. auto res = cli_.Get("/nocompress", headers,
  3048. [&](const char *data, uint64_t data_length) {
  3049. EXPECT_EQ(100U, data_length);
  3050. body.append(data, data_length);
  3051. return true;
  3052. });
  3053. ASSERT_TRUE(res);
  3054. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3055. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3056. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3057. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3058. "7890123456789012345678901234567890",
  3059. body);
  3060. EXPECT_EQ(200, res->status);
  3061. }
  3062. TEST_F(ServerTest, MultipartFormDataGzip) {
  3063. MultipartFormDataItems items = {
  3064. {"key1", "test", "", ""},
  3065. {"key2", "--abcdefg123", "", ""},
  3066. };
  3067. cli_.set_compress(true);
  3068. auto res = cli_.Post("/compress-multipart", items);
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ(200, res->status);
  3071. }
  3072. #endif
  3073. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3074. TEST_F(ServerTest, Brotli) {
  3075. Headers headers;
  3076. headers.emplace("Accept-Encoding", "br");
  3077. auto res = cli_.Get("/compress", headers);
  3078. ASSERT_TRUE(res);
  3079. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3080. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3081. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3082. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3083. "7890123456789012345678901234567890",
  3084. res->body);
  3085. EXPECT_EQ(200, res->status);
  3086. }
  3087. #endif
  3088. // Sends a raw request to a server listening at HOST:PORT.
  3089. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3090. std::string *resp = nullptr) {
  3091. auto error = Error::Success;
  3092. auto client_sock = detail::create_client_socket(
  3093. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3094. /*connection_timeout_sec=*/5, 0,
  3095. /*read_timeout_sec=*/5, 0,
  3096. /*write_timeout_sec=*/5, 0, std::string(), error);
  3097. if (client_sock == INVALID_SOCKET) { return false; }
  3098. auto ret = detail::process_client_socket(
  3099. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3100. if (req.size() !=
  3101. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3102. return false;
  3103. }
  3104. char buf[512];
  3105. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3106. while (line_reader.getline()) {
  3107. if (resp) { *resp += line_reader.ptr(); }
  3108. }
  3109. return true;
  3110. });
  3111. detail::close_socket(client_sock);
  3112. return ret;
  3113. }
  3114. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3115. Server svr;
  3116. std::string header_value;
  3117. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3118. header_value = req.get_header_value("foo");
  3119. res.set_content("ok", "text/plain");
  3120. });
  3121. thread t = thread([&] { svr.listen(HOST, PORT); });
  3122. while (!svr.is_running()) {
  3123. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3124. }
  3125. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3126. // like characters are not treated the same - use vertical tab and escape.
  3127. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3128. "foo: \t \v bar \x1B\t \r\n"
  3129. "Connection: close\r\n"
  3130. "\r\n";
  3131. ASSERT_TRUE(send_request(5, req));
  3132. svr.stop();
  3133. t.join();
  3134. EXPECT_EQ(header_value, "\v bar \x1B");
  3135. }
  3136. // Sends a raw request and verifies that there isn't a crash or exception.
  3137. static void test_raw_request(const std::string &req,
  3138. std::string *out = nullptr) {
  3139. Server svr;
  3140. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3141. res.set_content("ok", "text/plain");
  3142. });
  3143. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3144. res.set_content("ok", "text/plain");
  3145. });
  3146. // Server read timeout must be longer than the client read timeout for the
  3147. // bug to reproduce, probably to force the server to process a request
  3148. // without a trailing blank line.
  3149. const time_t client_read_timeout_sec = 1;
  3150. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3151. bool listen_thread_ok = false;
  3152. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3153. while (!svr.is_running()) {
  3154. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3155. }
  3156. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3157. svr.stop();
  3158. t.join();
  3159. EXPECT_TRUE(listen_thread_ok);
  3160. }
  3161. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3162. // A certain header line causes an exception if the header property is parsed
  3163. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3164. test_raw_request(
  3165. "GET /hi HTTP/1.1\r\n"
  3166. " : "
  3167. " "
  3168. " ");
  3169. }
  3170. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3171. // A certain header line causes an exception if the header property *name* is
  3172. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3173. // greedy matcher and requires backtracking when there are a lot of ":"
  3174. // characters.
  3175. // This occurs with libc++ but not libstdc++.
  3176. test_raw_request(
  3177. "GET /hi HTTP/1.1\r\n"
  3178. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3179. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3180. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3181. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3182. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3183. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3184. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3185. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3186. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3187. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3188. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3189. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3190. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3191. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3192. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3193. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3194. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3195. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3196. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3197. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3198. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3199. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3200. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3201. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3202. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3203. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3204. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3205. "&&&%%%");
  3206. }
  3207. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparseableHeaderLine) {
  3208. // Make sure this doesn't crash the server.
  3209. // In a previous version of the header line regex, the "\r" rendered the line
  3210. // unparseable and the regex engine repeatedly backtracked, trying to look for
  3211. // a new position where the leading white space ended and the field value
  3212. // began.
  3213. // The crash occurs with libc++ but not libstdc++.
  3214. test_raw_request("GET /hi HTTP/1.1\r\n"
  3215. "a:" +
  3216. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3217. "\r\n"
  3218. "\r\n");
  3219. }
  3220. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3221. std::string out;
  3222. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3223. "Content-Type: text/plain\r\n"
  3224. "Transfer-Encoding: chunked\r\n"
  3225. "\r\n"
  3226. "nothex\r\n",
  3227. &out);
  3228. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3229. }
  3230. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3231. std::string out;
  3232. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3233. "Content-Type: text/plain\r\n"
  3234. "Transfer-Encoding: chunked\r\n"
  3235. "\r\n"
  3236. "3\r\n"
  3237. "xyz\r\n"
  3238. "NaN\r\n",
  3239. &out);
  3240. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3241. }
  3242. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3243. std::string out;
  3244. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3245. "Content-Type: text/plain\r\n"
  3246. "Transfer-Encoding: chunked\r\n"
  3247. "\r\n"
  3248. // Length is too large for 64 bits.
  3249. "1ffffffffffffffff\r\n"
  3250. "xyz\r\n",
  3251. &out);
  3252. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3253. }
  3254. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3255. test_raw_request("GET /hi HTTP/1.1\r\n"
  3256. "Content-Type: text/plain\r\n\r");
  3257. }
  3258. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3259. std::string out;
  3260. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3261. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3262. }
  3263. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3264. Server svr;
  3265. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3266. res.set_header("Cache-Control", "no-cache");
  3267. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3268. DataSink &sink) {
  3269. char buffer[27];
  3270. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3271. auto ret = sink.write(buffer, size);
  3272. EXPECT_TRUE(ret);
  3273. std::this_thread::sleep_for(std::chrono::seconds(1));
  3274. return true;
  3275. });
  3276. });
  3277. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3278. while (!svr.is_running()) {
  3279. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3280. }
  3281. Client client(HOST, PORT);
  3282. const Headers headers = {{"Accept", "text/event-stream"}};
  3283. auto get_thread = std::thread([&client, &headers]() {
  3284. auto res = client.Get(
  3285. "/events", headers,
  3286. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3287. });
  3288. // Give GET time to get a few messages.
  3289. std::this_thread::sleep_for(std::chrono::seconds(2));
  3290. svr.stop();
  3291. listen_thread.join();
  3292. get_thread.join();
  3293. ASSERT_FALSE(svr.is_running());
  3294. }
  3295. TEST(StreamingTest, NoContentLengthStreaming) {
  3296. Server svr;
  3297. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3298. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3299. if (offset < 6) {
  3300. sink.os << (offset < 3 ? "a" : "b");
  3301. } else {
  3302. sink.done();
  3303. }
  3304. return true;
  3305. });
  3306. });
  3307. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3308. while (!svr.is_running()) {
  3309. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3310. }
  3311. Client client(HOST, PORT);
  3312. auto get_thread = std::thread([&client]() {
  3313. std::string s;
  3314. auto res =
  3315. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3316. s += std::string(data, len);
  3317. return true;
  3318. });
  3319. EXPECT_EQ("aaabbb", s);
  3320. });
  3321. // Give GET time to get a few messages.
  3322. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3323. svr.stop();
  3324. listen_thread.join();
  3325. get_thread.join();
  3326. ASSERT_FALSE(svr.is_running());
  3327. }
  3328. TEST(MountTest, Unmount) {
  3329. Server svr;
  3330. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3331. while (!svr.is_running()) {
  3332. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3333. }
  3334. // Give GET time to get a few messages.
  3335. std::this_thread::sleep_for(std::chrono::seconds(1));
  3336. Client cli("localhost", PORT);
  3337. svr.set_mount_point("/mount2", "./www2");
  3338. auto res = cli.Get("/");
  3339. ASSERT_TRUE(res);
  3340. EXPECT_EQ(404, res->status);
  3341. res = cli.Get("/mount2/dir/test.html");
  3342. ASSERT_TRUE(res);
  3343. EXPECT_EQ(200, res->status);
  3344. svr.set_mount_point("/", "./www");
  3345. res = cli.Get("/dir/");
  3346. ASSERT_TRUE(res);
  3347. EXPECT_EQ(200, res->status);
  3348. svr.remove_mount_point("/");
  3349. res = cli.Get("/dir/");
  3350. ASSERT_TRUE(res);
  3351. EXPECT_EQ(404, res->status);
  3352. svr.remove_mount_point("/mount2");
  3353. res = cli.Get("/mount2/dir/test.html");
  3354. ASSERT_TRUE(res);
  3355. EXPECT_EQ(404, res->status);
  3356. svr.stop();
  3357. listen_thread.join();
  3358. ASSERT_FALSE(svr.is_running());
  3359. }
  3360. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3361. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3362. Server svr;
  3363. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3364. throw std::runtime_error("exception...");
  3365. });
  3366. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3367. throw std::runtime_error("exception\r\n...");
  3368. });
  3369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3370. while (!svr.is_running()) {
  3371. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3372. }
  3373. // Give GET time to get a few messages.
  3374. std::this_thread::sleep_for(std::chrono::seconds(1));
  3375. Client cli("localhost", PORT);
  3376. {
  3377. auto res = cli.Get("/exception");
  3378. ASSERT_TRUE(res);
  3379. EXPECT_EQ(500, res->status);
  3380. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3381. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3382. }
  3383. {
  3384. auto res = cli.Get("/unknown");
  3385. ASSERT_TRUE(res);
  3386. EXPECT_EQ(500, res->status);
  3387. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3388. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3389. }
  3390. svr.stop();
  3391. listen_thread.join();
  3392. ASSERT_FALSE(svr.is_running());
  3393. }
  3394. #endif
  3395. TEST(KeepAliveTest, ReadTimeout) {
  3396. Server svr;
  3397. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3398. std::this_thread::sleep_for(std::chrono::seconds(2));
  3399. res.set_content("a", "text/plain");
  3400. });
  3401. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3402. res.set_content("b", "text/plain");
  3403. });
  3404. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3405. while (!svr.is_running()) {
  3406. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3407. }
  3408. // Give GET time to get a few messages.
  3409. std::this_thread::sleep_for(std::chrono::seconds(1));
  3410. Client cli("localhost", PORT);
  3411. cli.set_keep_alive(true);
  3412. cli.set_read_timeout(std::chrono::seconds(1));
  3413. auto resa = cli.Get("/a");
  3414. ASSERT_FALSE(resa);
  3415. EXPECT_EQ(Error::Read, resa.error());
  3416. auto resb = cli.Get("/b");
  3417. ASSERT_TRUE(resb);
  3418. EXPECT_EQ(200, resb->status);
  3419. EXPECT_EQ("b", resb->body);
  3420. svr.stop();
  3421. listen_thread.join();
  3422. ASSERT_FALSE(svr.is_running());
  3423. }
  3424. TEST(KeepAliveTest, Issue1041) {
  3425. Server svr;
  3426. svr.set_keep_alive_timeout(3);
  3427. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3428. res.set_content("Hello World!", "text/plain");
  3429. });
  3430. auto f = std::async(std::launch::async, [&svr] { svr.listen(HOST, PORT); });
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3432. Client cli(HOST, PORT);
  3433. cli.set_keep_alive(true);
  3434. auto result = cli.Get("/hi");
  3435. ASSERT_TRUE(result);
  3436. EXPECT_EQ(200, result->status);
  3437. std::this_thread::sleep_for(std::chrono::seconds(5));
  3438. result = cli.Get("/hi");
  3439. ASSERT_TRUE(result);
  3440. EXPECT_EQ(200, result->status);
  3441. svr.stop();
  3442. f.wait();
  3443. }
  3444. TEST(ClientProblemDetectionTest, ContentProvider) {
  3445. Server svr;
  3446. size_t content_length = 1024 * 1024;
  3447. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3448. res.set_content_provider(
  3449. content_length, "text/plain",
  3450. [&](size_t offset, size_t length, DataSink &sink) {
  3451. auto out_len = std::min(length, static_cast<size_t>(1024));
  3452. std::string out(out_len, '@');
  3453. sink.write(out.data(), out_len);
  3454. return offset < 4096;
  3455. },
  3456. [](bool success) { ASSERT_FALSE(success); });
  3457. });
  3458. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3459. while (!svr.is_running()) {
  3460. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3461. }
  3462. // Give GET time to get a few messages.
  3463. std::this_thread::sleep_for(std::chrono::seconds(1));
  3464. Client cli("localhost", PORT);
  3465. auto res = cli.Get("/hi", [&](const char * /*data*/, size_t /*data_length*/) {
  3466. return false;
  3467. });
  3468. ASSERT_FALSE(res);
  3469. svr.stop();
  3470. listen_thread.join();
  3471. ASSERT_FALSE(svr.is_running());
  3472. }
  3473. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3474. Server svr;
  3475. svr.set_error_handler([](Request const &, Response &res) -> void {
  3476. res.set_chunked_content_provider(
  3477. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3478. sink.os << "hello";
  3479. sink.os << "world";
  3480. sink.done();
  3481. return true;
  3482. });
  3483. });
  3484. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3485. while (!svr.is_running()) {
  3486. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3487. }
  3488. // Give GET time to get a few messages.
  3489. std::this_thread::sleep_for(std::chrono::seconds(1));
  3490. Client cli("localhost", PORT);
  3491. auto res = cli.Get("/");
  3492. ASSERT_TRUE(res);
  3493. EXPECT_EQ(404, res->status);
  3494. EXPECT_EQ("helloworld", res->body);
  3495. svr.stop();
  3496. listen_thread.join();
  3497. ASSERT_FALSE(svr.is_running());
  3498. }
  3499. TEST(GetWithParametersTest, GetWithParameters) {
  3500. Server svr;
  3501. svr.Get("/", [&](const Request &req, Response &) {
  3502. EXPECT_EQ("world", req.get_param_value("hello"));
  3503. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3504. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3505. });
  3506. svr.Get("/params", [&](const Request &req, Response &) {
  3507. EXPECT_EQ("world", req.get_param_value("hello"));
  3508. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3509. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3510. });
  3511. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3512. EXPECT_EQ("resource-id", req.matches[1]);
  3513. EXPECT_EQ("foo", req.get_param_value("param1"));
  3514. EXPECT_EQ("bar", req.get_param_value("param2"));
  3515. });
  3516. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3517. while (!svr.is_running()) {
  3518. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3519. }
  3520. std::this_thread::sleep_for(std::chrono::seconds(1));
  3521. {
  3522. Client cli(HOST, PORT);
  3523. Params params;
  3524. params.emplace("hello", "world");
  3525. params.emplace("hello2", "world2");
  3526. params.emplace("hello3", "world3");
  3527. auto res = cli.Get("/", params, Headers{});
  3528. ASSERT_TRUE(res);
  3529. EXPECT_EQ(200, res->status);
  3530. }
  3531. {
  3532. Client cli(HOST, PORT);
  3533. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3534. ASSERT_TRUE(res);
  3535. EXPECT_EQ(200, res->status);
  3536. }
  3537. {
  3538. Client cli(HOST, PORT);
  3539. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(200, res->status);
  3542. }
  3543. svr.stop();
  3544. listen_thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. }
  3547. TEST(GetWithParametersTest, GetWithParameters2) {
  3548. Server svr;
  3549. svr.Get("/", [&](const Request &req, Response &res) {
  3550. auto text = req.get_param_value("hello");
  3551. res.set_content(text, "text/plain");
  3552. });
  3553. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3554. while (!svr.is_running()) {
  3555. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3556. }
  3557. std::this_thread::sleep_for(std::chrono::seconds(1));
  3558. Client cli("localhost", PORT);
  3559. Params params;
  3560. params.emplace("hello", "world");
  3561. std::string body;
  3562. auto res = cli.Get("/", params, Headers{},
  3563. [&](const char *data, size_t data_length) {
  3564. body.append(data, data_length);
  3565. return true;
  3566. });
  3567. ASSERT_TRUE(res);
  3568. EXPECT_EQ(200, res->status);
  3569. EXPECT_EQ("world", body);
  3570. svr.stop();
  3571. listen_thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. }
  3574. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3575. Client cli("httpbin.org");
  3576. cli.set_default_headers({make_range_header({{1, 10}})});
  3577. cli.set_connection_timeout(5);
  3578. {
  3579. auto res = cli.Get("/range/32");
  3580. ASSERT_TRUE(res);
  3581. EXPECT_EQ("bcdefghijk", res->body);
  3582. EXPECT_EQ(206, res->status);
  3583. }
  3584. {
  3585. auto res = cli.Get("/range/32");
  3586. ASSERT_TRUE(res);
  3587. EXPECT_EQ("bcdefghijk", res->body);
  3588. EXPECT_EQ(206, res->status);
  3589. }
  3590. }
  3591. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3592. Server svr;
  3593. svr.set_default_headers({{"Hello", "World"}});
  3594. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3595. res.set_content("ok", "text/plain");
  3596. });
  3597. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3598. while (!svr.is_running()) {
  3599. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3600. }
  3601. std::this_thread::sleep_for(std::chrono::seconds(1));
  3602. Client cli("localhost", PORT);
  3603. auto res = cli.Get("/");
  3604. ASSERT_TRUE(res);
  3605. EXPECT_EQ(200, res->status);
  3606. EXPECT_EQ("ok", res->body);
  3607. EXPECT_EQ("World", res->get_header_value("Hello"));
  3608. svr.stop();
  3609. listen_thread.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. }
  3612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3613. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3615. ASSERT_TRUE(svr.is_valid());
  3616. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3617. std::this_thread::sleep_for(std::chrono::seconds(2));
  3618. res.set_content("a", "text/plain");
  3619. });
  3620. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3621. res.set_content("b", "text/plain");
  3622. });
  3623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3624. while (!svr.is_running()) {
  3625. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3626. }
  3627. // Give GET time to get a few messages.
  3628. std::this_thread::sleep_for(std::chrono::seconds(1));
  3629. SSLClient cli("localhost", PORT);
  3630. cli.enable_server_certificate_verification(false);
  3631. cli.set_keep_alive(true);
  3632. cli.set_read_timeout(std::chrono::seconds(1));
  3633. auto resa = cli.Get("/a");
  3634. ASSERT_TRUE(!resa);
  3635. EXPECT_EQ(Error::Read, resa.error());
  3636. auto resb = cli.Get("/b");
  3637. ASSERT_TRUE(resb);
  3638. EXPECT_EQ(200, resb->status);
  3639. EXPECT_EQ("b", resb->body);
  3640. svr.stop();
  3641. listen_thread.join();
  3642. ASSERT_FALSE(svr.is_running());
  3643. }
  3644. #endif
  3645. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3646. protected:
  3647. ServerTestWithAI_PASSIVE()
  3648. : cli_(HOST, PORT)
  3649. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3650. ,
  3651. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3652. #endif
  3653. {
  3654. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3655. cli_.enable_server_certificate_verification(false);
  3656. #endif
  3657. }
  3658. virtual void SetUp() {
  3659. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3660. res.set_content("Hello World!", "text/plain");
  3661. });
  3662. t_ = thread(
  3663. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3664. while (!svr_.is_running()) {
  3665. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3666. }
  3667. }
  3668. virtual void TearDown() {
  3669. svr_.stop();
  3670. t_.join();
  3671. }
  3672. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3673. SSLClient cli_;
  3674. SSLServer svr_;
  3675. #else
  3676. Client cli_;
  3677. Server svr_;
  3678. #endif
  3679. thread t_;
  3680. };
  3681. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3682. auto res = cli_.Get("/hi");
  3683. ASSERT_TRUE(res);
  3684. EXPECT_EQ(200, res->status);
  3685. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3686. EXPECT_EQ("Hello World!", res->body);
  3687. }
  3688. class ServerUpDownTest : public ::testing::Test {
  3689. protected:
  3690. ServerUpDownTest() : cli_(HOST, PORT) {}
  3691. virtual void SetUp() {
  3692. t_ = thread([&]() {
  3693. svr_.bind_to_any_port(HOST);
  3694. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3695. ASSERT_TRUE(svr_.listen_after_bind());
  3696. });
  3697. while (!svr_.is_running()) {
  3698. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3699. }
  3700. }
  3701. virtual void TearDown() {
  3702. svr_.stop();
  3703. t_.join();
  3704. }
  3705. Client cli_;
  3706. Server svr_;
  3707. thread t_;
  3708. };
  3709. TEST_F(ServerUpDownTest, QuickStartStop) {
  3710. // Should not crash, especially when run with
  3711. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3712. }
  3713. class PayloadMaxLengthTest : public ::testing::Test {
  3714. protected:
  3715. PayloadMaxLengthTest()
  3716. : cli_(HOST, PORT)
  3717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3718. ,
  3719. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3720. #endif
  3721. {
  3722. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3723. cli_.enable_server_certificate_verification(false);
  3724. #endif
  3725. }
  3726. virtual void SetUp() {
  3727. svr_.set_payload_max_length(8);
  3728. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3729. res.set_content("test", "text/plain");
  3730. });
  3731. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3732. while (!svr_.is_running()) {
  3733. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3734. }
  3735. }
  3736. virtual void TearDown() {
  3737. svr_.stop();
  3738. t_.join();
  3739. }
  3740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3741. SSLClient cli_;
  3742. SSLServer svr_;
  3743. #else
  3744. Client cli_;
  3745. Server svr_;
  3746. #endif
  3747. thread t_;
  3748. };
  3749. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3750. auto res = cli_.Post("/test", "123456789", "text/plain");
  3751. ASSERT_TRUE(res);
  3752. EXPECT_EQ(413, res->status);
  3753. res = cli_.Post("/test", "12345678", "text/plain");
  3754. ASSERT_TRUE(res);
  3755. EXPECT_EQ(200, res->status);
  3756. }
  3757. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3758. TEST(SSLClientTest, UpdateCAStore) {
  3759. httplib::SSLClient httplib_client("www.google.com");
  3760. auto ca_store_1 = X509_STORE_new();
  3761. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3762. nullptr);
  3763. httplib_client.set_ca_cert_store(ca_store_1);
  3764. auto ca_store_2 = X509_STORE_new();
  3765. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3766. nullptr);
  3767. httplib_client.set_ca_cert_store(ca_store_2);
  3768. }
  3769. TEST(SSLClientTest, ServerNameIndication_Online) {
  3770. SSLClient cli("httpbin.org", 443);
  3771. auto res = cli.Get("/get");
  3772. ASSERT_TRUE(res);
  3773. ASSERT_EQ(200, res->status);
  3774. }
  3775. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3776. SSLClient cli("google.com");
  3777. auto res = cli.Get("/");
  3778. ASSERT_TRUE(res);
  3779. ASSERT_EQ(301, res->status);
  3780. }
  3781. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3782. SSLClient cli("google.com");
  3783. cli.enable_server_certificate_verification(true);
  3784. cli.set_ca_cert_path("hello");
  3785. auto res = cli.Get("/");
  3786. ASSERT_TRUE(!res);
  3787. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3788. }
  3789. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3790. SSLClient cli("google.com");
  3791. cli.set_ca_cert_path(CA_CERT_FILE);
  3792. auto res = cli.Get("/");
  3793. ASSERT_TRUE(res);
  3794. ASSERT_EQ(301, res->status);
  3795. }
  3796. TEST(SSLClientTest, ServerCertificateVerification4) {
  3797. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3798. ASSERT_TRUE(svr.is_valid());
  3799. svr.Get("/test", [&](const Request &, Response &res) {
  3800. res.set_content("test", "text/plain");
  3801. svr.stop();
  3802. ASSERT_TRUE(true);
  3803. });
  3804. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3805. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3806. SSLClient cli("127.0.0.1", PORT);
  3807. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3808. cli.enable_server_certificate_verification(true);
  3809. cli.set_connection_timeout(30);
  3810. auto res = cli.Get("/test");
  3811. ASSERT_TRUE(res);
  3812. ASSERT_EQ(200, res->status);
  3813. t.join();
  3814. }
  3815. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  3816. SSLClient cli("www.youtube.com");
  3817. cli.set_ca_cert_path(CA_CERT_FILE);
  3818. cli.enable_server_certificate_verification(true);
  3819. cli.set_follow_location(true);
  3820. auto res = cli.Get("/");
  3821. ASSERT_TRUE(res);
  3822. ASSERT_EQ(200, res->status);
  3823. }
  3824. #if 0
  3825. TEST(SSLClientTest, SetInterfaceWithINET6) {
  3826. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  3827. ASSERT_TRUE(cli != nullptr);
  3828. cli->set_address_family(AF_INET6);
  3829. cli->set_interface("en0");
  3830. auto res = cli->Get("/get");
  3831. ASSERT_TRUE(res);
  3832. ASSERT_EQ(200, res->status);
  3833. }
  3834. #endif
  3835. TEST(SSLClientServerTest, ClientCertPresent) {
  3836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3837. CLIENT_CA_CERT_DIR);
  3838. ASSERT_TRUE(svr.is_valid());
  3839. svr.Get("/test", [&](const Request &req, Response &res) {
  3840. res.set_content("test", "text/plain");
  3841. svr.stop();
  3842. ASSERT_TRUE(true);
  3843. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3844. ASSERT_TRUE(peer_cert != nullptr);
  3845. auto subject_name = X509_get_subject_name(peer_cert);
  3846. ASSERT_TRUE(subject_name != nullptr);
  3847. std::string common_name;
  3848. {
  3849. char name[BUFSIZ];
  3850. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3851. name, sizeof(name));
  3852. common_name.assign(name, static_cast<size_t>(name_len));
  3853. }
  3854. EXPECT_EQ("Common Name", common_name);
  3855. X509_free(peer_cert);
  3856. });
  3857. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3858. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3859. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3860. cli.enable_server_certificate_verification(false);
  3861. cli.set_connection_timeout(30);
  3862. auto res = cli.Get("/test");
  3863. ASSERT_TRUE(res);
  3864. ASSERT_EQ(200, res->status);
  3865. t.join();
  3866. }
  3867. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  3868. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  3869. X509 *server_cert;
  3870. EVP_PKEY *server_private_key;
  3871. X509_STORE *client_ca_cert_store;
  3872. X509 *client_cert;
  3873. EVP_PKEY *client_private_key;
  3874. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  3875. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3876. fclose(f);
  3877. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  3878. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3879. fclose(f);
  3880. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  3881. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3882. client_ca_cert_store = X509_STORE_new();
  3883. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  3884. X509_free(client_cert);
  3885. fclose(f);
  3886. f = fopen(CLIENT_CERT_FILE, "r+");
  3887. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  3888. fclose(f);
  3889. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  3890. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  3891. fclose(f);
  3892. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  3893. ASSERT_TRUE(svr.is_valid());
  3894. svr.Get("/test", [&](const Request &req, Response &res) {
  3895. res.set_content("test", "text/plain");
  3896. svr.stop();
  3897. ASSERT_TRUE(true);
  3898. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  3899. ASSERT_TRUE(peer_cert != nullptr);
  3900. auto subject_name = X509_get_subject_name(peer_cert);
  3901. ASSERT_TRUE(subject_name != nullptr);
  3902. std::string common_name;
  3903. {
  3904. char name[BUFSIZ];
  3905. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3906. name, sizeof(name));
  3907. common_name.assign(name, static_cast<size_t>(name_len));
  3908. }
  3909. EXPECT_EQ("Common Name", common_name);
  3910. X509_free(peer_cert);
  3911. });
  3912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3913. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3914. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  3915. cli.enable_server_certificate_verification(false);
  3916. cli.set_connection_timeout(30);
  3917. auto res = cli.Get("/test");
  3918. ASSERT_TRUE(res);
  3919. ASSERT_EQ(200, res->status);
  3920. X509_free(server_cert);
  3921. EVP_PKEY_free(server_private_key);
  3922. X509_free(client_cert);
  3923. EVP_PKEY_free(client_private_key);
  3924. t.join();
  3925. }
  3926. #endif
  3927. TEST(SSLClientServerTest, ClientCertMissing) {
  3928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3929. CLIENT_CA_CERT_DIR);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  3932. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3933. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3934. SSLClient cli(HOST, PORT);
  3935. auto res = cli.Get("/test");
  3936. cli.set_connection_timeout(30);
  3937. ASSERT_TRUE(!res);
  3938. EXPECT_EQ(Error::SSLServerVerification, res.error());
  3939. svr.stop();
  3940. t.join();
  3941. }
  3942. TEST(SSLClientServerTest, TrustDirOptional) {
  3943. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3944. ASSERT_TRUE(svr.is_valid());
  3945. svr.Get("/test", [&](const Request &, Response &res) {
  3946. res.set_content("test", "text/plain");
  3947. svr.stop();
  3948. });
  3949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3950. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3951. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3952. cli.enable_server_certificate_verification(false);
  3953. cli.set_connection_timeout(30);
  3954. auto res = cli.Get("/test");
  3955. ASSERT_TRUE(res);
  3956. ASSERT_EQ(200, res->status);
  3957. t.join();
  3958. }
  3959. TEST(SSLClientServerTest, SSLConnectTimeout) {
  3960. class NoListenSSLServer : public SSLServer {
  3961. public:
  3962. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  3963. const char *client_ca_cert_file_path,
  3964. const char *client_ca_cert_dir_path = nullptr)
  3965. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  3966. client_ca_cert_dir_path),
  3967. stop_(false) {}
  3968. bool stop_;
  3969. private:
  3970. bool process_and_close_socket(socket_t /*sock*/) override {
  3971. // Don't create SSL context
  3972. while (!stop_) {
  3973. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3974. }
  3975. return true;
  3976. }
  3977. };
  3978. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  3979. CLIENT_CA_CERT_FILE);
  3980. ASSERT_TRUE(svr.is_valid());
  3981. svr.Get("/test", [&](const Request &, Response &res) {
  3982. res.set_content("test", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3986. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3987. cli.enable_server_certificate_verification(false);
  3988. cli.set_connection_timeout(1);
  3989. auto res = cli.Get("/test");
  3990. ASSERT_TRUE(!res);
  3991. EXPECT_EQ(Error::SSLConnection, res.error());
  3992. svr.stop_ = true;
  3993. svr.stop();
  3994. t.join();
  3995. }
  3996. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  3997. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  3998. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  3999. SSL_CTX_set_options(&ssl_ctx,
  4000. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4001. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4002. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4003. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4004. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4005. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4006. "ECDHE-DSS-AES128-SHA256:"
  4007. "ECDHE-RSA-AES256-SHA256:"
  4008. "ECDHE-DSS-AES256-SHA256:";
  4009. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4010. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4011. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4012. SSL_FILETYPE_PEM) != 1) {
  4013. return false;
  4014. }
  4015. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4016. CLIENT_CA_CERT_DIR);
  4017. SSL_CTX_set_verify(
  4018. &ssl_ctx,
  4019. SSL_VERIFY_PEER |
  4020. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4021. nullptr);
  4022. return true;
  4023. };
  4024. SSLServer svr(setup_ssl_ctx_callback);
  4025. ASSERT_TRUE(svr.is_valid());
  4026. svr.Get("/test", [&](const Request &req, Response &res) {
  4027. res.set_content("test", "text/plain");
  4028. svr.stop();
  4029. ASSERT_TRUE(true);
  4030. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4031. ASSERT_TRUE(peer_cert != nullptr);
  4032. auto subject_name = X509_get_subject_name(peer_cert);
  4033. ASSERT_TRUE(subject_name != nullptr);
  4034. std::string common_name;
  4035. {
  4036. char name[BUFSIZ];
  4037. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4038. name, sizeof(name));
  4039. common_name.assign(name, static_cast<size_t>(name_len));
  4040. }
  4041. EXPECT_EQ("Common Name", common_name);
  4042. X509_free(peer_cert);
  4043. });
  4044. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4045. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4046. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4047. cli.enable_server_certificate_verification(false);
  4048. cli.set_connection_timeout(30);
  4049. auto res = cli.Get("/test");
  4050. ASSERT_TRUE(res);
  4051. ASSERT_EQ(200, res->status);
  4052. t.join();
  4053. }
  4054. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4055. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4056. // prepare large data
  4057. std::random_device seed_gen;
  4058. std::mt19937 random(seed_gen());
  4059. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4060. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4061. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4062. // server
  4063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4064. ASSERT_TRUE(svr.is_valid());
  4065. svr.Post("/binary", [&](const Request &req, Response &res) {
  4066. EXPECT_EQ(large_size_byte, req.body.size());
  4067. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4068. res.set_content(req.body, "application/octet-stream");
  4069. });
  4070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4071. while (!svr.is_running()) {
  4072. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4073. }
  4074. // client POST
  4075. SSLClient cli("localhost", PORT);
  4076. cli.enable_server_certificate_verification(false);
  4077. cli.set_read_timeout(std::chrono::seconds(100));
  4078. cli.set_write_timeout(std::chrono::seconds(100));
  4079. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4080. large_size_byte, "application/octet-stream");
  4081. // compare
  4082. EXPECT_EQ(200, res->status);
  4083. EXPECT_EQ(large_size_byte, res->body.size());
  4084. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4085. // cleanup
  4086. svr.stop();
  4087. listen_thread.join();
  4088. ASSERT_FALSE(svr.is_running());
  4089. }
  4090. #endif
  4091. #ifdef _WIN32
  4092. TEST(CleanupTest, WSACleanup) {
  4093. int ret = WSACleanup();
  4094. ASSERT_EQ(0, ret);
  4095. }
  4096. #endif
  4097. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4098. TEST(NoSSLSupport, SimpleInterface) {
  4099. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4100. }
  4101. #endif
  4102. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4103. TEST(InvalidScheme, SimpleInterface) {
  4104. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4105. }
  4106. #endif
  4107. TEST(NoScheme, SimpleInterface) {
  4108. Client cli("yahoo.com:80");
  4109. ASSERT_TRUE(cli.is_valid());
  4110. }
  4111. TEST(SendAPI, SimpleInterface_Online) {
  4112. Client cli("http://yahoo.com");
  4113. Request req;
  4114. req.method = "GET";
  4115. req.path = "/";
  4116. auto res = cli.send(req);
  4117. ASSERT_TRUE(res);
  4118. EXPECT_EQ(301, res->status);
  4119. }
  4120. TEST(ClientImplMethods, GetSocketTest) {
  4121. httplib::Server svr;
  4122. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4123. res.status = 200;
  4124. });
  4125. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4126. while (!svr.is_running()) {
  4127. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  4128. }
  4129. {
  4130. httplib::Client cli("http://127.0.0.1:3333");
  4131. cli.set_keep_alive(true);
  4132. // Use the behavior of cpp-httplib of opening the connection
  4133. // only when the first request happens. If that changes,
  4134. // this test would be obsolete.
  4135. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4136. // This also implicitly tests the server. But other tests would fail much
  4137. // earlier than this one to be considered.
  4138. auto res = cli.Get("/");
  4139. ASSERT_TRUE(res);
  4140. EXPECT_EQ(200, res->status);
  4141. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4142. }
  4143. svr.stop();
  4144. thread.join();
  4145. ASSERT_FALSE(svr.is_running());
  4146. }
  4147. // Disabled due to out-of-memory problem on GitHub Actions
  4148. #ifdef _WIN64
  4149. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4150. // allocate content size larger than 2GB in memory
  4151. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4152. char *content = (char *)malloc(content_size);
  4153. ASSERT_TRUE(content);
  4154. Server svr;
  4155. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4156. resp.set_content(content, content_size, "application/octet-stream");
  4157. });
  4158. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4159. while (!svr.is_running()) {
  4160. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4161. }
  4162. // Give GET time to get a few messages.
  4163. std::this_thread::sleep_for(std::chrono::seconds(1));
  4164. Client cli(HOST, PORT);
  4165. auto res = cli.Get("/foo");
  4166. ASSERT_TRUE(res);
  4167. EXPECT_EQ(200, res->status);
  4168. EXPECT_EQ(content_size, res->body.length());
  4169. free(content);
  4170. svr.stop();
  4171. listen_thread.join();
  4172. ASSERT_FALSE(svr.is_running());
  4173. }
  4174. #endif
  4175. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4176. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4177. Client cli("http://yahoo.com");
  4178. auto res = cli.Get("/");
  4179. ASSERT_TRUE(res);
  4180. EXPECT_EQ(301, res->status);
  4181. cli.set_follow_location(true);
  4182. res = cli.Get("/");
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(200, res->status);
  4185. EXPECT_EQ("https://yahoo.com/", res->location);
  4186. }
  4187. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4188. Client cli("https://yahoo.com");
  4189. auto res = cli.Get("/");
  4190. ASSERT_TRUE(res);
  4191. EXPECT_EQ(301, res->status);
  4192. cli.set_follow_location(true);
  4193. res = cli.Get("/");
  4194. ASSERT_TRUE(res);
  4195. EXPECT_EQ(200, res->status);
  4196. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4197. }
  4198. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4199. Client cli("https://yahoo.com");
  4200. auto res = cli.Get("/");
  4201. ASSERT_TRUE(res);
  4202. ASSERT_FALSE(!res);
  4203. ASSERT_TRUE(res);
  4204. ASSERT_FALSE(res == nullptr);
  4205. ASSERT_TRUE(res != nullptr);
  4206. EXPECT_EQ(Error::Success, res.error());
  4207. EXPECT_EQ(301, res.value().status);
  4208. EXPECT_EQ(301, (*res).status);
  4209. EXPECT_EQ(301, res->status);
  4210. cli.set_follow_location(true);
  4211. res = cli.Get("/");
  4212. ASSERT_TRUE(res);
  4213. EXPECT_EQ(Error::Success, res.error());
  4214. EXPECT_EQ(200, res.value().status);
  4215. EXPECT_EQ(200, (*res).status);
  4216. EXPECT_EQ(200, res->status);
  4217. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4218. }
  4219. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4220. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4221. Client cli("https://cdnjs.cloudflare.com");
  4222. auto res =
  4223. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4224. ASSERT_TRUE(res);
  4225. EXPECT_EQ(200, res->status);
  4226. EXPECT_EQ(287630U, res->body.size());
  4227. EXPECT_EQ("application/javascript; charset=utf-8",
  4228. res->get_header_value("Content-Type"));
  4229. }
  4230. #endif
  4231. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4232. Client cli("https://nghttp2.org");
  4233. cli.set_follow_location(true);
  4234. auto res =
  4235. cli.Get("/httpbin/"
  4236. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4237. ASSERT_TRUE(res);
  4238. EXPECT_EQ(200, res->status);
  4239. }
  4240. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4241. Client cli("https://nghttp2.org");
  4242. cli.set_follow_location(true);
  4243. Params params;
  4244. params.emplace("url", "http://www.google.com");
  4245. params.emplace("status_code", "302");
  4246. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4247. ASSERT_TRUE(res);
  4248. EXPECT_EQ(200, res->status);
  4249. }
  4250. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4251. Client cli("https://nghttp2.org");
  4252. cli.set_follow_location(true);
  4253. Params params;
  4254. params.emplace("url", "http://www.google.com");
  4255. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4256. ASSERT_TRUE(res);
  4257. EXPECT_EQ(200, res->status);
  4258. }
  4259. TEST(HttpToHttpsRedirectTest, CertFile) {
  4260. Server svr;
  4261. ASSERT_TRUE(svr.is_valid());
  4262. svr.Get("/index", [&](const Request &, Response &res) {
  4263. res.set_redirect("https://127.0.0.1:1235/index");
  4264. svr.stop();
  4265. });
  4266. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4267. ASSERT_TRUE(ssl_svr.is_valid());
  4268. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4269. res.set_content("test", "text/plain");
  4270. ssl_svr.stop();
  4271. });
  4272. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4273. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4274. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4275. Client cli("127.0.0.1", PORT);
  4276. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4277. cli.enable_server_certificate_verification(true);
  4278. cli.set_follow_location(true);
  4279. cli.set_connection_timeout(30);
  4280. auto res = cli.Get("/index");
  4281. ASSERT_TRUE(res);
  4282. ASSERT_EQ(200, res->status);
  4283. t.join();
  4284. t2.join();
  4285. }
  4286. TEST(MultipartFormDataTest, LargeData) {
  4287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4288. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4289. const ContentReader &content_reader) {
  4290. if (req.is_multipart_form_data()) {
  4291. MultipartFormDataItems files;
  4292. content_reader(
  4293. [&](const MultipartFormData &file) {
  4294. files.push_back(file);
  4295. return true;
  4296. },
  4297. [&](const char *data, size_t data_length) {
  4298. files.back().content.append(data, data_length);
  4299. return true;
  4300. });
  4301. EXPECT_TRUE(std::string(files[0].name) == "document");
  4302. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4303. EXPECT_TRUE(files[0].filename == "2MB_data");
  4304. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4305. EXPECT_TRUE(files[1].name == "hello");
  4306. EXPECT_TRUE(files[1].content == "world");
  4307. EXPECT_TRUE(files[1].filename == "");
  4308. EXPECT_TRUE(files[1].content_type == "");
  4309. } else {
  4310. std::string body;
  4311. content_reader([&](const char *data, size_t data_length) {
  4312. body.append(data, data_length);
  4313. return true;
  4314. });
  4315. }
  4316. });
  4317. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4318. while (!svr.is_running()) {
  4319. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4320. }
  4321. std::this_thread::sleep_for(std::chrono::seconds(1));
  4322. {
  4323. std::string data(1024 * 1024 * 2, '.');
  4324. std::stringstream buffer;
  4325. buffer << data;
  4326. Client cli("https://localhost:8080");
  4327. cli.enable_server_certificate_verification(false);
  4328. MultipartFormDataItems items{
  4329. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4330. {"hello", "world", "", ""},
  4331. };
  4332. auto res = cli.Post("/post", items);
  4333. ASSERT_TRUE(res);
  4334. ASSERT_EQ(200, res->status);
  4335. }
  4336. svr.stop();
  4337. t.join();
  4338. }
  4339. TEST(MultipartFormDataTest, DataProviderItems) {
  4340. std::random_device seed_gen;
  4341. std::mt19937 random(seed_gen());
  4342. std::string rand1;
  4343. rand1.resize(1000);
  4344. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4345. std::string rand2;
  4346. rand2.resize(3000);
  4347. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4349. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4350. const ContentReader &content_reader) {
  4351. ASSERT_FALSE(req.is_multipart_form_data());
  4352. std::string body;
  4353. content_reader([&](const char *data, size_t data_length) {
  4354. body.append(data, data_length);
  4355. return true;
  4356. });
  4357. EXPECT_EQ(body, "");
  4358. });
  4359. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4360. const ContentReader &content_reader) {
  4361. ASSERT_TRUE(req.is_multipart_form_data());
  4362. MultipartFormDataItems files;
  4363. content_reader(
  4364. [&](const MultipartFormData &file) {
  4365. files.push_back(file);
  4366. return true;
  4367. },
  4368. [&](const char *data, size_t data_length) {
  4369. files.back().content.append(data, data_length);
  4370. return true;
  4371. });
  4372. ASSERT_TRUE(files.size() == 2);
  4373. EXPECT_EQ(std::string(files[0].name), "name1");
  4374. EXPECT_EQ(files[0].content, "Testing123");
  4375. EXPECT_EQ(files[0].filename, "filename1");
  4376. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4377. EXPECT_EQ(files[1].name, "name2");
  4378. EXPECT_EQ(files[1].content, "Testing456");
  4379. EXPECT_EQ(files[1].filename, "");
  4380. EXPECT_EQ(files[1].content_type, "");
  4381. });
  4382. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4383. const ContentReader &content_reader) {
  4384. ASSERT_TRUE(req.is_multipart_form_data());
  4385. MultipartFormDataItems files;
  4386. content_reader(
  4387. [&](const MultipartFormData &file) {
  4388. files.push_back(file);
  4389. return true;
  4390. },
  4391. [&](const char *data, size_t data_length) {
  4392. files.back().content.append(data, data_length);
  4393. return true;
  4394. });
  4395. ASSERT_TRUE(files.size() == 2);
  4396. EXPECT_EQ(files[0].name, "name3");
  4397. EXPECT_EQ(files[0].content, rand1);
  4398. EXPECT_EQ(files[0].filename, "filename3");
  4399. EXPECT_EQ(files[0].content_type, "");
  4400. EXPECT_EQ(files[1].name, "name4");
  4401. EXPECT_EQ(files[1].content, rand2);
  4402. EXPECT_EQ(files[1].filename, "filename4");
  4403. EXPECT_EQ(files[1].content_type, "");
  4404. });
  4405. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4406. const ContentReader &content_reader) {
  4407. ASSERT_TRUE(req.is_multipart_form_data());
  4408. MultipartFormDataItems files;
  4409. content_reader(
  4410. [&](const MultipartFormData &file) {
  4411. files.push_back(file);
  4412. return true;
  4413. },
  4414. [&](const char *data, size_t data_length) {
  4415. files.back().content.append(data, data_length);
  4416. return true;
  4417. });
  4418. ASSERT_TRUE(files.size() == 4);
  4419. EXPECT_EQ(std::string(files[0].name), "name1");
  4420. EXPECT_EQ(files[0].content, "Testing123");
  4421. EXPECT_EQ(files[0].filename, "filename1");
  4422. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4423. EXPECT_EQ(files[1].name, "name2");
  4424. EXPECT_EQ(files[1].content, "Testing456");
  4425. EXPECT_EQ(files[1].filename, "");
  4426. EXPECT_EQ(files[1].content_type, "");
  4427. EXPECT_EQ(files[2].name, "name3");
  4428. EXPECT_EQ(files[2].content, rand1);
  4429. EXPECT_EQ(files[2].filename, "filename3");
  4430. EXPECT_EQ(files[2].content_type, "");
  4431. EXPECT_EQ(files[3].name, "name4");
  4432. EXPECT_EQ(files[3].content, rand2);
  4433. EXPECT_EQ(files[3].filename, "filename4");
  4434. EXPECT_EQ(files[3].content_type, "");
  4435. });
  4436. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4437. while (!svr.is_running()) {
  4438. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4439. }
  4440. std::this_thread::sleep_for(std::chrono::seconds(1));
  4441. {
  4442. Client cli("https://localhost:8080");
  4443. cli.enable_server_certificate_verification(false);
  4444. MultipartFormDataItems items{
  4445. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4446. {"name2", "Testing456", "", ""}, // not a file
  4447. };
  4448. {
  4449. auto res = cli.Post("/post-none", {}, {}, {});
  4450. ASSERT_TRUE(res);
  4451. ASSERT_EQ(200, res->status);
  4452. }
  4453. MultipartFormDataProviderItems providers;
  4454. {
  4455. auto res =
  4456. cli.Post("/post-items", {}, items, providers); // empty providers
  4457. ASSERT_TRUE(res);
  4458. ASSERT_EQ(200, res->status);
  4459. }
  4460. providers.push_back({"name3",
  4461. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4462. // test the offset is given correctly at each step
  4463. if (!offset)
  4464. sink.os.write(rand1.data(), 30);
  4465. else if (offset == 30)
  4466. sink.os.write(rand1.data() + 30, 300);
  4467. else if (offset == 330)
  4468. sink.os.write(rand1.data() + 330, 670);
  4469. else if (offset == rand1.size())
  4470. sink.done();
  4471. return true;
  4472. },
  4473. "filename3",
  4474. {}});
  4475. providers.push_back({"name4",
  4476. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4477. // test the offset is given correctly at each step
  4478. if (!offset)
  4479. sink.os.write(rand2.data(), 2000);
  4480. else if (offset == 2000)
  4481. sink.os.write(rand2.data() + 2000, 1);
  4482. else if (offset == 2001)
  4483. sink.os.write(rand2.data() + 2001, 999);
  4484. else if (offset == rand2.size())
  4485. sink.done();
  4486. return true;
  4487. },
  4488. "filename4",
  4489. {}});
  4490. {
  4491. auto res = cli.Post("/post-providers", {}, {}, providers);
  4492. ASSERT_TRUE(res);
  4493. ASSERT_EQ(200, res->status);
  4494. }
  4495. {
  4496. auto res = cli.Post("/post-both", {}, items, providers);
  4497. ASSERT_TRUE(res);
  4498. ASSERT_EQ(200, res->status);
  4499. }
  4500. }
  4501. svr.stop();
  4502. t.join();
  4503. }
  4504. TEST(MultipartFormDataTest, BadHeader) {
  4505. Server svr;
  4506. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4507. res.set_content("ok", "text/plain");
  4508. });
  4509. thread t = thread([&] { svr.listen(HOST, PORT); });
  4510. while (!svr.is_running()) {
  4511. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4512. }
  4513. const std::string body =
  4514. "This is the preamble. It is to be ignored, though it\r\n"
  4515. "is a handy place for composition agents to include an\r\n"
  4516. "explanatory note to non-MIME conformant readers.\r\n"
  4517. "\r\n"
  4518. "\r\n"
  4519. "--simple boundary\r\n"
  4520. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4521. ": BAD...\r\n"
  4522. "\r\n"
  4523. "value1\r\n"
  4524. "--simple boundary\r\n"
  4525. "Content-Disposition: form-data; name=\"field2\"; "
  4526. "filename=\"example.txt\"\r\n"
  4527. "\r\n"
  4528. "value2\r\n"
  4529. "--simple boundary--\r\n"
  4530. "This is the epilogue. It is also to be ignored.\r\n";
  4531. std::string content_type =
  4532. R"(multipart/form-data; boundary="simple boundary")";
  4533. Client cli(HOST, PORT);
  4534. auto res = cli.Post("/post", body, content_type.c_str());
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(400, res->status);
  4537. svr.stop();
  4538. t.join();
  4539. }
  4540. TEST(MultipartFormDataTest, WithPreamble) {
  4541. Server svr;
  4542. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4543. res.set_content("ok", "text/plain");
  4544. });
  4545. thread t = thread([&] { svr.listen(HOST, PORT); });
  4546. while (!svr.is_running()) {
  4547. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4548. }
  4549. const std::string body =
  4550. "This is the preamble. It is to be ignored, though it\r\n"
  4551. "is a handy place for composition agents to include an\r\n"
  4552. "explanatory note to non-MIME conformant readers.\r\n"
  4553. "\r\n"
  4554. "\r\n"
  4555. "--simple boundary\r\n"
  4556. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4557. "\r\n"
  4558. "value1\r\n"
  4559. "--simple boundary\r\n"
  4560. "Content-Disposition: form-data; name=\"field2\"; "
  4561. "filename=\"example.txt\"\r\n"
  4562. "\r\n"
  4563. "value2\r\n"
  4564. "--simple boundary--\r\n"
  4565. "This is the epilogue. It is also to be ignored.\r\n";
  4566. std::string content_type =
  4567. R"(multipart/form-data; boundary="simple boundary")";
  4568. Client cli(HOST, PORT);
  4569. auto res = cli.Post("/post", body, content_type.c_str());
  4570. ASSERT_TRUE(res);
  4571. EXPECT_EQ(200, res->status);
  4572. svr.stop();
  4573. t.join();
  4574. }
  4575. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4577. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4578. const ContentReader &content_reader) {
  4579. if (req.is_multipart_form_data()) {
  4580. MultipartFormDataItems files;
  4581. content_reader(
  4582. [&](const MultipartFormData &file) {
  4583. files.push_back(file);
  4584. return true;
  4585. },
  4586. [&](const char *data, size_t data_length) {
  4587. files.back().content.append(data, data_length);
  4588. return true;
  4589. });
  4590. EXPECT_TRUE(std::string(files[0].name) == "document");
  4591. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4592. EXPECT_TRUE(files[0].filename == "2MB_data");
  4593. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4594. EXPECT_TRUE(files[1].name == "hello");
  4595. EXPECT_TRUE(files[1].content == "world");
  4596. EXPECT_TRUE(files[1].filename == "");
  4597. EXPECT_TRUE(files[1].content_type == "");
  4598. } else {
  4599. std::string body;
  4600. content_reader([&](const char *data, size_t data_length) {
  4601. body.append(data, data_length);
  4602. return true;
  4603. });
  4604. }
  4605. });
  4606. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4607. while (!svr.is_running()) {
  4608. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4609. }
  4610. std::this_thread::sleep_for(std::chrono::seconds(1));
  4611. {
  4612. std::string data(1024 * 1024 * 2, '.');
  4613. std::stringstream buffer;
  4614. buffer << data;
  4615. Client cli("https://localhost:8080");
  4616. cli.enable_server_certificate_verification(false);
  4617. MultipartFormDataItems items{
  4618. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4619. {"hello", "world", "", ""},
  4620. };
  4621. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  4622. ASSERT_TRUE(res);
  4623. ASSERT_EQ(200, res->status);
  4624. }
  4625. svr.stop();
  4626. t.join();
  4627. }
  4628. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  4629. std::this_thread::sleep_for(std::chrono::seconds(1));
  4630. std::string data(1024 * 1024 * 2, '&');
  4631. std::stringstream buffer;
  4632. buffer << data;
  4633. Client cli("https://localhost:8080");
  4634. MultipartFormDataItems items{
  4635. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4636. {"hello", "world", "", ""},
  4637. };
  4638. for (const char &c : " \t\r\n") {
  4639. auto res =
  4640. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  4641. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4642. ASSERT_FALSE(res);
  4643. }
  4644. }
  4645. TEST(MultipartFormDataTest, PutFormData) {
  4646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4647. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  4648. const ContentReader &content_reader) {
  4649. if (req.is_multipart_form_data()) {
  4650. MultipartFormDataItems files;
  4651. content_reader(
  4652. [&](const MultipartFormData &file) {
  4653. files.push_back(file);
  4654. return true;
  4655. },
  4656. [&](const char *data, size_t data_length) {
  4657. files.back().content.append(data, data_length);
  4658. return true;
  4659. });
  4660. EXPECT_TRUE(std::string(files[0].name) == "document");
  4661. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4662. EXPECT_TRUE(files[0].filename == "2MB_data");
  4663. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4664. EXPECT_TRUE(files[1].name == "hello");
  4665. EXPECT_TRUE(files[1].content == "world");
  4666. EXPECT_TRUE(files[1].filename == "");
  4667. EXPECT_TRUE(files[1].content_type == "");
  4668. } else {
  4669. std::string body;
  4670. content_reader([&](const char *data, size_t data_length) {
  4671. body.append(data, data_length);
  4672. return true;
  4673. });
  4674. }
  4675. });
  4676. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4677. while (!svr.is_running()) {
  4678. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4679. }
  4680. std::this_thread::sleep_for(std::chrono::seconds(1));
  4681. {
  4682. std::string data(1024 * 1024 * 2, '&');
  4683. std::stringstream buffer;
  4684. buffer << data;
  4685. Client cli("https://localhost:8080");
  4686. cli.enable_server_certificate_verification(false);
  4687. MultipartFormDataItems items{
  4688. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4689. {"hello", "world", "", ""},
  4690. };
  4691. auto res = cli.Put("/put", items);
  4692. ASSERT_TRUE(res);
  4693. ASSERT_EQ(200, res->status);
  4694. }
  4695. svr.stop();
  4696. t.join();
  4697. }
  4698. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  4699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4700. svr.Put("/put_customboundary",
  4701. [&](const Request &req, const Response & /*res*/,
  4702. const ContentReader &content_reader) {
  4703. if (req.is_multipart_form_data()) {
  4704. MultipartFormDataItems files;
  4705. content_reader(
  4706. [&](const MultipartFormData &file) {
  4707. files.push_back(file);
  4708. return true;
  4709. },
  4710. [&](const char *data, size_t data_length) {
  4711. files.back().content.append(data, data_length);
  4712. return true;
  4713. });
  4714. EXPECT_TRUE(std::string(files[0].name) == "document");
  4715. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4716. EXPECT_TRUE(files[0].filename == "2MB_data");
  4717. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4718. EXPECT_TRUE(files[1].name == "hello");
  4719. EXPECT_TRUE(files[1].content == "world");
  4720. EXPECT_TRUE(files[1].filename == "");
  4721. EXPECT_TRUE(files[1].content_type == "");
  4722. } else {
  4723. std::string body;
  4724. content_reader([&](const char *data, size_t data_length) {
  4725. body.append(data, data_length);
  4726. return true;
  4727. });
  4728. }
  4729. });
  4730. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4731. while (!svr.is_running()) {
  4732. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4733. }
  4734. std::this_thread::sleep_for(std::chrono::seconds(1));
  4735. {
  4736. std::string data(1024 * 1024 * 2, '&');
  4737. std::stringstream buffer;
  4738. buffer << data;
  4739. Client cli("https://localhost:8080");
  4740. cli.enable_server_certificate_verification(false);
  4741. MultipartFormDataItems items{
  4742. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4743. {"hello", "world", "", ""},
  4744. };
  4745. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  4746. ASSERT_TRUE(res);
  4747. ASSERT_EQ(200, res->status);
  4748. }
  4749. svr.stop();
  4750. t.join();
  4751. }
  4752. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  4753. std::this_thread::sleep_for(std::chrono::seconds(1));
  4754. std::string data(1024 * 1024 * 2, '&');
  4755. std::stringstream buffer;
  4756. buffer << data;
  4757. Client cli("https://localhost:8080");
  4758. cli.enable_server_certificate_verification(false);
  4759. MultipartFormDataItems items{
  4760. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4761. {"hello", "world", "", ""},
  4762. };
  4763. for (const char &c : " \t\r\n") {
  4764. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  4765. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4766. ASSERT_FALSE(res);
  4767. }
  4768. }
  4769. #endif
  4770. #ifndef _WIN32
  4771. class UnixSocketTest : public ::testing::Test {
  4772. protected:
  4773. void TearDown() override { std::remove(pathname_.c_str()); }
  4774. void client_GET(const std::string &addr) {
  4775. httplib::Client cli{addr};
  4776. cli.set_address_family(AF_UNIX);
  4777. ASSERT_TRUE(cli.is_valid());
  4778. const auto &result = cli.Get(pattern_);
  4779. ASSERT_TRUE(result) << "error: " << result.error();
  4780. const auto &resp = result.value();
  4781. EXPECT_EQ(resp.status, 200);
  4782. EXPECT_EQ(resp.body, content_);
  4783. }
  4784. const std::string pathname_{"./httplib-server.sock"};
  4785. const std::string pattern_{"/hi"};
  4786. const std::string content_{"Hello World!"};
  4787. };
  4788. TEST_F(UnixSocketTest, pathname) {
  4789. httplib::Server svr;
  4790. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  4791. res.set_content(content_, "text/plain");
  4792. });
  4793. std::thread t{[&] {
  4794. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  4795. }};
  4796. while (!svr.is_running()) {
  4797. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4798. }
  4799. ASSERT_TRUE(svr.is_running());
  4800. client_GET(pathname_);
  4801. svr.stop();
  4802. t.join();
  4803. }
  4804. #if defined(__linux__) || \
  4805. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  4806. TEST_F(UnixSocketTest, PeerPid) {
  4807. httplib::Server svr;
  4808. std::string remote_port_val;
  4809. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  4810. res.set_content(content_, "text/plain");
  4811. remote_port_val = req.get_header_value("REMOTE_PORT");
  4812. });
  4813. std::thread t{[&] {
  4814. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  4815. }};
  4816. while (!svr.is_running()) {
  4817. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4818. }
  4819. ASSERT_TRUE(svr.is_running());
  4820. client_GET(pathname_);
  4821. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  4822. svr.stop();
  4823. t.join();
  4824. }
  4825. #endif
  4826. #ifdef __linux__
  4827. TEST_F(UnixSocketTest, abstract) {
  4828. constexpr char svr_path[]{"\x00httplib-server.sock"};
  4829. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  4830. httplib::Server svr;
  4831. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  4832. res.set_content(content_, "text/plain");
  4833. });
  4834. std::thread t{[&] {
  4835. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  4836. }};
  4837. while (!svr.is_running()) {
  4838. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4839. }
  4840. ASSERT_TRUE(svr.is_running());
  4841. client_GET(abstract_addr);
  4842. svr.stop();
  4843. t.join();
  4844. }
  4845. #endif
  4846. TEST(SocketStream, is_writable_UNIX) {
  4847. int fds[2];
  4848. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  4849. const auto asSocketStream = [&](socket_t fd,
  4850. std::function<bool(Stream &)> func) {
  4851. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  4852. };
  4853. asSocketStream(fds[0], [&](Stream &s0) {
  4854. EXPECT_EQ(s0.socket(), fds[0]);
  4855. EXPECT_TRUE(s0.is_writable());
  4856. EXPECT_EQ(0, close(fds[1]));
  4857. EXPECT_FALSE(s0.is_writable());
  4858. return true;
  4859. });
  4860. EXPECT_EQ(0, close(fds[0]));
  4861. }
  4862. TEST(SocketStream, is_writable_INET) {
  4863. sockaddr_in addr;
  4864. memset(&addr, 0, sizeof(addr));
  4865. addr.sin_family = AF_INET;
  4866. addr.sin_port = htons(PORT + 1);
  4867. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4868. int disconnected_svr_sock = -1;
  4869. std::thread svr{[&] {
  4870. const int s = socket(AF_INET, SOCK_STREAM, 0);
  4871. ASSERT_LE(0, s);
  4872. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4873. ASSERT_EQ(0, listen(s, 1));
  4874. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  4875. ASSERT_EQ(0, close(s));
  4876. }};
  4877. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4878. std::thread cli{[&] {
  4879. const int s = socket(AF_INET, SOCK_STREAM, 0);
  4880. ASSERT_LE(0, s);
  4881. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4882. ASSERT_EQ(0, close(s));
  4883. }};
  4884. cli.join();
  4885. svr.join();
  4886. ASSERT_NE(disconnected_svr_sock, -1);
  4887. const auto asSocketStream = [&](socket_t fd,
  4888. std::function<bool(Stream &)> func) {
  4889. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  4890. };
  4891. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  4892. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  4893. EXPECT_FALSE(ss.is_writable());
  4894. return true;
  4895. });
  4896. ASSERT_EQ(0, close(disconnected_svr_sock));
  4897. }
  4898. #endif // #ifndef _WIN32
  4899. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  4900. static constexpr unsigned int number_of_task{1000000};
  4901. std::atomic_uint count{0};
  4902. std::unique_ptr<TaskQueue> task_queue{
  4903. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  4904. for (unsigned int i = 0; i < number_of_task; ++i) {
  4905. task_queue->enqueue(
  4906. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  4907. }
  4908. EXPECT_NO_THROW(task_queue->shutdown());
  4909. EXPECT_EQ(number_of_task, count.load());
  4910. }