test.cc 127 KB

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