test.cc 184 KB

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