test.cc 139 KB

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