test.cc 122 KB

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