test.cc 171 KB

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