test.cc 177 KB

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