test.cc 162 KB

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