test.cc 228 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606
  1. #include <httplib.h>
  2. #include <signal.h>
  3. #include <gtest/gtest.h>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <future>
  7. #include <limits>
  8. #include <memory>
  9. #include <sstream>
  10. #include <stdexcept>
  11. #include <thread>
  12. #include <type_traits>
  13. #define SERVER_CERT_FILE "./cert.pem"
  14. #define SERVER_CERT2_FILE "./cert2.pem"
  15. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  16. #define CA_CERT_FILE "./ca-bundle.crt"
  17. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  18. #define CLIENT_CA_CERT_DIR "."
  19. #define CLIENT_CERT_FILE "./client.cert.pem"
  20. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  21. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  22. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  23. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  24. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  25. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  26. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  27. using namespace std;
  28. using namespace httplib;
  29. const char *HOST = "localhost";
  30. const int PORT = 1234;
  31. const string LONG_QUERY_VALUE = string(25000, '@');
  32. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  33. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  34. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  35. MultipartFormData &get_file_value(MultipartFormDataItems &files,
  36. const char *key) {
  37. auto it = std::find_if(
  38. files.begin(), files.end(),
  39. [&](const MultipartFormData &file) { return file.name == key; });
  40. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  41. return *it;
  42. #else
  43. if (it != files.end()) { return *it; }
  44. throw std::runtime_error("invalid multipart form data name error");
  45. #endif
  46. }
  47. #ifndef _WIN32
  48. class UnixSocketTest : public ::testing::Test {
  49. protected:
  50. void TearDown() override { std::remove(pathname_.c_str()); }
  51. void client_GET(const std::string &addr) {
  52. httplib::Client cli{addr};
  53. cli.set_address_family(AF_UNIX);
  54. ASSERT_TRUE(cli.is_valid());
  55. const auto &result = cli.Get(pattern_);
  56. ASSERT_TRUE(result) << "error: " << result.error();
  57. const auto &resp = result.value();
  58. EXPECT_EQ(resp.status, StatusCode::OK_200);
  59. EXPECT_EQ(resp.body, content_);
  60. }
  61. const std::string pathname_{"./httplib-server.sock"};
  62. const std::string pattern_{"/hi"};
  63. const std::string content_{"Hello World!"};
  64. };
  65. TEST_F(UnixSocketTest, pathname) {
  66. httplib::Server svr;
  67. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  68. res.set_content(content_, "text/plain");
  69. });
  70. std::thread t{[&] {
  71. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  72. }};
  73. auto se = detail::scope_exit([&] {
  74. svr.stop();
  75. t.join();
  76. ASSERT_FALSE(svr.is_running());
  77. });
  78. svr.wait_until_ready();
  79. ASSERT_TRUE(svr.is_running());
  80. client_GET(pathname_);
  81. }
  82. #if defined(__linux__) || \
  83. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  84. TEST_F(UnixSocketTest, PeerPid) {
  85. httplib::Server svr;
  86. std::string remote_port_val;
  87. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  88. res.set_content(content_, "text/plain");
  89. remote_port_val = req.get_header_value("REMOTE_PORT");
  90. });
  91. std::thread t{[&] {
  92. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  93. }};
  94. auto se = detail::scope_exit([&] {
  95. svr.stop();
  96. t.join();
  97. ASSERT_FALSE(svr.is_running());
  98. });
  99. svr.wait_until_ready();
  100. ASSERT_TRUE(svr.is_running());
  101. client_GET(pathname_);
  102. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  103. }
  104. #endif
  105. #ifdef __linux__
  106. TEST_F(UnixSocketTest, abstract) {
  107. constexpr char svr_path[]{"\x00httplib-server.sock"};
  108. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  109. httplib::Server svr;
  110. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  111. res.set_content(content_, "text/plain");
  112. });
  113. std::thread t{[&] {
  114. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  115. }};
  116. auto se = detail::scope_exit([&] {
  117. svr.stop();
  118. t.join();
  119. ASSERT_FALSE(svr.is_running());
  120. });
  121. svr.wait_until_ready();
  122. ASSERT_TRUE(svr.is_running());
  123. client_GET(abstract_addr);
  124. }
  125. #endif
  126. TEST(SocketStream, is_writable_UNIX) {
  127. int fds[2];
  128. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  129. const auto asSocketStream = [&](socket_t fd,
  130. std::function<bool(Stream &)> func) {
  131. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  132. };
  133. asSocketStream(fds[0], [&](Stream &s0) {
  134. EXPECT_EQ(s0.socket(), fds[0]);
  135. EXPECT_TRUE(s0.is_writable());
  136. EXPECT_EQ(0, close(fds[1]));
  137. EXPECT_FALSE(s0.is_writable());
  138. return true;
  139. });
  140. EXPECT_EQ(0, close(fds[0]));
  141. }
  142. TEST(SocketStream, is_writable_INET) {
  143. sockaddr_in addr;
  144. memset(&addr, 0, sizeof(addr));
  145. addr.sin_family = AF_INET;
  146. addr.sin_port = htons(PORT + 1);
  147. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  148. int disconnected_svr_sock = -1;
  149. std::thread svr{[&] {
  150. const int s = socket(AF_INET, SOCK_STREAM, 0);
  151. ASSERT_LE(0, s);
  152. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  153. ASSERT_EQ(0, listen(s, 1));
  154. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  155. ASSERT_EQ(0, close(s));
  156. }};
  157. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  158. std::thread cli{[&] {
  159. const int s = socket(AF_INET, SOCK_STREAM, 0);
  160. ASSERT_LE(0, s);
  161. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  162. ASSERT_EQ(0, close(s));
  163. }};
  164. cli.join();
  165. svr.join();
  166. ASSERT_NE(disconnected_svr_sock, -1);
  167. const auto asSocketStream = [&](socket_t fd,
  168. std::function<bool(Stream &)> func) {
  169. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  170. };
  171. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  172. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  173. EXPECT_FALSE(ss.is_writable());
  174. return true;
  175. });
  176. ASSERT_EQ(0, close(disconnected_svr_sock));
  177. }
  178. #endif // #ifndef _WIN32
  179. TEST(ClientTest, MoveConstructible) {
  180. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  181. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  182. }
  183. TEST(ClientTest, MoveAssignable) {
  184. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  185. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  186. }
  187. #ifdef _WIN32
  188. TEST(StartupTest, WSAStartup) {
  189. WSADATA wsaData;
  190. int ret = WSAStartup(0x0002, &wsaData);
  191. ASSERT_EQ(0, ret);
  192. }
  193. #endif
  194. TEST(DecodeURLTest, PercentCharacter) {
  195. EXPECT_EQ(
  196. detail::decode_url(
  197. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)",
  198. false),
  199. R"(descrip=Gastos áéíóúñÑ 6)");
  200. }
  201. TEST(DecodeURLTest, PercentCharacterNUL) {
  202. string expected;
  203. expected.push_back('x');
  204. expected.push_back('\0');
  205. expected.push_back('x');
  206. EXPECT_EQ(detail::decode_url("x%00x", false), expected);
  207. }
  208. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  209. string unescapedCharacters = "-_.!~*'()";
  210. EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
  211. }
  212. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  213. string reservedCharacters = ";,/?:@&=+$";
  214. EXPECT_EQ(detail::encode_query_param(reservedCharacters),
  215. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  216. }
  217. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  218. string chineseCharacters = "中国語";
  219. string russianCharacters = "дом";
  220. string brazilianCharacters = "óculos";
  221. EXPECT_EQ(detail::encode_query_param(chineseCharacters),
  222. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  223. EXPECT_EQ(detail::encode_query_param(russianCharacters),
  224. "%D0%B4%D0%BE%D0%BC");
  225. EXPECT_EQ(detail::encode_query_param(brazilianCharacters), "%C3%B3culos");
  226. }
  227. TEST(TrimTests, TrimStringTests) {
  228. EXPECT_EQ("abc", detail::trim_copy("abc"));
  229. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  230. EXPECT_TRUE(detail::trim_copy("").empty());
  231. }
  232. TEST(DivideTest, DivideStringTests) {
  233. auto divide = [](const std::string &str, char d) {
  234. std::string lhs;
  235. std::string rhs;
  236. detail::divide(str, d,
  237. [&](const char *lhs_data, std::size_t lhs_size,
  238. const char *rhs_data, std::size_t rhs_size) {
  239. lhs.assign(lhs_data, lhs_size);
  240. rhs.assign(rhs_data, rhs_size);
  241. });
  242. return std::make_pair(std::move(lhs), std::move(rhs));
  243. };
  244. {
  245. const auto res = divide("", '=');
  246. EXPECT_EQ(res.first, "");
  247. EXPECT_EQ(res.second, "");
  248. }
  249. {
  250. const auto res = divide("=", '=');
  251. EXPECT_EQ(res.first, "");
  252. EXPECT_EQ(res.second, "");
  253. }
  254. {
  255. const auto res = divide(" ", '=');
  256. EXPECT_EQ(res.first, " ");
  257. EXPECT_EQ(res.second, "");
  258. }
  259. {
  260. const auto res = divide("a", '=');
  261. EXPECT_EQ(res.first, "a");
  262. EXPECT_EQ(res.second, "");
  263. }
  264. {
  265. const auto res = divide("a=", '=');
  266. EXPECT_EQ(res.first, "a");
  267. EXPECT_EQ(res.second, "");
  268. }
  269. {
  270. const auto res = divide("=b", '=');
  271. EXPECT_EQ(res.first, "");
  272. EXPECT_EQ(res.second, "b");
  273. }
  274. {
  275. const auto res = divide("a=b", '=');
  276. EXPECT_EQ(res.first, "a");
  277. EXPECT_EQ(res.second, "b");
  278. }
  279. {
  280. const auto res = divide("a=b=", '=');
  281. EXPECT_EQ(res.first, "a");
  282. EXPECT_EQ(res.second, "b=");
  283. }
  284. {
  285. const auto res = divide("a=b=c", '=');
  286. EXPECT_EQ(res.first, "a");
  287. EXPECT_EQ(res.second, "b=c");
  288. }
  289. }
  290. TEST(SplitTest, ParseQueryString) {
  291. string s = "key1=val1&key2=val2&key3=val3";
  292. Params dic;
  293. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  294. [&](const char *b, const char *e) {
  295. string key, val;
  296. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  297. if (key.empty()) {
  298. key.assign(b2, e2);
  299. } else {
  300. val.assign(b2, e2);
  301. }
  302. });
  303. dic.emplace(key, val);
  304. });
  305. EXPECT_EQ("val1", dic.find("key1")->second);
  306. EXPECT_EQ("val2", dic.find("key2")->second);
  307. EXPECT_EQ("val3", dic.find("key3")->second);
  308. }
  309. TEST(SplitTest, ParseInvalidQueryTests) {
  310. {
  311. string s = " ";
  312. Params dict;
  313. detail::parse_query_text(s, dict);
  314. EXPECT_TRUE(dict.empty());
  315. }
  316. {
  317. string s = " = =";
  318. Params dict;
  319. detail::parse_query_text(s, dict);
  320. EXPECT_TRUE(dict.empty());
  321. }
  322. }
  323. TEST(ParseQueryTest, ParseQueryString) {
  324. {
  325. std::string s = "key1=val1&key2=val2&key3=val3";
  326. Params dic;
  327. detail::parse_query_text(s, dic);
  328. EXPECT_EQ("val1", dic.find("key1")->second);
  329. EXPECT_EQ("val2", dic.find("key2")->second);
  330. EXPECT_EQ("val3", dic.find("key3")->second);
  331. }
  332. {
  333. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  334. Params dic;
  335. detail::parse_query_text(s, dic);
  336. EXPECT_EQ("", dic.find("key1")->second);
  337. EXPECT_EQ("val1", dic.find("key2")->second);
  338. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  339. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  340. }
  341. }
  342. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  343. Params dic;
  344. EXPECT_EQ(detail::params_to_query_str(dic), "");
  345. dic.emplace("key1", "val1");
  346. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  347. dic.emplace("key2", "val2");
  348. dic.emplace("key3", "val3");
  349. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  350. }
  351. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  352. string content_type = "multipart/form-data; boundary=something";
  353. string boundary;
  354. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  355. EXPECT_TRUE(ret);
  356. EXPECT_EQ(boundary, "something");
  357. }
  358. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  359. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  360. string boundary;
  361. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  362. EXPECT_TRUE(ret);
  363. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  364. }
  365. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  366. string content_type =
  367. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  368. string boundary;
  369. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  370. EXPECT_TRUE(ret);
  371. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  372. }
  373. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  374. string content_type =
  375. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  376. string boundary;
  377. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  378. EXPECT_TRUE(ret);
  379. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  380. }
  381. TEST(GetHeaderValueTest, DefaultValue) {
  382. Headers headers = {{"Dummy", "Dummy"}};
  383. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  384. EXPECT_STREQ("text/plain", val);
  385. }
  386. TEST(GetHeaderValueTest, DefaultValueInt) {
  387. Headers headers = {{"Dummy", "Dummy"}};
  388. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  389. EXPECT_EQ(100ull, val);
  390. }
  391. TEST(GetHeaderValueTest, RegularValue) {
  392. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  393. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  394. EXPECT_STREQ("text/html", val);
  395. }
  396. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  397. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  398. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  399. EXPECT_STREQ("text/html", val);
  400. }
  401. TEST(GetHeaderValueTest, SetContent) {
  402. Response res;
  403. res.set_content("html", "text/html");
  404. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  405. res.set_content("text", "text/plain");
  406. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  407. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  408. }
  409. TEST(GetHeaderValueTest, RegularValueInt) {
  410. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  411. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  412. EXPECT_EQ(100ull, val);
  413. }
  414. TEST(GetHeaderValueTest, Range) {
  415. {
  416. Headers headers = {make_range_header({{1, -1}})};
  417. auto val = detail::get_header_value(headers, "Range", 0, 0);
  418. EXPECT_STREQ("bytes=1-", val);
  419. }
  420. {
  421. Headers headers = {make_range_header({{-1, 1}})};
  422. auto val = detail::get_header_value(headers, "Range", 0, 0);
  423. EXPECT_STREQ("bytes=-1", val);
  424. }
  425. {
  426. Headers headers = {make_range_header({{1, 10}})};
  427. auto val = detail::get_header_value(headers, "Range", 0, 0);
  428. EXPECT_STREQ("bytes=1-10", val);
  429. }
  430. {
  431. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  432. auto val = detail::get_header_value(headers, "Range", 0, 0);
  433. EXPECT_STREQ("bytes=1-10, 100-", val);
  434. }
  435. {
  436. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  437. auto val = detail::get_header_value(headers, "Range", 0, 0);
  438. EXPECT_STREQ("bytes=1-10, 100-200", val);
  439. }
  440. {
  441. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  442. auto val = detail::get_header_value(headers, "Range", 0, 0);
  443. EXPECT_STREQ("bytes=0-0, -1", val);
  444. }
  445. }
  446. TEST(ParseHeaderValueTest, Range) {
  447. {
  448. Ranges ranges;
  449. auto ret = detail::parse_range_header("bytes=1-", ranges);
  450. EXPECT_TRUE(ret);
  451. EXPECT_EQ(1u, ranges.size());
  452. EXPECT_EQ(1u, ranges[0].first);
  453. EXPECT_EQ(-1, ranges[0].second);
  454. }
  455. {
  456. Ranges ranges;
  457. auto ret = detail::parse_range_header("bytes=-1", ranges);
  458. EXPECT_TRUE(ret);
  459. EXPECT_EQ(1u, ranges.size());
  460. EXPECT_EQ(-1, ranges[0].first);
  461. EXPECT_EQ(1u, ranges[0].second);
  462. }
  463. {
  464. Ranges ranges;
  465. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  466. EXPECT_TRUE(ret);
  467. EXPECT_EQ(1u, ranges.size());
  468. EXPECT_EQ(1u, ranges[0].first);
  469. EXPECT_EQ(10u, ranges[0].second);
  470. }
  471. {
  472. Ranges ranges;
  473. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  474. EXPECT_FALSE(ret);
  475. }
  476. {
  477. Ranges ranges;
  478. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  479. EXPECT_TRUE(ret);
  480. EXPECT_EQ(2u, ranges.size());
  481. EXPECT_EQ(1u, ranges[0].first);
  482. EXPECT_EQ(10u, ranges[0].second);
  483. EXPECT_EQ(100u, ranges[1].first);
  484. EXPECT_EQ(-1, ranges[1].second);
  485. }
  486. {
  487. Ranges ranges;
  488. auto ret =
  489. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  490. EXPECT_TRUE(ret);
  491. EXPECT_EQ(3u, ranges.size());
  492. EXPECT_EQ(1u, ranges[0].first);
  493. EXPECT_EQ(10u, ranges[0].second);
  494. EXPECT_EQ(100u, ranges[1].first);
  495. EXPECT_EQ(200u, ranges[1].second);
  496. EXPECT_EQ(300u, ranges[2].first);
  497. EXPECT_EQ(400u, ranges[2].second);
  498. }
  499. {
  500. Ranges ranges;
  501. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  502. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  503. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  504. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  505. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  506. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  507. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  508. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  509. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  510. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  511. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  512. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  513. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  514. EXPECT_TRUE(ranges.empty());
  515. }
  516. }
  517. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  518. Request req;
  519. req.set_header("Accept-Encoding", "gzip");
  520. Response res;
  521. res.set_header("Content-Type", "text/plain");
  522. auto ret = detail::encoding_type(req, res);
  523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  524. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  525. #else
  526. EXPECT_TRUE(ret == detail::EncodingType::None);
  527. #endif
  528. }
  529. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  530. Request req;
  531. req.set_header("Accept-Encoding", "gzip, deflate, br");
  532. Response res;
  533. res.set_header("Content-Type", "text/plain");
  534. auto ret = detail::encoding_type(req, res);
  535. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  536. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  537. #elif CPPHTTPLIB_ZLIB_SUPPORT
  538. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  539. #else
  540. EXPECT_TRUE(ret == detail::EncodingType::None);
  541. #endif
  542. }
  543. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  544. Request req;
  545. req.set_header("Accept-Encoding", "br;q=1.0, gzip;q=0.8, *;q=0.1");
  546. Response res;
  547. res.set_header("Content-Type", "text/plain");
  548. auto ret = detail::encoding_type(req, res);
  549. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  550. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  551. #elif CPPHTTPLIB_ZLIB_SUPPORT
  552. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  553. #else
  554. EXPECT_TRUE(ret == detail::EncodingType::None);
  555. #endif
  556. }
  557. TEST(BufferStreamTest, read) {
  558. detail::BufferStream strm1;
  559. Stream &strm = strm1;
  560. EXPECT_EQ(5, strm.write("hello"));
  561. char buf[512];
  562. EXPECT_EQ(2, strm.read(buf, 2));
  563. EXPECT_EQ('h', buf[0]);
  564. EXPECT_EQ('e', buf[1]);
  565. EXPECT_EQ(2, strm.read(buf, 2));
  566. EXPECT_EQ('l', buf[0]);
  567. EXPECT_EQ('l', buf[1]);
  568. EXPECT_EQ(1, strm.read(buf, 1));
  569. EXPECT_EQ('o', buf[0]);
  570. EXPECT_EQ(0, strm.read(buf, 1));
  571. }
  572. TEST(ChunkedEncodingTest, FromHTTPWatch_Online) {
  573. auto host = "www.httpwatch.com";
  574. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  575. auto port = 443;
  576. SSLClient cli(host, port);
  577. #else
  578. auto port = 80;
  579. Client cli(host, port);
  580. #endif
  581. cli.set_connection_timeout(2);
  582. auto res =
  583. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137");
  584. ASSERT_TRUE(res);
  585. std::string out;
  586. detail::read_file("./image.jpg", out);
  587. EXPECT_EQ(StatusCode::OK_200, res->status);
  588. EXPECT_EQ(out, res->body);
  589. }
  590. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  591. auto host = "www.httpwatch.com";
  592. auto ip = hosted_at(host);
  593. EXPECT_EQ("23.96.13.243", ip);
  594. std::vector<std::string> addrs;
  595. hosted_at(host, addrs);
  596. EXPECT_EQ(1u, addrs.size());
  597. }
  598. #if 0 // It depends on each test environment...
  599. TEST(HostnameToIPConversionTest, YouTube_Online) {
  600. auto host = "www.youtube.com";
  601. std::vector<std::string> addrs;
  602. hosted_at(host, addrs);
  603. EXPECT_EQ(20u, addrs.size());
  604. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  605. EXPECT_TRUE(it != addrs.end());
  606. }
  607. #endif
  608. TEST(ChunkedEncodingTest, WithContentReceiver_Online) {
  609. auto host = "www.httpwatch.com";
  610. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  611. auto port = 443;
  612. SSLClient cli(host, port);
  613. #else
  614. auto port = 80;
  615. Client cli(host, port);
  616. #endif
  617. cli.set_connection_timeout(2);
  618. std::string body;
  619. auto res =
  620. cli.Get("/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  621. [&](const char *data, size_t data_length) {
  622. body.append(data, data_length);
  623. return true;
  624. });
  625. ASSERT_TRUE(res);
  626. std::string out;
  627. detail::read_file("./image.jpg", out);
  628. EXPECT_EQ(StatusCode::OK_200, res->status);
  629. EXPECT_EQ(out, body);
  630. }
  631. TEST(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver_Online) {
  632. auto host = "www.httpwatch.com";
  633. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  634. auto port = 443;
  635. SSLClient cli(host, port);
  636. #else
  637. auto port = 80;
  638. Client cli(host, port);
  639. #endif
  640. cli.set_connection_timeout(2);
  641. std::string body;
  642. auto res = cli.Get(
  643. "/httpgallery/chunked/chunkedimage.aspx?0.4153841143030137",
  644. [&](const Response &response) {
  645. EXPECT_EQ(StatusCode::OK_200, response.status);
  646. return true;
  647. },
  648. [&](const char *data, size_t data_length) {
  649. body.append(data, data_length);
  650. return true;
  651. });
  652. ASSERT_TRUE(res);
  653. std::string out;
  654. detail::read_file("./image.jpg", out);
  655. EXPECT_EQ(StatusCode::OK_200, res->status);
  656. EXPECT_EQ(out, body);
  657. }
  658. TEST(RangeTest, FromHTTPBin_Online) {
  659. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  660. auto host = "httpbin.org";
  661. auto path = std::string{"/range/32"};
  662. #else
  663. auto host = "nghttp2.org";
  664. auto path = std::string{"/httpbin/range/32"};
  665. #endif
  666. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  667. auto port = 443;
  668. SSLClient cli(host, port);
  669. #else
  670. auto port = 80;
  671. Client cli(host, port);
  672. #endif
  673. cli.set_connection_timeout(5);
  674. {
  675. auto res = cli.Get(path);
  676. ASSERT_TRUE(res);
  677. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  678. EXPECT_EQ(StatusCode::OK_200, res->status);
  679. }
  680. {
  681. Headers headers = {make_range_header({{1, -1}})};
  682. auto res = cli.Get(path, headers);
  683. ASSERT_TRUE(res);
  684. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  686. }
  687. {
  688. Headers headers = {make_range_header({{1, 10}})};
  689. auto res = cli.Get(path, headers);
  690. ASSERT_TRUE(res);
  691. EXPECT_EQ("bcdefghijk", res->body);
  692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  693. }
  694. {
  695. Headers headers = {make_range_header({{0, 31}})};
  696. auto res = cli.Get(path, headers);
  697. ASSERT_TRUE(res);
  698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  699. EXPECT_EQ(StatusCode::OK_200, res->status);
  700. }
  701. {
  702. Headers headers = {make_range_header({{0, -1}})};
  703. auto res = cli.Get(path, headers);
  704. ASSERT_TRUE(res);
  705. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  706. EXPECT_EQ(StatusCode::OK_200, res->status);
  707. }
  708. {
  709. Headers headers = {make_range_header({{0, 32}})};
  710. auto res = cli.Get(path, headers);
  711. ASSERT_TRUE(res);
  712. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  713. }
  714. }
  715. TEST(ConnectionErrorTest, InvalidHost) {
  716. auto host = "-abcde.com";
  717. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  718. auto port = 443;
  719. SSLClient cli(host, port);
  720. #else
  721. auto port = 80;
  722. Client cli(host, port);
  723. #endif
  724. cli.set_connection_timeout(std::chrono::seconds(2));
  725. auto res = cli.Get("/");
  726. ASSERT_TRUE(!res);
  727. EXPECT_EQ(Error::Connection, res.error());
  728. }
  729. TEST(ConnectionErrorTest, InvalidHost2) {
  730. auto host = "httpbin.org/";
  731. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  732. SSLClient cli(host);
  733. #else
  734. Client cli(host);
  735. #endif
  736. cli.set_connection_timeout(std::chrono::seconds(2));
  737. auto res = cli.Get("/");
  738. ASSERT_TRUE(!res);
  739. EXPECT_EQ(Error::Connection, res.error());
  740. }
  741. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  742. auto host = "httpbin.org/";
  743. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  744. SSLClient cli(host);
  745. #else
  746. Client cli(host);
  747. #endif
  748. cli.set_connection_timeout(std::chrono::seconds(2));
  749. auto res = cli.Get("/");
  750. ASSERT_TRUE(!res);
  751. stringstream s;
  752. s << "error code: " << res.error();
  753. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  754. }
  755. TEST(ConnectionErrorTest, InvalidPort) {
  756. auto host = "localhost";
  757. auto port = 44380;
  758. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  759. SSLClient cli(host, port);
  760. #else
  761. Client cli(host, port);
  762. #endif
  763. cli.set_connection_timeout(std::chrono::seconds(2));
  764. auto res = cli.Get("/");
  765. ASSERT_TRUE(!res);
  766. EXPECT_TRUE(Error::Connection == res.error() ||
  767. Error::ConnectionTimeout == res.error());
  768. }
  769. TEST(ConnectionErrorTest, Timeout_Online) {
  770. auto host = "google.com";
  771. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  772. auto port = 44380;
  773. SSLClient cli(host, port);
  774. #else
  775. auto port = 8080;
  776. Client cli(host, port);
  777. #endif
  778. cli.set_connection_timeout(std::chrono::seconds(2));
  779. // only probe one address type so that the error reason
  780. // correlates to the timed-out IPv4, not the unsupported
  781. // IPv6 connection attempt
  782. cli.set_address_family(AF_INET);
  783. auto res = cli.Get("/");
  784. ASSERT_TRUE(!res);
  785. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  786. }
  787. TEST(CancelTest, NoCancel_Online) {
  788. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  789. auto host = "httpbin.org";
  790. auto path = std::string{"/range/32"};
  791. #else
  792. auto host = "nghttp2.org";
  793. auto path = std::string{"/httpbin/range/32"};
  794. #endif
  795. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  796. auto port = 443;
  797. SSLClient cli(host, port);
  798. #else
  799. auto port = 80;
  800. Client cli(host, port);
  801. #endif
  802. cli.set_connection_timeout(std::chrono::seconds(5));
  803. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  804. ASSERT_TRUE(res);
  805. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  806. EXPECT_EQ(StatusCode::OK_200, res->status);
  807. }
  808. TEST(CancelTest, WithCancelSmallPayload_Online) {
  809. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  810. auto host = "httpbin.org";
  811. auto path = std::string{"/range/32"};
  812. #else
  813. auto host = "nghttp2.org";
  814. auto path = std::string{"/httpbin/range/32"};
  815. #endif
  816. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  817. auto port = 443;
  818. SSLClient cli(host, port);
  819. #else
  820. auto port = 80;
  821. Client cli(host, port);
  822. #endif
  823. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  824. cli.set_connection_timeout(std::chrono::seconds(5));
  825. ASSERT_TRUE(!res);
  826. EXPECT_EQ(Error::Canceled, res.error());
  827. }
  828. TEST(CancelTest, WithCancelLargePayload_Online) {
  829. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  830. auto host = "httpbin.org";
  831. auto path = std::string{"/range/65536"};
  832. #else
  833. auto host = "nghttp2.org";
  834. auto path = std::string{"/httpbin/range/65536"};
  835. #endif
  836. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  837. auto port = 443;
  838. SSLClient cli(host, port);
  839. #else
  840. auto port = 80;
  841. Client cli(host, port);
  842. #endif
  843. cli.set_connection_timeout(std::chrono::seconds(5));
  844. uint32_t count = 0;
  845. auto res =
  846. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  847. ASSERT_TRUE(!res);
  848. EXPECT_EQ(Error::Canceled, res.error());
  849. }
  850. TEST(CancelTest, NoCancelPost) {
  851. Server svr;
  852. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  853. res.set_content("Hello World!", "text/plain");
  854. });
  855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  856. auto se = detail::scope_exit([&] {
  857. svr.stop();
  858. thread.join();
  859. ASSERT_FALSE(svr.is_running());
  860. });
  861. svr.wait_until_ready();
  862. Client cli(HOST, PORT);
  863. cli.set_connection_timeout(std::chrono::seconds(5));
  864. auto res =
  865. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  866. "application/json", [](uint64_t, uint64_t) { return true; });
  867. ASSERT_TRUE(res);
  868. EXPECT_EQ("Hello World!", res->body);
  869. EXPECT_EQ(StatusCode::OK_200, res->status);
  870. }
  871. TEST(CancelTest, WithCancelSmallPayloadPost) {
  872. Server svr;
  873. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  874. res.set_content("Hello World!", "text/plain");
  875. });
  876. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  877. auto se = detail::scope_exit([&] {
  878. svr.stop();
  879. thread.join();
  880. ASSERT_FALSE(svr.is_running());
  881. });
  882. svr.wait_until_ready();
  883. Client cli(HOST, PORT);
  884. cli.set_connection_timeout(std::chrono::seconds(5));
  885. auto res =
  886. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  887. "application/json", [](uint64_t, uint64_t) { return false; });
  888. ASSERT_TRUE(!res);
  889. EXPECT_EQ(Error::Canceled, res.error());
  890. }
  891. TEST(CancelTest, WithCancelLargePayloadPost) {
  892. Server svr;
  893. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  894. res.set_content(LARGE_DATA, "text/plain");
  895. });
  896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  897. auto se = detail::scope_exit([&] {
  898. svr.stop();
  899. thread.join();
  900. ASSERT_FALSE(svr.is_running());
  901. });
  902. svr.wait_until_ready();
  903. Client cli(HOST, PORT);
  904. cli.set_connection_timeout(std::chrono::seconds(5));
  905. auto res =
  906. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  907. "application/json", [](uint64_t, uint64_t) { return false; });
  908. ASSERT_TRUE(!res);
  909. EXPECT_EQ(Error::Canceled, res.error());
  910. }
  911. TEST(CancelTest, NoCancelPut) {
  912. Server svr;
  913. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  914. res.set_content("Hello World!", "text/plain");
  915. });
  916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  917. auto se = detail::scope_exit([&] {
  918. svr.stop();
  919. thread.join();
  920. ASSERT_FALSE(svr.is_running());
  921. });
  922. svr.wait_until_ready();
  923. Client cli(HOST, PORT);
  924. cli.set_connection_timeout(std::chrono::seconds(5));
  925. auto res =
  926. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  927. "application/json", [](uint64_t, uint64_t) { return true; });
  928. ASSERT_TRUE(res);
  929. EXPECT_EQ("Hello World!", res->body);
  930. EXPECT_EQ(StatusCode::OK_200, res->status);
  931. }
  932. TEST(CancelTest, WithCancelSmallPayloadPut) {
  933. Server svr;
  934. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  935. res.set_content("Hello World!", "text/plain");
  936. });
  937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  938. auto se = detail::scope_exit([&] {
  939. svr.stop();
  940. thread.join();
  941. ASSERT_FALSE(svr.is_running());
  942. });
  943. svr.wait_until_ready();
  944. Client cli(HOST, PORT);
  945. cli.set_connection_timeout(std::chrono::seconds(5));
  946. auto res =
  947. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  948. "application/json", [](uint64_t, uint64_t) { return false; });
  949. ASSERT_TRUE(!res);
  950. EXPECT_EQ(Error::Canceled, res.error());
  951. }
  952. TEST(CancelTest, WithCancelLargePayloadPut) {
  953. Server svr;
  954. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  955. res.set_content(LARGE_DATA, "text/plain");
  956. });
  957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  958. auto se = detail::scope_exit([&] {
  959. svr.stop();
  960. thread.join();
  961. ASSERT_FALSE(svr.is_running());
  962. });
  963. svr.wait_until_ready();
  964. Client cli(HOST, PORT);
  965. cli.set_connection_timeout(std::chrono::seconds(5));
  966. auto res =
  967. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  968. "application/json", [](uint64_t, uint64_t) { return false; });
  969. ASSERT_TRUE(!res);
  970. EXPECT_EQ(Error::Canceled, res.error());
  971. }
  972. TEST(CancelTest, NoCancelPatch) {
  973. Server svr;
  974. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  975. res.set_content("Hello World!", "text/plain");
  976. });
  977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  978. auto se = detail::scope_exit([&] {
  979. svr.stop();
  980. thread.join();
  981. ASSERT_FALSE(svr.is_running());
  982. });
  983. svr.wait_until_ready();
  984. Client cli(HOST, PORT);
  985. cli.set_connection_timeout(std::chrono::seconds(5));
  986. auto res =
  987. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  988. "application/json", [](uint64_t, uint64_t) { return true; });
  989. ASSERT_TRUE(res);
  990. EXPECT_EQ("Hello World!", res->body);
  991. EXPECT_EQ(StatusCode::OK_200, res->status);
  992. }
  993. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  994. Server svr;
  995. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  996. res.set_content("Hello World!", "text/plain");
  997. });
  998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  999. auto se = detail::scope_exit([&] {
  1000. svr.stop();
  1001. thread.join();
  1002. ASSERT_FALSE(svr.is_running());
  1003. });
  1004. svr.wait_until_ready();
  1005. Client cli(HOST, PORT);
  1006. cli.set_connection_timeout(std::chrono::seconds(5));
  1007. auto res =
  1008. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1009. "application/json", [](uint64_t, uint64_t) { return false; });
  1010. ASSERT_TRUE(!res);
  1011. EXPECT_EQ(Error::Canceled, res.error());
  1012. }
  1013. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1014. Server svr;
  1015. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1016. res.set_content(LARGE_DATA, "text/plain");
  1017. });
  1018. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1019. auto se = detail::scope_exit([&] {
  1020. svr.stop();
  1021. thread.join();
  1022. ASSERT_FALSE(svr.is_running());
  1023. });
  1024. svr.wait_until_ready();
  1025. Client cli(HOST, PORT);
  1026. cli.set_connection_timeout(std::chrono::seconds(5));
  1027. auto res =
  1028. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1029. "application/json", [](uint64_t, uint64_t) { return false; });
  1030. ASSERT_TRUE(!res);
  1031. EXPECT_EQ(Error::Canceled, res.error());
  1032. }
  1033. TEST(CancelTest, NoCancelDelete) {
  1034. Server svr;
  1035. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1036. res.set_content("Hello World!", "text/plain");
  1037. });
  1038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1039. auto se = detail::scope_exit([&] {
  1040. svr.stop();
  1041. thread.join();
  1042. ASSERT_FALSE(svr.is_running());
  1043. });
  1044. svr.wait_until_ready();
  1045. Client cli(HOST, PORT);
  1046. cli.set_connection_timeout(std::chrono::seconds(5));
  1047. auto res =
  1048. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1049. "application/json", [](uint64_t, uint64_t) { return true; });
  1050. ASSERT_TRUE(res);
  1051. EXPECT_EQ("Hello World!", res->body);
  1052. EXPECT_EQ(StatusCode::OK_200, res->status);
  1053. }
  1054. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1055. Server svr;
  1056. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1057. res.set_content("Hello World!", "text/plain");
  1058. });
  1059. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1060. auto se = detail::scope_exit([&] {
  1061. svr.stop();
  1062. thread.join();
  1063. ASSERT_FALSE(svr.is_running());
  1064. });
  1065. svr.wait_until_ready();
  1066. Client cli(HOST, PORT);
  1067. cli.set_connection_timeout(std::chrono::seconds(5));
  1068. auto res =
  1069. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1070. "application/json", [](uint64_t, uint64_t) { return false; });
  1071. ASSERT_TRUE(!res);
  1072. EXPECT_EQ(Error::Canceled, res.error());
  1073. }
  1074. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1075. Server svr;
  1076. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1077. res.set_content(LARGE_DATA, "text/plain");
  1078. });
  1079. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1080. auto se = detail::scope_exit([&] {
  1081. svr.stop();
  1082. thread.join();
  1083. ASSERT_FALSE(svr.is_running());
  1084. });
  1085. svr.wait_until_ready();
  1086. Client cli(HOST, PORT);
  1087. cli.set_connection_timeout(std::chrono::seconds(5));
  1088. auto res =
  1089. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1090. "application/json", [](uint64_t, uint64_t) { return false; });
  1091. ASSERT_TRUE(!res);
  1092. EXPECT_EQ(Error::Canceled, res.error());
  1093. }
  1094. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1095. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1096. auto host = "httpbin.org";
  1097. auto path = std::string{"/basic-auth/hello/world"};
  1098. #else
  1099. auto host = "nghttp2.org";
  1100. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1101. #endif
  1102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1103. auto port = 443;
  1104. SSLClient cli(host, port);
  1105. #else
  1106. auto port = 80;
  1107. Client cli(host, port);
  1108. #endif
  1109. {
  1110. auto res = cli.Get(path);
  1111. ASSERT_TRUE(res);
  1112. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1113. }
  1114. {
  1115. auto res =
  1116. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1117. ASSERT_TRUE(res);
  1118. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1119. res->body);
  1120. EXPECT_EQ(StatusCode::OK_200, res->status);
  1121. }
  1122. {
  1123. cli.set_basic_auth("hello", "world");
  1124. auto res = cli.Get(path);
  1125. ASSERT_TRUE(res);
  1126. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1127. res->body);
  1128. EXPECT_EQ(StatusCode::OK_200, res->status);
  1129. }
  1130. {
  1131. cli.set_basic_auth("hello", "bad");
  1132. auto res = cli.Get(path);
  1133. ASSERT_TRUE(res);
  1134. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1135. }
  1136. {
  1137. cli.set_basic_auth("bad", "world");
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1141. }
  1142. }
  1143. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1144. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1145. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1146. auto host = "httpbin.org";
  1147. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1148. auto paths = std::vector<std::string>{
  1149. "/digest-auth/auth/hello/world/MD5",
  1150. "/digest-auth/auth/hello/world/SHA-256",
  1151. "/digest-auth/auth/hello/world/SHA-512",
  1152. "/digest-auth/auth-int/hello/world/MD5",
  1153. };
  1154. #else
  1155. auto host = "nghttp2.org";
  1156. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1157. auto paths = std::vector<std::string>{
  1158. "/httpbin/digest-auth/auth/hello/world/MD5",
  1159. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1160. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1161. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1162. };
  1163. #endif
  1164. auto port = 443;
  1165. SSLClient cli(host, port);
  1166. {
  1167. auto res = cli.Get(unauth_path);
  1168. ASSERT_TRUE(res);
  1169. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1170. }
  1171. {
  1172. cli.set_digest_auth("hello", "world");
  1173. for (const auto &path : paths) {
  1174. auto res = cli.Get(path.c_str());
  1175. ASSERT_TRUE(res);
  1176. EXPECT_EQ("{\n \"authenticated\": true, \n \"user\": \"hello\"\n}\n",
  1177. res->body);
  1178. EXPECT_EQ(StatusCode::OK_200, res->status);
  1179. }
  1180. cli.set_digest_auth("hello", "bad");
  1181. for (const auto &path : paths) {
  1182. auto res = cli.Get(path.c_str());
  1183. ASSERT_TRUE(res);
  1184. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1185. }
  1186. // NOTE: Until httpbin.org fixes issue #46, the following test is commented
  1187. // out. Please see https://httpbin.org/digest-auth/auth/hello/world
  1188. // cli.set_digest_auth("bad", "world");
  1189. // for (const auto& path : paths) {
  1190. // auto res = cli.Get(path.c_str());
  1191. // ASSERT_TRUE(res);
  1192. // EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1193. // }
  1194. }
  1195. }
  1196. #endif
  1197. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1198. auto host = "google.com";
  1199. auto another_host = "example.com";
  1200. auto wrong_ip = "0.0.0.0";
  1201. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1202. SSLClient cli(host);
  1203. #else
  1204. Client cli(host);
  1205. #endif
  1206. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1207. auto res = cli.Get("/");
  1208. ASSERT_TRUE(res);
  1209. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1210. }
  1211. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1212. auto host = "google.com";
  1213. auto wrong_ip = "0.0.0.0";
  1214. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1215. SSLClient cli(host);
  1216. #else
  1217. Client cli(host);
  1218. #endif
  1219. cli.set_hostname_addr_map({{host, wrong_ip}});
  1220. auto res = cli.Get("/");
  1221. ASSERT_TRUE(!res);
  1222. EXPECT_EQ(Error::Connection, res.error());
  1223. }
  1224. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1225. auto host = "nghttp2.org";
  1226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1227. SSLClient cli(host);
  1228. #else
  1229. Client cli(host);
  1230. #endif
  1231. cli.set_follow_location(true);
  1232. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1233. ASSERT_TRUE(res);
  1234. EXPECT_EQ(StatusCode::OK_200, res->status);
  1235. }
  1236. TEST(RedirectTest, Redirect_Online) {
  1237. auto host = "nghttp2.org";
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host);
  1240. #else
  1241. Client cli(host);
  1242. #endif
  1243. cli.set_follow_location(true);
  1244. auto res = cli.Get("/httpbin/redirect/3");
  1245. ASSERT_TRUE(res);
  1246. EXPECT_EQ(StatusCode::OK_200, res->status);
  1247. }
  1248. TEST(RelativeRedirectTest, Redirect_Online) {
  1249. auto host = "nghttp2.org";
  1250. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1251. SSLClient cli(host);
  1252. #else
  1253. Client cli(host);
  1254. #endif
  1255. cli.set_follow_location(true);
  1256. auto res = cli.Get("/httpbin/relative-redirect/3");
  1257. ASSERT_TRUE(res);
  1258. EXPECT_EQ(StatusCode::OK_200, res->status);
  1259. }
  1260. TEST(TooManyRedirectTest, Redirect_Online) {
  1261. auto host = "nghttp2.org";
  1262. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1263. SSLClient cli(host);
  1264. #else
  1265. Client cli(host);
  1266. #endif
  1267. cli.set_follow_location(true);
  1268. auto res = cli.Get("/httpbin/redirect/21");
  1269. ASSERT_TRUE(!res);
  1270. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1271. }
  1272. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1273. TEST(YahooRedirectTest, Redirect_Online) {
  1274. Client cli("yahoo.com");
  1275. auto res = cli.Get("/");
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1278. cli.set_follow_location(true);
  1279. res = cli.Get("/");
  1280. ASSERT_TRUE(res);
  1281. EXPECT_EQ(StatusCode::OK_200, res->status);
  1282. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1283. }
  1284. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1285. SSLClient cli("nghttp2.org");
  1286. cli.set_follow_location(true);
  1287. auto res = cli.Get(
  1288. "/httpbin/redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  1289. ASSERT_TRUE(res);
  1290. EXPECT_EQ(StatusCode::OK_200, res->status);
  1291. }
  1292. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1293. SSLClient cli("nghttp2.org");
  1294. cli.set_follow_location(true);
  1295. Params params;
  1296. params.emplace("url", "http://www.google.com");
  1297. params.emplace("status_code", "302");
  1298. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  1299. ASSERT_TRUE(res);
  1300. EXPECT_EQ(StatusCode::OK_200, res->status);
  1301. }
  1302. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1303. SSLClient cli("nghttp2.org");
  1304. cli.set_follow_location(true);
  1305. Params params;
  1306. params.emplace("url", "http://www.google.com");
  1307. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  1308. ASSERT_TRUE(res);
  1309. EXPECT_EQ(StatusCode::OK_200, res->status);
  1310. }
  1311. TEST(UrlWithSpace, Redirect_Online) {
  1312. SSLClient cli("edge.forgecdn.net");
  1313. cli.set_follow_location(true);
  1314. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1315. ASSERT_TRUE(res);
  1316. EXPECT_EQ(StatusCode::OK_200, res->status);
  1317. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1318. }
  1319. #endif
  1320. #if !defined(_WIN32) && !defined(_WIN64)
  1321. TEST(ReceiveSignals, Signal) {
  1322. auto setupSignalHandlers = []() {
  1323. struct sigaction act;
  1324. sigemptyset(&act.sa_mask);
  1325. act.sa_flags = SA_SIGINFO;
  1326. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1327. switch (sig) {
  1328. case SIGINT:
  1329. default: break;
  1330. }
  1331. };
  1332. ::sigaction(SIGINT, &act, nullptr);
  1333. };
  1334. Server svr;
  1335. int port = 0;
  1336. auto thread = std::thread([&]() {
  1337. setupSignalHandlers();
  1338. port = svr.bind_to_any_port("localhost");
  1339. svr.listen_after_bind();
  1340. });
  1341. auto se = detail::scope_exit([&] {
  1342. svr.stop();
  1343. thread.join();
  1344. ASSERT_FALSE(svr.is_running());
  1345. });
  1346. svr.wait_until_ready();
  1347. ASSERT_TRUE(svr.is_running());
  1348. pthread_kill(thread.native_handle(), SIGINT);
  1349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1350. ASSERT_TRUE(svr.is_running());
  1351. }
  1352. #endif
  1353. TEST(RedirectToDifferentPort, Redirect) {
  1354. Server svr1;
  1355. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1356. res.set_content("Hello World!", "text/plain");
  1357. });
  1358. int svr1_port = 0;
  1359. auto thread1 = std::thread([&]() {
  1360. svr1_port = svr1.bind_to_any_port("localhost");
  1361. svr1.listen_after_bind();
  1362. });
  1363. Server svr2;
  1364. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1365. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1366. });
  1367. int svr2_port = 0;
  1368. auto thread2 = std::thread([&]() {
  1369. svr2_port = svr2.bind_to_any_port("localhost");
  1370. svr2.listen_after_bind();
  1371. });
  1372. auto se = detail::scope_exit([&] {
  1373. svr2.stop();
  1374. thread2.join();
  1375. svr1.stop();
  1376. thread1.join();
  1377. ASSERT_FALSE(svr2.is_running());
  1378. ASSERT_FALSE(svr1.is_running());
  1379. });
  1380. svr1.wait_until_ready();
  1381. svr2.wait_until_ready();
  1382. Client cli("localhost", svr2_port);
  1383. cli.set_follow_location(true);
  1384. auto res = cli.Get("/2");
  1385. ASSERT_TRUE(res);
  1386. EXPECT_EQ(StatusCode::OK_200, res->status);
  1387. EXPECT_EQ("Hello World!", res->body);
  1388. }
  1389. TEST(RedirectFromPageWithContent, Redirect) {
  1390. Server svr;
  1391. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1392. res.set_content("___", "text/plain");
  1393. res.set_redirect("/2");
  1394. });
  1395. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1396. res.set_content("Hello World!", "text/plain");
  1397. });
  1398. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1399. auto se = detail::scope_exit([&] {
  1400. svr.stop();
  1401. th.join();
  1402. ASSERT_FALSE(svr.is_running());
  1403. });
  1404. svr.wait_until_ready();
  1405. {
  1406. Client cli("localhost", PORT);
  1407. cli.set_follow_location(true);
  1408. std::string body;
  1409. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1410. body.append(data, data_length);
  1411. return true;
  1412. });
  1413. ASSERT_TRUE(res);
  1414. EXPECT_EQ(StatusCode::OK_200, res->status);
  1415. EXPECT_EQ("Hello World!", body);
  1416. }
  1417. {
  1418. Client cli("localhost", PORT);
  1419. std::string body;
  1420. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1421. body.append(data, data_length);
  1422. return true;
  1423. });
  1424. ASSERT_TRUE(res);
  1425. EXPECT_EQ(StatusCode::Found_302, res->status);
  1426. EXPECT_EQ("___", body);
  1427. }
  1428. }
  1429. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1430. Server svr;
  1431. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1432. res.set_content("___", "text/plain");
  1433. // res.set_redirect("/2");
  1434. res.set_redirect("http://[::1]:1234/2");
  1435. });
  1436. svr.Get("/2", [&](const Request &req, Response &res) {
  1437. auto host_header = req.headers.find("Host");
  1438. ASSERT_TRUE(host_header != req.headers.end());
  1439. EXPECT_EQ("[::1]:1234", host_header->second);
  1440. res.set_content("Hello World!", "text/plain");
  1441. });
  1442. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1443. auto se = detail::scope_exit([&] {
  1444. svr.stop();
  1445. th.join();
  1446. ASSERT_FALSE(svr.is_running());
  1447. });
  1448. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1449. // actually starts anything, so the condition !svr.is_running() will
  1450. // always remain true, and the loop never stops.
  1451. // This basically counts how many milliseconds have passed since the
  1452. // call to svr.listen(), and if after 5 seconds nothing started yet
  1453. // aborts the test.
  1454. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1455. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1456. ASSERT_LT(milliseconds, 5000U);
  1457. }
  1458. {
  1459. Client cli("http://[::1]:1234");
  1460. cli.set_follow_location(true);
  1461. std::string body;
  1462. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1463. body.append(data, data_length);
  1464. return true;
  1465. });
  1466. ASSERT_TRUE(res);
  1467. EXPECT_EQ(StatusCode::OK_200, res->status);
  1468. EXPECT_EQ("Hello World!", body);
  1469. }
  1470. {
  1471. Client cli("http://[::1]:1234");
  1472. std::string body;
  1473. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1474. body.append(data, data_length);
  1475. return true;
  1476. });
  1477. ASSERT_TRUE(res);
  1478. EXPECT_EQ(StatusCode::Found_302, res->status);
  1479. EXPECT_EQ("___", body);
  1480. }
  1481. }
  1482. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1483. Server svr;
  1484. svr.Get("/foo", [](const Request &req, Response &res) {
  1485. auto a = req.params.find("a");
  1486. if (a != req.params.end()) {
  1487. res.set_content((*a).second, "text/plain");
  1488. res.status = StatusCode::OK_200;
  1489. } else {
  1490. res.status = StatusCode::BadRequest_400;
  1491. }
  1492. });
  1493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1494. auto se = detail::scope_exit([&] {
  1495. svr.stop();
  1496. thread.join();
  1497. ASSERT_FALSE(svr.is_running());
  1498. });
  1499. svr.wait_until_ready();
  1500. {
  1501. Client cli(HOST, PORT);
  1502. cli.set_url_encode(false);
  1503. auto res = cli.Get("/foo?a=explicitly+encoded");
  1504. ASSERT_TRUE(res);
  1505. EXPECT_EQ(StatusCode::OK_200, res->status);
  1506. // This expects it back with a space, as the `+` won't have been
  1507. // url-encoded, and server-side the params get decoded turning `+`
  1508. // into spaces.
  1509. EXPECT_EQ("explicitly encoded", res->body);
  1510. }
  1511. }
  1512. TEST(BindServerTest, DISABLED_BindDualStack) {
  1513. Server svr;
  1514. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1515. res.set_content("Hello World!", "text/plain");
  1516. });
  1517. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  1518. auto se = detail::scope_exit([&] {
  1519. svr.stop();
  1520. thread.join();
  1521. ASSERT_FALSE(svr.is_running());
  1522. });
  1523. svr.wait_until_ready();
  1524. {
  1525. Client cli("127.0.0.1", PORT);
  1526. auto res = cli.Get("/1");
  1527. ASSERT_TRUE(res);
  1528. EXPECT_EQ(StatusCode::OK_200, res->status);
  1529. EXPECT_EQ("Hello World!", res->body);
  1530. }
  1531. {
  1532. Client cli("::1", PORT);
  1533. auto res = cli.Get("/1");
  1534. ASSERT_TRUE(res);
  1535. EXPECT_EQ(StatusCode::OK_200, res->status);
  1536. EXPECT_EQ("Hello World!", res->body);
  1537. }
  1538. }
  1539. TEST(BindServerTest, BindAndListenSeparately) {
  1540. Server svr;
  1541. int port = svr.bind_to_any_port("0.0.0.0");
  1542. ASSERT_TRUE(svr.is_valid());
  1543. ASSERT_TRUE(port > 0);
  1544. svr.stop();
  1545. }
  1546. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1547. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  1548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  1549. CLIENT_CA_CERT_DIR);
  1550. int port = svr.bind_to_any_port("0.0.0.0");
  1551. ASSERT_TRUE(svr.is_valid());
  1552. ASSERT_TRUE(port > 0);
  1553. svr.stop();
  1554. }
  1555. #endif
  1556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1557. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  1558. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  1559. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  1560. int port = svr.bind_to_any_port("0.0.0.0");
  1561. ASSERT_TRUE(svr.is_valid());
  1562. ASSERT_TRUE(port > 0);
  1563. svr.stop();
  1564. }
  1565. #endif
  1566. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1567. X509 *readCertificate(const std::string &strFileName) {
  1568. std::ifstream inStream(strFileName);
  1569. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  1570. std::istreambuf_iterator<char>());
  1571. if (strCertPEM.empty()) return (nullptr);
  1572. BIO *pbCert = BIO_new(BIO_s_mem());
  1573. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  1574. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  1575. BIO_free(pbCert);
  1576. return (pCert);
  1577. }
  1578. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  1579. std::ifstream inStream(strFileName);
  1580. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  1581. std::istreambuf_iterator<char>());
  1582. if (strPrivateKeyPEM.empty()) return (nullptr);
  1583. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  1584. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  1585. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  1586. BIO_free(pbPrivKey);
  1587. return (pPrivateKey);
  1588. }
  1589. TEST(BindServerTest, UpdateCerts) {
  1590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  1591. int port = svr.bind_to_any_port("0.0.0.0");
  1592. ASSERT_TRUE(svr.is_valid());
  1593. ASSERT_TRUE(port > 0);
  1594. X509 *cert = readCertificate(SERVER_CERT_FILE);
  1595. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  1596. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  1597. ASSERT_TRUE(cert != nullptr);
  1598. ASSERT_TRUE(ca_cert != nullptr);
  1599. ASSERT_TRUE(key != nullptr);
  1600. X509_STORE *cert_store = X509_STORE_new();
  1601. X509_STORE_add_cert(cert_store, ca_cert);
  1602. svr.update_certs(cert, key, cert_store);
  1603. ASSERT_TRUE(svr.is_valid());
  1604. svr.stop();
  1605. X509_free(cert);
  1606. X509_free(ca_cert);
  1607. EVP_PKEY_free(key);
  1608. }
  1609. #endif
  1610. TEST(ErrorHandlerTest, ContentLength) {
  1611. Server svr;
  1612. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1613. res.status = StatusCode::OK_200;
  1614. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1615. "text/html"); // <= Content-Length still 13
  1616. });
  1617. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1618. res.set_content("Hello World!\n", "text/plain");
  1619. res.status = 524;
  1620. });
  1621. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1622. auto se = detail::scope_exit([&] {
  1623. svr.stop();
  1624. thread.join();
  1625. ASSERT_FALSE(svr.is_running());
  1626. });
  1627. svr.wait_until_ready();
  1628. {
  1629. Client cli(HOST, PORT);
  1630. auto res = cli.Get("/hi");
  1631. ASSERT_TRUE(res);
  1632. EXPECT_EQ(StatusCode::OK_200, res->status);
  1633. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1634. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1635. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1636. }
  1637. }
  1638. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  1639. TEST(ExceptionHandlerTest, ContentLength) {
  1640. Server svr;
  1641. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  1642. std::exception_ptr ep) {
  1643. EXPECT_FALSE(ep == nullptr);
  1644. try {
  1645. std::rethrow_exception(ep);
  1646. } catch (std::exception &e) { EXPECT_EQ("abc", std::string(e.what())); }
  1647. res.status = StatusCode::InternalServerError_500;
  1648. res.set_content("abcdefghijklmnopqrstuvwxyz",
  1649. "text/html"); // <= Content-Length still 13 at this point
  1650. });
  1651. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1652. res.set_content("Hello World!\n", "text/plain");
  1653. throw std::runtime_error("abc");
  1654. });
  1655. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1656. auto se = detail::scope_exit([&] {
  1657. svr.stop();
  1658. thread.join();
  1659. ASSERT_FALSE(svr.is_running());
  1660. });
  1661. svr.wait_until_ready();
  1662. for (size_t i = 0; i < 10; i++) {
  1663. Client cli(HOST, PORT);
  1664. for (size_t j = 0; j < 100; j++) {
  1665. auto res = cli.Get("/hi");
  1666. ASSERT_TRUE(res);
  1667. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1668. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1669. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1670. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1671. }
  1672. cli.set_keep_alive(true);
  1673. for (size_t j = 0; j < 100; j++) {
  1674. auto res = cli.Get("/hi");
  1675. ASSERT_TRUE(res);
  1676. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  1677. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  1678. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  1679. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  1680. }
  1681. }
  1682. }
  1683. #endif
  1684. TEST(NoContentTest, ContentLength) {
  1685. Server svr;
  1686. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1687. res.status = StatusCode::NoContent_204;
  1688. });
  1689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1690. auto se = detail::scope_exit([&] {
  1691. svr.stop();
  1692. thread.join();
  1693. ASSERT_FALSE(svr.is_running());
  1694. });
  1695. svr.wait_until_ready();
  1696. {
  1697. Client cli(HOST, PORT);
  1698. auto res = cli.Get("/hi");
  1699. ASSERT_TRUE(res);
  1700. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  1701. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  1702. }
  1703. }
  1704. TEST(RoutingHandlerTest, PreRoutingHandler) {
  1705. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  1707. ASSERT_TRUE(svr.is_valid());
  1708. #else
  1709. Server svr;
  1710. #endif
  1711. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  1712. if (req.path == "/routing_handler") {
  1713. res.set_header("PRE_ROUTING", "on");
  1714. res.set_content("Routing Handler", "text/plain");
  1715. return httplib::Server::HandlerResponse::Handled;
  1716. }
  1717. return httplib::Server::HandlerResponse::Unhandled;
  1718. });
  1719. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  1720. res.set_content("Error", "text/html");
  1721. });
  1722. svr.set_post_routing_handler([](const Request &req, Response &res) {
  1723. if (req.path == "/routing_handler") {
  1724. res.set_header("POST_ROUTING", "on");
  1725. }
  1726. });
  1727. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1728. res.set_content("Hello World!\n", "text/plain");
  1729. });
  1730. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1731. auto se = detail::scope_exit([&] {
  1732. svr.stop();
  1733. thread.join();
  1734. ASSERT_FALSE(svr.is_running());
  1735. });
  1736. svr.wait_until_ready();
  1737. {
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(HOST, PORT);
  1740. cli.enable_server_certificate_verification(false);
  1741. #else
  1742. Client cli(HOST, PORT);
  1743. #endif
  1744. auto res = cli.Get("/routing_handler");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. EXPECT_EQ("Routing Handler", res->body);
  1748. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  1749. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  1750. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  1751. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  1752. }
  1753. {
  1754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1755. SSLClient cli(HOST, PORT);
  1756. cli.enable_server_certificate_verification(false);
  1757. #else
  1758. Client cli(HOST, PORT);
  1759. #endif
  1760. auto res = cli.Get("/hi");
  1761. ASSERT_TRUE(res);
  1762. EXPECT_EQ(StatusCode::OK_200, res->status);
  1763. EXPECT_EQ("Hello World!\n", res->body);
  1764. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1765. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1766. }
  1767. {
  1768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1769. SSLClient cli(HOST, PORT);
  1770. cli.enable_server_certificate_verification(false);
  1771. #else
  1772. Client cli(HOST, PORT);
  1773. #endif
  1774. auto res = cli.Get("/aaa");
  1775. ASSERT_TRUE(res);
  1776. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1777. EXPECT_EQ("Error", res->body);
  1778. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  1779. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  1780. }
  1781. }
  1782. TEST(InvalidFormatTest, StatusCode) {
  1783. Server svr;
  1784. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  1785. res.set_content("Hello World!\n", "text/plain");
  1786. res.status = 9999; // Status should be a three-digit code...
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. {
  1796. Client cli(HOST, PORT);
  1797. auto res = cli.Get("/hi");
  1798. ASSERT_FALSE(res);
  1799. }
  1800. }
  1801. TEST(URLFragmentTest, WithFragment) {
  1802. Server svr;
  1803. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  1804. EXPECT_TRUE(req.target == "/hi");
  1805. });
  1806. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1807. auto se = detail::scope_exit([&] {
  1808. svr.stop();
  1809. thread.join();
  1810. ASSERT_FALSE(svr.is_running());
  1811. });
  1812. svr.wait_until_ready();
  1813. {
  1814. Client cli(HOST, PORT);
  1815. auto res = cli.Get("/hi#key1=val1=key2=val2");
  1816. EXPECT_TRUE(res);
  1817. EXPECT_EQ(StatusCode::OK_200, res->status);
  1818. res = cli.Get("/hi%23key1=val1=key2=val2");
  1819. EXPECT_TRUE(res);
  1820. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  1821. }
  1822. }
  1823. TEST(HeaderWriter, SetHeaderWriter) {
  1824. Server svr;
  1825. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  1826. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  1827. return detail::write_headers(strm, hdrs);
  1828. });
  1829. svr.Get("/hi", [](const Request &req, Response &res) {
  1830. auto it = req.headers.find("CustomClientHeader");
  1831. EXPECT_TRUE(it != req.headers.end());
  1832. EXPECT_EQ(it->second, "CustomClientValue");
  1833. res.set_content("Hello World!\n", "text/plain");
  1834. });
  1835. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. thread.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. {
  1843. Client cli(HOST, PORT);
  1844. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  1845. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  1846. return detail::write_headers(strm, hdrs);
  1847. });
  1848. auto res = cli.Get("/hi");
  1849. EXPECT_TRUE(res);
  1850. EXPECT_EQ(StatusCode::OK_200, res->status);
  1851. auto it = res->headers.find("CustomServerHeader");
  1852. EXPECT_TRUE(it != res->headers.end());
  1853. EXPECT_EQ(it->second, "CustomServerValue");
  1854. }
  1855. }
  1856. class ServerTest : public ::testing::Test {
  1857. protected:
  1858. ServerTest()
  1859. : cli_(HOST, PORT)
  1860. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1861. ,
  1862. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1863. #endif
  1864. {
  1865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1866. cli_.enable_server_certificate_verification(false);
  1867. #endif
  1868. }
  1869. virtual void SetUp() {
  1870. svr_.set_mount_point("/", "./www");
  1871. svr_.set_mount_point("/mount", "./www2");
  1872. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  1873. svr_.Get("/hi",
  1874. [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("Hello World!", "text/plain");
  1876. })
  1877. .Get("/http_response_splitting",
  1878. [&](const Request & /*req*/, Response &res) {
  1879. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1880. EXPECT_EQ(0U, res.headers.size());
  1881. EXPECT_FALSE(res.has_header("a"));
  1882. res.set_header("a", "1\nSet-Cookie: a=1");
  1883. EXPECT_EQ(0U, res.headers.size());
  1884. EXPECT_FALSE(res.has_header("a"));
  1885. res.set_header("a", "1\rSet-Cookie: a=1");
  1886. EXPECT_EQ(0U, res.headers.size());
  1887. EXPECT_FALSE(res.has_header("a"));
  1888. res.set_header("a\r\nb", "0");
  1889. EXPECT_EQ(0U, res.headers.size());
  1890. EXPECT_FALSE(res.has_header("a"));
  1891. res.set_header("a\rb", "0");
  1892. EXPECT_EQ(0U, res.headers.size());
  1893. EXPECT_FALSE(res.has_header("a"));
  1894. res.set_header("a\nb", "0");
  1895. EXPECT_EQ(0U, res.headers.size());
  1896. EXPECT_FALSE(res.has_header("a"));
  1897. res.set_redirect("1\r\nSet-Cookie: a=1");
  1898. EXPECT_EQ(0U, res.headers.size());
  1899. EXPECT_FALSE(res.has_header("Location"));
  1900. })
  1901. .Get("/slow",
  1902. [&](const Request & /*req*/, Response &res) {
  1903. std::this_thread::sleep_for(std::chrono::seconds(2));
  1904. res.set_content("slow", "text/plain");
  1905. })
  1906. #if 0
  1907. .Post("/slowpost",
  1908. [&](const Request & /*req*/, Response &res) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(2));
  1910. res.set_content("slow", "text/plain");
  1911. })
  1912. #endif
  1913. .Get("/remote_addr",
  1914. [&](const Request &req, Response &res) {
  1915. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1916. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1917. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1918. EXPECT_EQ(req.remote_port,
  1919. std::stoi(req.get_header_value("REMOTE_PORT")));
  1920. res.set_content(remote_addr.c_str(), "text/plain");
  1921. })
  1922. .Get("/local_addr",
  1923. [&](const Request &req, Response &res) {
  1924. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1925. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1926. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1927. auto local_port = req.get_header_value("LOCAL_PORT");
  1928. EXPECT_EQ(req.local_addr, local_addr);
  1929. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1930. res.set_content(local_addr.append(":").append(local_port),
  1931. "text/plain");
  1932. })
  1933. .Get("/endwith%",
  1934. [&](const Request & /*req*/, Response &res) {
  1935. res.set_content("Hello World!", "text/plain");
  1936. })
  1937. .Get("/a\\+\\+b",
  1938. [&](const Request &req, Response &res) {
  1939. ASSERT_TRUE(req.has_param("a +b"));
  1940. auto val = req.get_param_value("a +b");
  1941. res.set_content(val, "text/plain");
  1942. })
  1943. .Get("/", [&](const Request & /*req*/,
  1944. Response &res) { res.set_redirect("/hi"); })
  1945. .Post("/1",
  1946. [](const Request & /*req*/, Response &res) {
  1947. res.set_redirect("/2", StatusCode::SeeOther_303);
  1948. })
  1949. .Get("/2",
  1950. [](const Request & /*req*/, Response &res) {
  1951. res.set_content("redirected.", "text/plain");
  1952. res.status = StatusCode::OK_200;
  1953. })
  1954. .Post("/person",
  1955. [&](const Request &req, Response &res) {
  1956. if (req.has_param("name") && req.has_param("note")) {
  1957. persons_[req.get_param_value("name")] =
  1958. req.get_param_value("note");
  1959. } else {
  1960. res.status = StatusCode::BadRequest_400;
  1961. }
  1962. })
  1963. .Put("/person",
  1964. [&](const Request &req, Response &res) {
  1965. if (req.has_param("name") && req.has_param("note")) {
  1966. persons_[req.get_param_value("name")] =
  1967. req.get_param_value("note");
  1968. } else {
  1969. res.status = StatusCode::BadRequest_400;
  1970. }
  1971. })
  1972. .Get("/person/(.*)",
  1973. [&](const Request &req, Response &res) {
  1974. string name = req.matches[1];
  1975. if (persons_.find(name) != persons_.end()) {
  1976. auto note = persons_[name];
  1977. res.set_content(note, "text/plain");
  1978. } else {
  1979. res.status = StatusCode::NotFound_404;
  1980. }
  1981. })
  1982. .Post("/x-www-form-urlencoded-json",
  1983. [&](const Request &req, Response &res) {
  1984. auto json = req.get_param_value("json");
  1985. ASSERT_EQ(JSON_DATA, json);
  1986. res.set_content(json, "appliation/json");
  1987. res.status = StatusCode::OK_200;
  1988. })
  1989. .Get("/streamed-chunked",
  1990. [&](const Request & /*req*/, Response &res) {
  1991. res.set_chunked_content_provider(
  1992. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  1993. sink.os << "123";
  1994. sink.os << "456";
  1995. sink.os << "789";
  1996. sink.done();
  1997. return true;
  1998. });
  1999. })
  2000. .Get("/streamed-chunked2",
  2001. [&](const Request & /*req*/, Response &res) {
  2002. auto i = new int(0);
  2003. res.set_chunked_content_provider(
  2004. "text/plain",
  2005. [i](size_t /*offset*/, DataSink &sink) {
  2006. switch (*i) {
  2007. case 0: sink.os << "123"; break;
  2008. case 1: sink.os << "456"; break;
  2009. case 2: sink.os << "789"; break;
  2010. case 3: sink.done(); break;
  2011. }
  2012. (*i)++;
  2013. return true;
  2014. },
  2015. [i](bool success) {
  2016. EXPECT_TRUE(success);
  2017. delete i;
  2018. });
  2019. })
  2020. .Get("/streamed-chunked-with-trailer",
  2021. [&](const Request & /*req*/, Response &res) {
  2022. auto i = new int(0);
  2023. res.set_header("Trailer", "Dummy1, Dummy2");
  2024. res.set_chunked_content_provider(
  2025. "text/plain",
  2026. [i](size_t /*offset*/, DataSink &sink) {
  2027. switch (*i) {
  2028. case 0: sink.os << "123"; break;
  2029. case 1: sink.os << "456"; break;
  2030. case 2: sink.os << "789"; break;
  2031. case 3: {
  2032. sink.done_with_trailer(
  2033. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2034. } break;
  2035. }
  2036. (*i)++;
  2037. return true;
  2038. },
  2039. [i](bool success) {
  2040. EXPECT_TRUE(success);
  2041. delete i;
  2042. });
  2043. })
  2044. .Get("/streamed",
  2045. [&](const Request & /*req*/, Response &res) {
  2046. res.set_content_provider(
  2047. 6, "text/plain",
  2048. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2049. sink.os << (offset < 3 ? "a" : "b");
  2050. return true;
  2051. });
  2052. })
  2053. .Get("/streamed-with-range",
  2054. [&](const Request &req, Response &res) {
  2055. auto data = new std::string("abcdefg");
  2056. res.set_content_provider(
  2057. data->size(), "text/plain",
  2058. [data](size_t offset, size_t length, DataSink &sink) {
  2059. size_t DATA_CHUNK_SIZE = 4;
  2060. const auto &d = *data;
  2061. auto out_len =
  2062. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2063. auto ret =
  2064. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2065. EXPECT_TRUE(ret);
  2066. return true;
  2067. },
  2068. [data, &req](bool success) {
  2069. EXPECT_EQ(success, !req.has_param("error"));
  2070. delete data;
  2071. });
  2072. })
  2073. .Get("/streamed-cancel",
  2074. [&](const Request & /*req*/, Response &res) {
  2075. res.set_content_provider(
  2076. size_t(-1), "text/plain",
  2077. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2078. sink.os << "data_chunk";
  2079. return true;
  2080. });
  2081. })
  2082. .Get("/regex-with-delimiter",
  2083. [&](const Request &req, Response & /*res*/) {
  2084. ASSERT_TRUE(req.has_param("key"));
  2085. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2086. })
  2087. .Get("/with-range",
  2088. [&](const Request & /*req*/, Response &res) {
  2089. res.set_content("abcdefg", "text/plain");
  2090. })
  2091. .Get("/with-range-customized-response",
  2092. [&](const Request & /*req*/, Response &res) {
  2093. res.status = StatusCode::BadRequest_400;
  2094. res.set_content(JSON_DATA, "application/json");
  2095. })
  2096. .Post("/chunked",
  2097. [&](const Request &req, Response & /*res*/) {
  2098. EXPECT_EQ(req.body, "dechunked post body");
  2099. })
  2100. .Post("/large-chunked",
  2101. [&](const Request &req, Response & /*res*/) {
  2102. std::string expected(6 * 30 * 1024u, 'a');
  2103. EXPECT_EQ(req.body, expected);
  2104. })
  2105. .Post("/multipart",
  2106. [&](const Request &req, Response & /*res*/) {
  2107. EXPECT_EQ(6u, req.files.size());
  2108. ASSERT_TRUE(!req.has_file("???"));
  2109. ASSERT_TRUE(req.body.empty());
  2110. {
  2111. const auto &file = req.get_file_value("text1");
  2112. EXPECT_TRUE(file.filename.empty());
  2113. EXPECT_EQ("text default", file.content);
  2114. }
  2115. {
  2116. const auto &file = req.get_file_value("text2");
  2117. EXPECT_TRUE(file.filename.empty());
  2118. EXPECT_EQ("aωb", file.content);
  2119. }
  2120. {
  2121. const auto &file = req.get_file_value("file1");
  2122. EXPECT_EQ("hello.txt", file.filename);
  2123. EXPECT_EQ("text/plain", file.content_type);
  2124. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2125. }
  2126. {
  2127. const auto &file = req.get_file_value("file3");
  2128. EXPECT_TRUE(file.filename.empty());
  2129. EXPECT_EQ("application/octet-stream", file.content_type);
  2130. EXPECT_EQ(0u, file.content.size());
  2131. }
  2132. {
  2133. const auto &file = req.get_file_value("file4");
  2134. EXPECT_TRUE(file.filename.empty());
  2135. EXPECT_EQ(0u, file.content.size());
  2136. EXPECT_EQ("application/json tmp-string", file.content_type);
  2137. }
  2138. })
  2139. .Post("/multipart/multi_file_values",
  2140. [&](const Request &req, Response & /*res*/) {
  2141. EXPECT_EQ(5u, req.files.size());
  2142. ASSERT_TRUE(!req.has_file("???"));
  2143. ASSERT_TRUE(req.body.empty());
  2144. {
  2145. const auto &text_value = req.get_file_values("text");
  2146. EXPECT_EQ(1u, text_value.size());
  2147. auto &text = text_value[0];
  2148. EXPECT_TRUE(text.filename.empty());
  2149. EXPECT_EQ("default text", text.content);
  2150. }
  2151. {
  2152. const auto &text1_values = req.get_file_values("multi_text1");
  2153. EXPECT_EQ(2u, text1_values.size());
  2154. EXPECT_EQ("aaaaa", text1_values[0].content);
  2155. EXPECT_EQ("bbbbb", text1_values[1].content);
  2156. }
  2157. {
  2158. const auto &file1_values = req.get_file_values("multi_file1");
  2159. EXPECT_EQ(2u, file1_values.size());
  2160. auto file1 = file1_values[0];
  2161. EXPECT_EQ(file1.filename, "hello.txt");
  2162. EXPECT_EQ(file1.content_type, "text/plain");
  2163. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2164. auto file2 = file1_values[1];
  2165. EXPECT_EQ(file2.filename, "world.json");
  2166. EXPECT_EQ(file2.content_type, "application/json");
  2167. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2168. }
  2169. })
  2170. .Post("/empty",
  2171. [&](const Request &req, Response &res) {
  2172. EXPECT_EQ(req.body, "");
  2173. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2174. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2175. res.set_content("empty", "text/plain");
  2176. })
  2177. .Post("/empty-no-content-type",
  2178. [&](const Request &req, Response &res) {
  2179. EXPECT_EQ(req.body, "");
  2180. EXPECT_FALSE(req.has_header("Content-Type"));
  2181. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2182. res.set_content("empty-no-content-type", "text/plain");
  2183. })
  2184. .Post("/path-only",
  2185. [&](const Request &req, Response &res) {
  2186. EXPECT_EQ(req.body, "");
  2187. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2188. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2189. res.set_content("path-only", "text/plain");
  2190. })
  2191. .Post("/path-headers-only",
  2192. [&](const Request &req, Response &res) {
  2193. EXPECT_EQ(req.body, "");
  2194. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2195. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2196. EXPECT_EQ("world", req.get_header_value("hello"));
  2197. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2198. res.set_content("path-headers-only", "text/plain");
  2199. })
  2200. .Post("/post-large",
  2201. [&](const Request &req, Response &res) {
  2202. EXPECT_EQ(req.body, LARGE_DATA);
  2203. res.set_content(req.body, "text/plain");
  2204. })
  2205. .Put("/empty-no-content-type",
  2206. [&](const Request &req, Response &res) {
  2207. EXPECT_EQ(req.body, "");
  2208. EXPECT_FALSE(req.has_header("Content-Type"));
  2209. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2210. res.set_content("empty-no-content-type", "text/plain");
  2211. })
  2212. .Put("/put",
  2213. [&](const Request &req, Response &res) {
  2214. EXPECT_EQ(req.body, "PUT");
  2215. res.set_content(req.body, "text/plain");
  2216. })
  2217. .Put("/put-large",
  2218. [&](const Request &req, Response &res) {
  2219. EXPECT_EQ(req.body, LARGE_DATA);
  2220. res.set_content(req.body, "text/plain");
  2221. })
  2222. .Patch("/patch",
  2223. [&](const Request &req, Response &res) {
  2224. EXPECT_EQ(req.body, "PATCH");
  2225. res.set_content(req.body, "text/plain");
  2226. })
  2227. .Delete("/delete",
  2228. [&](const Request & /*req*/, Response &res) {
  2229. res.set_content("DELETE", "text/plain");
  2230. })
  2231. .Delete("/delete-body",
  2232. [&](const Request &req, Response &res) {
  2233. EXPECT_EQ(req.body, "content");
  2234. res.set_content(req.body, "text/plain");
  2235. })
  2236. .Options(R"(\*)",
  2237. [&](const Request & /*req*/, Response &res) {
  2238. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2239. })
  2240. .Get("/request-target",
  2241. [&](const Request &req, Response & /*res*/) {
  2242. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2243. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2244. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2245. })
  2246. .Get("/long-query-value",
  2247. [&](const Request &req, Response & /*res*/) {
  2248. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2249. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2250. })
  2251. .Get("/array-param",
  2252. [&](const Request &req, Response & /*res*/) {
  2253. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2254. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2255. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2256. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2257. })
  2258. .Post("/validate-no-multiple-headers",
  2259. [&](const Request &req, Response & /*res*/) {
  2260. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2261. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2262. })
  2263. .Post("/content_receiver",
  2264. [&](const Request &req, Response &res,
  2265. const ContentReader &content_reader) {
  2266. if (req.is_multipart_form_data()) {
  2267. MultipartFormDataItems files;
  2268. content_reader(
  2269. [&](const MultipartFormData &file) {
  2270. files.push_back(file);
  2271. return true;
  2272. },
  2273. [&](const char *data, size_t data_length) {
  2274. files.back().content.append(data, data_length);
  2275. return true;
  2276. });
  2277. EXPECT_EQ(5u, files.size());
  2278. {
  2279. const auto &file = get_file_value(files, "text1");
  2280. EXPECT_TRUE(file.filename.empty());
  2281. EXPECT_EQ("text default", file.content);
  2282. }
  2283. {
  2284. const auto &file = get_file_value(files, "text2");
  2285. EXPECT_TRUE(file.filename.empty());
  2286. EXPECT_EQ("aωb", file.content);
  2287. }
  2288. {
  2289. const auto &file = get_file_value(files, "file1");
  2290. EXPECT_EQ("hello.txt", file.filename);
  2291. EXPECT_EQ("text/plain", file.content_type);
  2292. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2293. }
  2294. {
  2295. const auto &file = get_file_value(files, "file3");
  2296. EXPECT_TRUE(file.filename.empty());
  2297. EXPECT_EQ("application/octet-stream", file.content_type);
  2298. EXPECT_EQ(0u, file.content.size());
  2299. }
  2300. } else {
  2301. std::string body;
  2302. content_reader([&](const char *data, size_t data_length) {
  2303. EXPECT_EQ(7U, data_length);
  2304. body.append(data, data_length);
  2305. return true;
  2306. });
  2307. EXPECT_EQ(body, "content");
  2308. res.set_content(body, "text/plain");
  2309. }
  2310. })
  2311. .Put("/content_receiver",
  2312. [&](const Request & /*req*/, Response &res,
  2313. const ContentReader &content_reader) {
  2314. std::string body;
  2315. content_reader([&](const char *data, size_t data_length) {
  2316. body.append(data, data_length);
  2317. return true;
  2318. });
  2319. EXPECT_EQ(body, "content");
  2320. res.set_content(body, "text/plain");
  2321. })
  2322. .Patch("/content_receiver",
  2323. [&](const Request & /*req*/, Response &res,
  2324. const ContentReader &content_reader) {
  2325. std::string body;
  2326. content_reader([&](const char *data, size_t data_length) {
  2327. body.append(data, data_length);
  2328. return true;
  2329. });
  2330. EXPECT_EQ(body, "content");
  2331. res.set_content(body, "text/plain");
  2332. })
  2333. .Post("/query-string-and-body",
  2334. [&](const Request &req, Response & /*res*/) {
  2335. ASSERT_TRUE(req.has_param("key"));
  2336. EXPECT_EQ(req.get_param_value("key"), "value");
  2337. EXPECT_EQ(req.body, "content");
  2338. })
  2339. .Get("/last-request",
  2340. [&](const Request &req, Response & /*res*/) {
  2341. EXPECT_EQ("close", req.get_header_value("Connection"));
  2342. })
  2343. .Get(R"(/redirect/(\d+))",
  2344. [&](const Request &req, Response &res) {
  2345. auto num = std::stoi(req.matches[1]) + 1;
  2346. std::string url = "/redirect/" + std::to_string(num);
  2347. res.set_redirect(url);
  2348. })
  2349. .Post("/binary",
  2350. [&](const Request &req, Response &res) {
  2351. EXPECT_EQ(4U, req.body.size());
  2352. EXPECT_EQ("application/octet-stream",
  2353. req.get_header_value("Content-Type"));
  2354. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2355. res.set_content(req.body, "application/octet-stream");
  2356. })
  2357. .Put("/binary",
  2358. [&](const Request &req, Response &res) {
  2359. EXPECT_EQ(4U, req.body.size());
  2360. EXPECT_EQ("application/octet-stream",
  2361. req.get_header_value("Content-Type"));
  2362. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2363. res.set_content(req.body, "application/octet-stream");
  2364. })
  2365. .Patch("/binary",
  2366. [&](const Request &req, Response &res) {
  2367. EXPECT_EQ(4U, req.body.size());
  2368. EXPECT_EQ("application/octet-stream",
  2369. req.get_header_value("Content-Type"));
  2370. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2371. res.set_content(req.body, "application/octet-stream");
  2372. })
  2373. .Delete("/binary",
  2374. [&](const Request &req, Response &res) {
  2375. EXPECT_EQ(4U, req.body.size());
  2376. EXPECT_EQ("application/octet-stream",
  2377. req.get_header_value("Content-Type"));
  2378. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2379. res.set_content(req.body, "application/octet-stream");
  2380. })
  2381. .Get("/issue1772",
  2382. [&](const Request & /*req*/, Response &res) {
  2383. res.status = 401;
  2384. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2385. })
  2386. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  2387. .Get("/compress",
  2388. [&](const Request & /*req*/, Response &res) {
  2389. res.set_content(
  2390. "12345678901234567890123456789012345678901234567890123456789"
  2391. "01234567890123456789012345678901234567890",
  2392. "text/plain");
  2393. })
  2394. .Get("/nocompress",
  2395. [&](const Request & /*req*/, Response &res) {
  2396. res.set_content(
  2397. "12345678901234567890123456789012345678901234567890123456789"
  2398. "01234567890123456789012345678901234567890",
  2399. "application/octet-stream");
  2400. })
  2401. .Post("/compress-multipart",
  2402. [&](const Request &req, Response & /*res*/) {
  2403. EXPECT_EQ(2u, req.files.size());
  2404. ASSERT_TRUE(!req.has_file("???"));
  2405. {
  2406. const auto &file = req.get_file_value("key1");
  2407. EXPECT_TRUE(file.filename.empty());
  2408. EXPECT_EQ("test", file.content);
  2409. }
  2410. {
  2411. const auto &file = req.get_file_value("key2");
  2412. EXPECT_TRUE(file.filename.empty());
  2413. EXPECT_EQ("--abcdefg123", file.content);
  2414. }
  2415. })
  2416. #endif
  2417. ;
  2418. persons_["john"] = "programmer";
  2419. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2420. svr_.wait_until_ready();
  2421. }
  2422. virtual void TearDown() {
  2423. svr_.stop();
  2424. if (!request_threads_.empty()) {
  2425. std::this_thread::sleep_for(std::chrono::seconds(1));
  2426. for (auto &t : request_threads_) {
  2427. t.join();
  2428. }
  2429. }
  2430. t_.join();
  2431. }
  2432. map<string, string> persons_;
  2433. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2434. SSLClient cli_;
  2435. SSLServer svr_;
  2436. #else
  2437. Client cli_;
  2438. Server svr_;
  2439. #endif
  2440. thread t_;
  2441. std::vector<thread> request_threads_;
  2442. };
  2443. TEST_F(ServerTest, GetMethod200) {
  2444. auto res = cli_.Get("/hi");
  2445. ASSERT_TRUE(res);
  2446. EXPECT_EQ("HTTP/1.1", res->version);
  2447. EXPECT_EQ(StatusCode::OK_200, res->status);
  2448. EXPECT_EQ("OK", res->reason);
  2449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2450. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2451. EXPECT_EQ("Hello World!", res->body);
  2452. }
  2453. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2454. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2455. ASSERT_TRUE(res);
  2456. EXPECT_EQ("HTTP/1.1", res->version);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2459. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2460. EXPECT_EQ("Hello World!", res->body);
  2461. }
  2462. TEST_F(ServerTest, GetMethod302) {
  2463. auto res = cli_.Get("/");
  2464. ASSERT_TRUE(res);
  2465. EXPECT_EQ(StatusCode::Found_302, res->status);
  2466. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2467. }
  2468. TEST_F(ServerTest, GetMethod302Redirect) {
  2469. cli_.set_follow_location(true);
  2470. auto res = cli_.Get("/");
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::OK_200, res->status);
  2473. EXPECT_EQ("Hello World!", res->body);
  2474. EXPECT_EQ("/hi", res->location);
  2475. }
  2476. TEST_F(ServerTest, GetMethod404) {
  2477. auto res = cli_.Get("/invalid");
  2478. ASSERT_TRUE(res);
  2479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2480. }
  2481. TEST_F(ServerTest, HeadMethod200) {
  2482. auto res = cli_.Head("/hi");
  2483. ASSERT_TRUE(res);
  2484. EXPECT_EQ(StatusCode::OK_200, res->status);
  2485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2486. EXPECT_TRUE(res->body.empty());
  2487. }
  2488. TEST_F(ServerTest, HeadMethod200Static) {
  2489. auto res = cli_.Head("/mount/dir/index.html");
  2490. ASSERT_TRUE(res);
  2491. EXPECT_EQ(StatusCode::OK_200, res->status);
  2492. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2493. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2494. EXPECT_TRUE(res->body.empty());
  2495. }
  2496. TEST_F(ServerTest, HeadMethod404) {
  2497. auto res = cli_.Head("/invalid");
  2498. ASSERT_TRUE(res);
  2499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2500. EXPECT_TRUE(res->body.empty());
  2501. }
  2502. TEST_F(ServerTest, GetMethodPersonJohn) {
  2503. auto res = cli_.Get("/person/john");
  2504. ASSERT_TRUE(res);
  2505. EXPECT_EQ(StatusCode::OK_200, res->status);
  2506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2507. EXPECT_EQ("programmer", res->body);
  2508. }
  2509. TEST_F(ServerTest, PostMethod1) {
  2510. auto res = cli_.Get("/person/john1");
  2511. ASSERT_TRUE(res);
  2512. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2513. res = cli_.Post("/person", "name=john1&note=coder",
  2514. "application/x-www-form-urlencoded");
  2515. ASSERT_TRUE(res);
  2516. ASSERT_EQ(StatusCode::OK_200, res->status);
  2517. res = cli_.Get("/person/john1");
  2518. ASSERT_TRUE(res);
  2519. ASSERT_EQ(StatusCode::OK_200, res->status);
  2520. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2521. ASSERT_EQ("coder", res->body);
  2522. }
  2523. TEST_F(ServerTest, PostMethod2) {
  2524. auto res = cli_.Get("/person/john2");
  2525. ASSERT_TRUE(res);
  2526. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2527. Params params;
  2528. params.emplace("name", "john2");
  2529. params.emplace("note", "coder");
  2530. res = cli_.Post("/person", params);
  2531. ASSERT_TRUE(res);
  2532. ASSERT_EQ(StatusCode::OK_200, res->status);
  2533. res = cli_.Get("/person/john2");
  2534. ASSERT_TRUE(res);
  2535. ASSERT_EQ(StatusCode::OK_200, res->status);
  2536. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2537. ASSERT_EQ("coder", res->body);
  2538. }
  2539. TEST_F(ServerTest, PutMethod3) {
  2540. auto res = cli_.Get("/person/john3");
  2541. ASSERT_TRUE(res);
  2542. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2543. Params params;
  2544. params.emplace("name", "john3");
  2545. params.emplace("note", "coder");
  2546. res = cli_.Put("/person", params);
  2547. ASSERT_TRUE(res);
  2548. ASSERT_EQ(StatusCode::OK_200, res->status);
  2549. res = cli_.Get("/person/john3");
  2550. ASSERT_TRUE(res);
  2551. ASSERT_EQ(StatusCode::OK_200, res->status);
  2552. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2553. ASSERT_EQ("coder", res->body);
  2554. }
  2555. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2556. Params params;
  2557. params.emplace("json", JSON_DATA);
  2558. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2559. ASSERT_TRUE(res);
  2560. ASSERT_EQ(StatusCode::OK_200, res->status);
  2561. ASSERT_EQ(JSON_DATA, res->body);
  2562. }
  2563. TEST_F(ServerTest, PostEmptyContent) {
  2564. auto res = cli_.Post("/empty", "", "text/plain");
  2565. ASSERT_TRUE(res);
  2566. ASSERT_EQ(StatusCode::OK_200, res->status);
  2567. ASSERT_EQ("empty", res->body);
  2568. }
  2569. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2570. auto res = cli_.Post("/empty-no-content-type");
  2571. ASSERT_TRUE(res);
  2572. ASSERT_EQ(StatusCode::OK_200, res->status);
  2573. ASSERT_EQ("empty-no-content-type", res->body);
  2574. }
  2575. TEST_F(ServerTest, PostPathOnly) {
  2576. auto res = cli_.Post("/path-only");
  2577. ASSERT_TRUE(res);
  2578. ASSERT_EQ(StatusCode::OK_200, res->status);
  2579. ASSERT_EQ("path-only", res->body);
  2580. }
  2581. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2582. auto res = cli_.Post("/path-headers-only",
  2583. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2584. ASSERT_TRUE(res);
  2585. ASSERT_EQ(StatusCode::OK_200, res->status);
  2586. ASSERT_EQ("path-headers-only", res->body);
  2587. }
  2588. TEST_F(ServerTest, PostLarge) {
  2589. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2590. ASSERT_TRUE(res);
  2591. ASSERT_EQ(StatusCode::OK_200, res->status);
  2592. EXPECT_EQ(LARGE_DATA, res->body);
  2593. }
  2594. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2595. auto res = cli_.Put("/empty-no-content-type");
  2596. ASSERT_TRUE(res);
  2597. ASSERT_EQ(StatusCode::OK_200, res->status);
  2598. ASSERT_EQ("empty-no-content-type", res->body);
  2599. }
  2600. TEST_F(ServerTest, GetMethodDir) {
  2601. auto res = cli_.Get("/dir/");
  2602. ASSERT_TRUE(res);
  2603. EXPECT_EQ(StatusCode::OK_200, res->status);
  2604. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2605. auto body = R"(<html>
  2606. <head>
  2607. </head>
  2608. <body>
  2609. <a href="/dir/test.html">Test</a>
  2610. <a href="/hi">hi</a>
  2611. </body>
  2612. </html>
  2613. )";
  2614. EXPECT_EQ(body, res->body);
  2615. }
  2616. TEST_F(ServerTest, GetMethodDirTest) {
  2617. auto res = cli_.Get("/dir/test.html");
  2618. ASSERT_TRUE(res);
  2619. EXPECT_EQ(StatusCode::OK_200, res->status);
  2620. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2621. EXPECT_EQ("test.html", res->body);
  2622. }
  2623. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2624. auto res = cli_.Get("/dir/../dir/test.html");
  2625. ASSERT_TRUE(res);
  2626. EXPECT_EQ(StatusCode::OK_200, res->status);
  2627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2628. EXPECT_EQ("test.html", res->body);
  2629. }
  2630. TEST_F(ServerTest, GetMethodInvalidPath) {
  2631. auto res = cli_.Get("/dir/../test.html");
  2632. ASSERT_TRUE(res);
  2633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2634. }
  2635. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2636. auto res = cli_.Get("/../www/dir/test.html");
  2637. ASSERT_TRUE(res);
  2638. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2639. }
  2640. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2641. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2642. ASSERT_TRUE(res);
  2643. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2644. }
  2645. TEST_F(ServerTest, GetMethodDirMountTest) {
  2646. auto res = cli_.Get("/mount/dir/test.html");
  2647. ASSERT_TRUE(res);
  2648. EXPECT_EQ(StatusCode::OK_200, res->status);
  2649. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2650. EXPECT_EQ("test.html", res->body);
  2651. }
  2652. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2653. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2654. ASSERT_TRUE(res);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2657. EXPECT_EQ("test.html", res->body);
  2658. }
  2659. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2660. auto res = cli_.Get("/mount/dir/../test.html");
  2661. ASSERT_TRUE(res);
  2662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2663. }
  2664. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2665. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2666. ASSERT_TRUE(res);
  2667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2668. }
  2669. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2670. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2671. ASSERT_TRUE(res);
  2672. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2673. }
  2674. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2675. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2676. ASSERT_TRUE(res);
  2677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2678. }
  2679. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2680. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2681. ASSERT_TRUE(res);
  2682. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2683. }
  2684. TEST_F(ServerTest, PostMethod303) {
  2685. auto res = cli_.Post("/1", "body", "text/plain");
  2686. ASSERT_TRUE(res);
  2687. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2688. EXPECT_EQ("/2", res->get_header_value("Location"));
  2689. }
  2690. TEST_F(ServerTest, PostMethod303Redirect) {
  2691. cli_.set_follow_location(true);
  2692. auto res = cli_.Post("/1", "body", "text/plain");
  2693. ASSERT_TRUE(res);
  2694. EXPECT_EQ(StatusCode::OK_200, res->status);
  2695. EXPECT_EQ("redirected.", res->body);
  2696. EXPECT_EQ("/2", res->location);
  2697. }
  2698. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2699. auto res = cli_.Get("/dir/test.abcde");
  2700. ASSERT_TRUE(res);
  2701. EXPECT_EQ(StatusCode::OK_200, res->status);
  2702. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2703. EXPECT_EQ("abcde", res->body);
  2704. }
  2705. TEST_F(ServerTest, StaticFileRange) {
  2706. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2707. ASSERT_TRUE(res);
  2708. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2709. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2710. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2711. EXPECT_EQ(true, res->has_header("Content-Range"));
  2712. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2713. EXPECT_EQ(std::string("cd"), res->body);
  2714. }
  2715. TEST_F(ServerTest, StaticFileRanges) {
  2716. auto res =
  2717. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2718. ASSERT_TRUE(res);
  2719. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2720. EXPECT_TRUE(
  2721. res->get_header_value("Content-Type")
  2722. .find(
  2723. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2724. 0);
  2725. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2726. }
  2727. TEST_F(ServerTest, StaticFileRangeHead) {
  2728. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2729. ASSERT_TRUE(res);
  2730. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2731. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2732. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2733. EXPECT_EQ(true, res->has_header("Content-Range"));
  2734. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2735. }
  2736. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2737. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2738. ASSERT_TRUE(res);
  2739. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2740. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2741. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2742. EXPECT_EQ(true, res->has_header("Content-Range"));
  2743. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2744. res->get_header_value("Content-Range"));
  2745. EXPECT_EQ("LAST\n", res->body);
  2746. }
  2747. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2748. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2749. ASSERT_TRUE(res);
  2750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2752. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2753. EXPECT_EQ(true, res->has_header("Content-Range"));
  2754. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2755. }
  2756. TEST_F(ServerTest, StaticFileBigFile) {
  2757. auto res = cli_.Get("/dir/1MB.txt");
  2758. ASSERT_TRUE(res);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2761. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2762. }
  2763. TEST_F(ServerTest, InvalidBaseDirMount) {
  2764. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2765. }
  2766. TEST_F(ServerTest, Binary) {
  2767. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2768. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2769. "application/octet-stream");
  2770. ASSERT_TRUE(res);
  2771. ASSERT_EQ(StatusCode::OK_200, res->status);
  2772. ASSERT_EQ(4U, res->body.size());
  2773. res = cli_.Put("/binary", binary.data(), binary.size(),
  2774. "application/octet-stream");
  2775. ASSERT_TRUE(res);
  2776. ASSERT_EQ(StatusCode::OK_200, res->status);
  2777. ASSERT_EQ(4U, res->body.size());
  2778. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2779. "application/octet-stream");
  2780. ASSERT_TRUE(res);
  2781. ASSERT_EQ(StatusCode::OK_200, res->status);
  2782. ASSERT_EQ(4U, res->body.size());
  2783. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2784. "application/octet-stream");
  2785. ASSERT_TRUE(res);
  2786. ASSERT_EQ(StatusCode::OK_200, res->status);
  2787. ASSERT_EQ(4U, res->body.size());
  2788. }
  2789. TEST_F(ServerTest, BinaryString) {
  2790. auto binary = std::string("\x00\x01\x02\x03", 4);
  2791. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2792. ASSERT_TRUE(res);
  2793. ASSERT_EQ(StatusCode::OK_200, res->status);
  2794. ASSERT_EQ(4U, res->body.size());
  2795. res = cli_.Put("/binary", binary, "application/octet-stream");
  2796. ASSERT_TRUE(res);
  2797. ASSERT_EQ(StatusCode::OK_200, res->status);
  2798. ASSERT_EQ(4U, res->body.size());
  2799. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2800. ASSERT_TRUE(res);
  2801. ASSERT_EQ(StatusCode::OK_200, res->status);
  2802. ASSERT_EQ(4U, res->body.size());
  2803. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2804. ASSERT_TRUE(res);
  2805. ASSERT_EQ(StatusCode::OK_200, res->status);
  2806. ASSERT_EQ(4U, res->body.size());
  2807. }
  2808. TEST_F(ServerTest, EmptyRequest) {
  2809. auto res = cli_.Get("");
  2810. ASSERT_TRUE(!res);
  2811. EXPECT_EQ(Error::Connection, res.error());
  2812. }
  2813. TEST_F(ServerTest, LongRequest) {
  2814. std::string request;
  2815. for (size_t i = 0; i < 545; i++) {
  2816. request += "/TooLongRequest";
  2817. }
  2818. request += "OK";
  2819. auto res = cli_.Get(request.c_str());
  2820. ASSERT_TRUE(res);
  2821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2822. }
  2823. TEST_F(ServerTest, TooLongRequest) {
  2824. std::string request;
  2825. for (size_t i = 0; i < 545; i++) {
  2826. request += "/TooLongRequest";
  2827. }
  2828. request += "_NG";
  2829. auto res = cli_.Get(request.c_str());
  2830. ASSERT_TRUE(res);
  2831. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2832. }
  2833. TEST_F(ServerTest, LongHeader) {
  2834. Request req;
  2835. req.method = "GET";
  2836. req.path = "/hi";
  2837. std::string host_and_port;
  2838. host_and_port += HOST;
  2839. host_and_port += ":";
  2840. host_and_port += std::to_string(PORT);
  2841. req.headers.emplace("Host", host_and_port.c_str());
  2842. req.headers.emplace("Accept", "*/*");
  2843. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2844. req.headers.emplace(
  2845. "Header-Name",
  2846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2858. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2859. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2861. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2862. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2863. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2864. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2865. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2866. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2867. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2868. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2869. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2870. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2871. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2872. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2873. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2874. "@@@@@@@@@@@@@@@@");
  2875. auto res = std::make_shared<Response>();
  2876. auto error = Error::Success;
  2877. auto ret = cli_.send(req, *res, error);
  2878. ASSERT_TRUE(ret);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. TEST_F(ServerTest, LongQueryValue) {
  2882. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2883. ASSERT_TRUE(res);
  2884. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2885. }
  2886. TEST_F(ServerTest, TooLongHeader) {
  2887. Request req;
  2888. req.method = "GET";
  2889. req.path = "/hi";
  2890. std::string host_and_port;
  2891. host_and_port += HOST;
  2892. host_and_port += ":";
  2893. host_and_port += std::to_string(PORT);
  2894. req.headers.emplace("Host", host_and_port.c_str());
  2895. req.headers.emplace("Accept", "*/*");
  2896. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2897. req.headers.emplace(
  2898. "Header-Name",
  2899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2925. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2926. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2927. "@@@@@@@@@@@@@@@@@");
  2928. auto res = std::make_shared<Response>();
  2929. auto error = Error::Success;
  2930. auto ret = cli_.send(req, *res, error);
  2931. ASSERT_TRUE(ret);
  2932. EXPECT_EQ(StatusCode::OK_200, res->status);
  2933. }
  2934. TEST_F(ServerTest, PercentEncoding) {
  2935. auto res = cli_.Get("/e%6edwith%");
  2936. ASSERT_TRUE(res);
  2937. EXPECT_EQ(StatusCode::OK_200, res->status);
  2938. }
  2939. TEST_F(ServerTest, PercentEncodingUnicode) {
  2940. auto res = cli_.Get("/e%u006edwith%");
  2941. ASSERT_TRUE(res);
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST_F(ServerTest, InvalidPercentEncoding) {
  2945. auto res = cli_.Get("/%endwith%");
  2946. ASSERT_TRUE(res);
  2947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2948. }
  2949. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2950. auto res = cli_.Get("/%uendwith%");
  2951. ASSERT_TRUE(res);
  2952. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2953. }
  2954. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2955. auto res = cli_.Get("/hello?aaa=bbb%");
  2956. ASSERT_TRUE(res);
  2957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2958. }
  2959. TEST_F(ServerTest, PlusSignEncoding) {
  2960. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2961. ASSERT_TRUE(res);
  2962. EXPECT_EQ(StatusCode::OK_200, res->status);
  2963. EXPECT_EQ("a +b", res->body);
  2964. }
  2965. TEST_F(ServerTest, MultipartFormData) {
  2966. MultipartFormDataItems items = {
  2967. {"text1", "text default", "", ""},
  2968. {"text2", "aωb", "", ""},
  2969. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2970. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2971. {"file3", "", "", "application/octet-stream"},
  2972. {"file4", "", "", " application/json tmp-string "}};
  2973. auto res = cli_.Post("/multipart", items);
  2974. ASSERT_TRUE(res);
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. }
  2977. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  2978. MultipartFormDataItems items = {
  2979. {"text", "default text", "", ""},
  2980. {"multi_text1", "aaaaa", "", ""},
  2981. {"multi_text1", "bbbbb", "", ""},
  2982. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2983. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  2984. "application/json"},
  2985. };
  2986. auto res = cli_.Post("/multipart/multi_file_values", items);
  2987. ASSERT_TRUE(res);
  2988. EXPECT_EQ(StatusCode::OK_200, res->status);
  2989. }
  2990. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  2991. auto res = cli_.Get("/hi");
  2992. ASSERT_TRUE(res);
  2993. EXPECT_EQ(StatusCode::OK_200, res->status);
  2994. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  2995. EXPECT_EQ("Hello World!", res->body);
  2996. }
  2997. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  2998. Request req;
  2999. req.method = "POST";
  3000. req.path = "/chunked";
  3001. std::string host_and_port;
  3002. host_and_port += HOST;
  3003. host_and_port += ":";
  3004. host_and_port += std::to_string(PORT);
  3005. req.headers.emplace("Host", host_and_port.c_str());
  3006. req.headers.emplace("Accept", "*/*");
  3007. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3008. req.headers.emplace("Content-Type", "text/plain");
  3009. req.headers.emplace("Content-Length", "0");
  3010. req.headers.emplace(
  3011. "Transfer-Encoding",
  3012. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3013. // Client does not chunk, so make a chunked body manually.
  3014. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3015. auto res = std::make_shared<Response>();
  3016. auto error = Error::Success;
  3017. auto ret = cli_.send(req, *res, error);
  3018. ASSERT_TRUE(ret);
  3019. EXPECT_EQ(StatusCode::OK_200, res->status);
  3020. }
  3021. TEST_F(ServerTest, GetStreamed2) {
  3022. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3023. ASSERT_TRUE(res);
  3024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3025. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3026. EXPECT_EQ(true, res->has_header("Content-Range"));
  3027. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3028. EXPECT_EQ(std::string("ab"), res->body);
  3029. }
  3030. TEST_F(ServerTest, GetStreamed) {
  3031. auto res = cli_.Get("/streamed");
  3032. ASSERT_TRUE(res);
  3033. EXPECT_EQ(StatusCode::OK_200, res->status);
  3034. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3035. EXPECT_EQ(std::string("aaabbb"), res->body);
  3036. }
  3037. TEST_F(ServerTest, GetStreamedWithRange1) {
  3038. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3039. ASSERT_TRUE(res);
  3040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3041. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3042. EXPECT_EQ(true, res->has_header("Content-Range"));
  3043. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3044. EXPECT_EQ(std::string("def"), res->body);
  3045. }
  3046. TEST_F(ServerTest, GetStreamedWithRange2) {
  3047. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3048. ASSERT_TRUE(res);
  3049. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3050. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3051. EXPECT_EQ(true, res->has_header("Content-Range"));
  3052. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3053. EXPECT_EQ(std::string("bcdefg"), res->body);
  3054. }
  3055. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3056. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3057. ASSERT_TRUE(res);
  3058. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3059. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3060. EXPECT_EQ(true, res->has_header("Content-Range"));
  3061. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3062. EXPECT_EQ(std::string("efg"), res->body);
  3063. }
  3064. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3065. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3066. ASSERT_TRUE(res);
  3067. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3068. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3069. EXPECT_EQ(false, res->has_header("Content-Range"));
  3070. EXPECT_EQ(0U, res->body.size());
  3071. }
  3072. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3073. auto res = cli_.Get("/streamed-with-range",
  3074. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3075. "92233720368547758079223372036854775807"}});
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3078. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3079. EXPECT_EQ(false, res->has_header("Content-Range"));
  3080. EXPECT_EQ(0U, res->body.size());
  3081. }
  3082. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3083. auto res = cli_.Get(
  3084. "/with-range",
  3085. {{"Range",
  3086. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())}});
  3087. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3088. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3089. EXPECT_EQ(false, res->has_header("Content-Range"));
  3090. EXPECT_EQ(0U, res->body.size());
  3091. }
  3092. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3093. auto res =
  3094. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3095. ASSERT_TRUE(res);
  3096. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3097. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3098. EXPECT_EQ(false, res->has_header("Content-Range"));
  3099. EXPECT_EQ(267U, res->body.size());
  3100. }
  3101. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3102. Ranges ranges;
  3103. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3104. ranges.emplace_back(0, -1);
  3105. }
  3106. auto res =
  3107. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3108. ASSERT_TRUE(res);
  3109. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3110. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3111. EXPECT_EQ(false, res->has_header("Content-Range"));
  3112. EXPECT_EQ(0U, res->body.size());
  3113. }
  3114. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3115. auto res = cli_.Get("/streamed-with-range?error",
  3116. {{make_range_header({{0, -1}, {0, -1}})}});
  3117. ASSERT_TRUE(res);
  3118. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3119. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3120. EXPECT_EQ(false, res->has_header("Content-Range"));
  3121. EXPECT_EQ(0U, res->body.size());
  3122. }
  3123. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3124. auto res = cli_.Get("/streamed-with-range?error",
  3125. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3126. ASSERT_TRUE(res);
  3127. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3128. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3129. EXPECT_EQ(false, res->has_header("Content-Range"));
  3130. EXPECT_EQ(0U, res->body.size());
  3131. }
  3132. TEST_F(ServerTest, GetStreamedEndless) {
  3133. uint64_t offset = 0;
  3134. auto res = cli_.Get("/streamed-cancel",
  3135. [&](const char * /*data*/, uint64_t data_length) {
  3136. if (offset < 100) {
  3137. offset += data_length;
  3138. return true;
  3139. }
  3140. return false;
  3141. });
  3142. ASSERT_TRUE(!res);
  3143. EXPECT_EQ(Error::Canceled, res.error());
  3144. }
  3145. TEST_F(ServerTest, ClientStop) {
  3146. std::atomic_size_t count{4};
  3147. std::vector<std::thread> threads;
  3148. for (auto i = count.load(); i != 0; --i) {
  3149. threads.emplace_back([&]() {
  3150. auto res = cli_.Get("/streamed-cancel",
  3151. [&](const char *, uint64_t) { return true; });
  3152. --count;
  3153. ASSERT_TRUE(!res);
  3154. EXPECT_TRUE(res.error() == Error::Canceled ||
  3155. res.error() == Error::Read || res.error() == Error::Write);
  3156. });
  3157. }
  3158. std::this_thread::sleep_for(std::chrono::seconds(2));
  3159. while (count != 0) {
  3160. cli_.stop();
  3161. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3162. }
  3163. for (auto &t : threads) {
  3164. t.join();
  3165. }
  3166. }
  3167. TEST_F(ServerTest, GetWithRange1) {
  3168. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  3169. ASSERT_TRUE(res);
  3170. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3171. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3172. EXPECT_EQ(true, res->has_header("Content-Range"));
  3173. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3174. EXPECT_EQ(std::string("def"), res->body);
  3175. }
  3176. TEST_F(ServerTest, GetWithRange2) {
  3177. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  3178. ASSERT_TRUE(res);
  3179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3180. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3181. EXPECT_EQ(true, res->has_header("Content-Range"));
  3182. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3183. EXPECT_EQ(std::string("bcdefg"), res->body);
  3184. }
  3185. TEST_F(ServerTest, GetWithRange3) {
  3186. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  3187. ASSERT_TRUE(res);
  3188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3189. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3190. EXPECT_EQ(true, res->has_header("Content-Range"));
  3191. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3192. EXPECT_EQ(std::string("a"), res->body);
  3193. }
  3194. TEST_F(ServerTest, GetWithRange4) {
  3195. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  3196. ASSERT_TRUE(res);
  3197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3198. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3199. EXPECT_EQ(true, res->has_header("Content-Range"));
  3200. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3201. EXPECT_EQ(std::string("fg"), res->body);
  3202. }
  3203. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3204. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3205. ASSERT_TRUE(res);
  3206. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3207. }
  3208. TEST_F(ServerTest, GetWithRangeMultipart) {
  3209. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3213. EXPECT_EQ(false, res->has_header("Content-Range"));
  3214. EXPECT_EQ(267U, res->body.size());
  3215. }
  3216. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3217. auto res =
  3218. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3221. }
  3222. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3223. auto res = cli_.Get("/with-range-customized-response",
  3224. {{make_range_header({{1, 2}})}});
  3225. ASSERT_TRUE(res);
  3226. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3227. EXPECT_EQ(true, res->has_header("Content-Length"));
  3228. EXPECT_EQ(false, res->has_header("Content-Range"));
  3229. EXPECT_EQ(JSON_DATA, res->body);
  3230. }
  3231. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3232. auto res = cli_.Get("/with-range-customized-response",
  3233. {{make_range_header({{1, 2}, {4, 5}})}});
  3234. ASSERT_TRUE(res);
  3235. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3236. EXPECT_EQ(true, res->has_header("Content-Length"));
  3237. EXPECT_EQ(false, res->has_header("Content-Range"));
  3238. EXPECT_EQ(JSON_DATA, res->body);
  3239. }
  3240. TEST_F(ServerTest, Issue1772) {
  3241. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetStreamedChunked) {
  3246. auto res = cli_.Get("/streamed-chunked");
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::OK_200, res->status);
  3249. EXPECT_EQ(std::string("123456789"), res->body);
  3250. }
  3251. TEST_F(ServerTest, GetStreamedChunked2) {
  3252. auto res = cli_.Get("/streamed-chunked2");
  3253. ASSERT_TRUE(res);
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. EXPECT_EQ(std::string("123456789"), res->body);
  3256. }
  3257. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3258. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3259. ASSERT_TRUE(res);
  3260. EXPECT_EQ(StatusCode::OK_200, res->status);
  3261. EXPECT_EQ(std::string("123456789"), res->body);
  3262. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3263. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3264. }
  3265. TEST_F(ServerTest, LargeChunkedPost) {
  3266. Request req;
  3267. req.method = "POST";
  3268. req.path = "/large-chunked";
  3269. std::string host_and_port;
  3270. host_and_port += HOST;
  3271. host_and_port += ":";
  3272. host_and_port += std::to_string(PORT);
  3273. req.headers.emplace("Host", host_and_port.c_str());
  3274. req.headers.emplace("Accept", "*/*");
  3275. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3276. req.headers.emplace("Content-Type", "text/plain");
  3277. req.headers.emplace("Content-Length", "0");
  3278. req.headers.emplace("Transfer-Encoding", "chunked");
  3279. std::string long_string(30 * 1024u, 'a');
  3280. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3281. // Attempt to make a large enough post to exceed OS buffers, to test that
  3282. // the server handles short reads if the full chunk data isn't available.
  3283. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3284. auto res = std::make_shared<Response>();
  3285. auto error = Error::Success;
  3286. auto ret = cli_.send(req, *res, error);
  3287. ASSERT_TRUE(ret);
  3288. EXPECT_EQ(StatusCode::OK_200, res->status);
  3289. }
  3290. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3291. auto res = cli_.Get("/remote_addr");
  3292. ASSERT_TRUE(res);
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3295. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3296. }
  3297. TEST_F(ServerTest, GetMethodLocalAddr) {
  3298. auto res = cli_.Get("/local_addr");
  3299. ASSERT_TRUE(res);
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3302. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3303. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3304. }
  3305. TEST_F(ServerTest, HTTPResponseSplitting) {
  3306. auto res = cli_.Get("/http_response_splitting");
  3307. ASSERT_TRUE(res);
  3308. EXPECT_EQ(StatusCode::OK_200, res->status);
  3309. }
  3310. TEST_F(ServerTest, SlowRequest) {
  3311. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3312. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3313. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3314. }
  3315. #if 0
  3316. TEST_F(ServerTest, SlowPost) {
  3317. char buffer[64 * 1024];
  3318. memset(buffer, 0x42, sizeof(buffer));
  3319. auto res = cli_.Post(
  3320. "/slowpost", 64 * 1024 * 1024,
  3321. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3322. auto ret = sink.write(buffer, sizeof(buffer));
  3323. EXPECT_TRUE(ret);
  3324. return true;
  3325. },
  3326. "text/plain");
  3327. ASSERT_TRUE(res);
  3328. EXPECT_EQ(StatusCode::OK_200, res->status);
  3329. }
  3330. TEST_F(ServerTest, SlowPostFail) {
  3331. char buffer[64 * 1024];
  3332. memset(buffer, 0x42, sizeof(buffer));
  3333. cli_.set_write_timeout(std::chrono::seconds(0));
  3334. auto res = cli_.Post(
  3335. "/slowpost", 64 * 1024 * 1024,
  3336. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3337. sink.write(buffer, sizeof(buffer));
  3338. return true;
  3339. },
  3340. "text/plain");
  3341. ASSERT_TRUE(!res);
  3342. EXPECT_EQ(Error::Write, res.error());
  3343. }
  3344. #endif
  3345. TEST_F(ServerTest, Put) {
  3346. auto res = cli_.Put("/put", "PUT", "text/plain");
  3347. ASSERT_TRUE(res);
  3348. EXPECT_EQ(StatusCode::OK_200, res->status);
  3349. EXPECT_EQ("PUT", res->body);
  3350. }
  3351. TEST_F(ServerTest, PutWithContentProvider) {
  3352. auto res = cli_.Put(
  3353. "/put", 3,
  3354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3355. sink.os << "PUT";
  3356. return true;
  3357. },
  3358. "text/plain");
  3359. ASSERT_TRUE(res);
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("PUT", res->body);
  3362. }
  3363. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3364. auto res = cli_.Post(
  3365. "/post", 42,
  3366. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3367. return false;
  3368. },
  3369. "text/plain");
  3370. ASSERT_TRUE(!res);
  3371. EXPECT_EQ(Error::Canceled, res.error());
  3372. }
  3373. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3374. auto res = cli_.Put(
  3375. "/put",
  3376. [](size_t /*offset*/, DataSink &sink) {
  3377. sink.os << "PUT";
  3378. sink.done();
  3379. return true;
  3380. },
  3381. "text/plain");
  3382. ASSERT_TRUE(res);
  3383. EXPECT_EQ(StatusCode::OK_200, res->status);
  3384. EXPECT_EQ("PUT", res->body);
  3385. }
  3386. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3387. auto res = cli_.Post(
  3388. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3389. "text/plain");
  3390. ASSERT_TRUE(!res);
  3391. EXPECT_EQ(Error::Canceled, res.error());
  3392. }
  3393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3394. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3395. cli_.set_compress(true);
  3396. auto res = cli_.Put(
  3397. "/put", 3,
  3398. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3399. sink.os << "PUT";
  3400. return true;
  3401. },
  3402. "text/plain");
  3403. ASSERT_TRUE(res);
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. EXPECT_EQ("PUT", res->body);
  3406. }
  3407. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3408. cli_.set_compress(true);
  3409. auto res = cli_.Post(
  3410. "/post", 42,
  3411. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3412. return false;
  3413. },
  3414. "text/plain");
  3415. ASSERT_TRUE(!res);
  3416. EXPECT_EQ(Error::Canceled, res.error());
  3417. }
  3418. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3419. cli_.set_compress(true);
  3420. auto res = cli_.Put(
  3421. "/put",
  3422. [](size_t /*offset*/, DataSink &sink) {
  3423. sink.os << "PUT";
  3424. sink.done();
  3425. return true;
  3426. },
  3427. "text/plain");
  3428. ASSERT_TRUE(res);
  3429. EXPECT_EQ(StatusCode::OK_200, res->status);
  3430. EXPECT_EQ("PUT", res->body);
  3431. }
  3432. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3433. cli_.set_compress(true);
  3434. auto res = cli_.Post(
  3435. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3436. "text/plain");
  3437. ASSERT_TRUE(!res);
  3438. EXPECT_EQ(Error::Canceled, res.error());
  3439. }
  3440. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3441. cli_.set_compress(true);
  3442. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3443. ASSERT_TRUE(res);
  3444. EXPECT_EQ(StatusCode::OK_200, res->status);
  3445. EXPECT_EQ(LARGE_DATA, res->body);
  3446. }
  3447. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3448. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3449. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3450. Client cli(s.c_str());
  3451. cli.enable_server_certificate_verification(false);
  3452. #else
  3453. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3454. Client cli(s.c_str());
  3455. #endif
  3456. cli.set_compress(true);
  3457. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ(LARGE_DATA, res->body);
  3461. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  3462. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3463. }
  3464. TEST_F(ServerTest, PutContentWithDeflate) {
  3465. cli_.set_compress(false);
  3466. Headers headers;
  3467. headers.emplace("Content-Encoding", "deflate");
  3468. // PUT in deflate format:
  3469. auto res = cli_.Put("/put", headers,
  3470. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3471. ASSERT_TRUE(res);
  3472. EXPECT_EQ(StatusCode::OK_200, res->status);
  3473. EXPECT_EQ("PUT", res->body);
  3474. }
  3475. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3476. Headers headers;
  3477. headers.emplace("Accept-Encoding", "gzip, deflate");
  3478. auto res = cli_.Get("/streamed-chunked", headers);
  3479. ASSERT_TRUE(res);
  3480. EXPECT_EQ(StatusCode::OK_200, res->status);
  3481. EXPECT_EQ(std::string("123456789"), res->body);
  3482. }
  3483. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3484. Headers headers;
  3485. headers.emplace("Accept-Encoding", "gzip, deflate");
  3486. auto res = cli_.Get("/streamed-chunked2", headers);
  3487. ASSERT_TRUE(res);
  3488. EXPECT_EQ(StatusCode::OK_200, res->status);
  3489. EXPECT_EQ(std::string("123456789"), res->body);
  3490. }
  3491. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3492. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. }
  3496. TEST(GzipDecompressor, ChunkedDecompression) {
  3497. std::string data;
  3498. for (size_t i = 0; i < 32 * 1024; ++i) {
  3499. data.push_back(static_cast<char>('a' + i % 26));
  3500. }
  3501. std::string compressed_data;
  3502. {
  3503. httplib::detail::gzip_compressor compressor;
  3504. bool result = compressor.compress(
  3505. data.data(), data.size(),
  3506. /*last=*/true,
  3507. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3508. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3509. compressed_data_size);
  3510. return true;
  3511. });
  3512. ASSERT_TRUE(result);
  3513. }
  3514. std::string decompressed_data;
  3515. {
  3516. httplib::detail::gzip_decompressor decompressor;
  3517. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3518. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3519. size_t chunk_size = 130;
  3520. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3521. chunk_begin += chunk_size) {
  3522. size_t current_chunk_size =
  3523. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3524. bool result = decompressor.decompress(
  3525. compressed_data.data() + chunk_begin, current_chunk_size,
  3526. [&](const char *decompressed_data_chunk,
  3527. size_t decompressed_data_chunk_size) {
  3528. decompressed_data.insert(decompressed_data.size(),
  3529. decompressed_data_chunk,
  3530. decompressed_data_chunk_size);
  3531. return true;
  3532. });
  3533. ASSERT_TRUE(result);
  3534. }
  3535. }
  3536. ASSERT_EQ(data, decompressed_data);
  3537. }
  3538. TEST(GzipDecompressor, DeflateDecompression) {
  3539. std::string original_text = "Raw deflate without gzip";
  3540. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3541. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3542. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3543. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3544. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3545. std::string decompressed_data;
  3546. {
  3547. httplib::detail::gzip_decompressor decompressor;
  3548. bool result = decompressor.decompress(
  3549. compressed_data.data(), compressed_data.size(),
  3550. [&](const char *decompressed_data_chunk,
  3551. size_t decompressed_data_chunk_size) {
  3552. decompressed_data.insert(decompressed_data.size(),
  3553. decompressed_data_chunk,
  3554. decompressed_data_chunk_size);
  3555. return true;
  3556. });
  3557. ASSERT_TRUE(result);
  3558. }
  3559. ASSERT_EQ(original_text, decompressed_data);
  3560. }
  3561. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3562. std::string original_text = "Raw deflate without gzip";
  3563. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3564. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3565. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3566. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3567. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3568. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3569. std::string decompressed_data;
  3570. {
  3571. httplib::detail::gzip_decompressor decompressor;
  3572. bool result = decompressor.decompress(
  3573. compressed_data.data(), compressed_data.size(),
  3574. [&](const char *decompressed_data_chunk,
  3575. size_t decompressed_data_chunk_size) {
  3576. decompressed_data.insert(decompressed_data.size(),
  3577. decompressed_data_chunk,
  3578. decompressed_data_chunk_size);
  3579. return true;
  3580. });
  3581. ASSERT_TRUE(result);
  3582. }
  3583. ASSERT_EQ(original_text, decompressed_data);
  3584. }
  3585. #ifdef _WIN32
  3586. TEST(GzipDecompressor, LargeRandomData) {
  3587. // prepare large random data that is difficult to be compressed and is
  3588. // expected to have large size even when compressed
  3589. std::random_device seed_gen;
  3590. std::mt19937 random(seed_gen());
  3591. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3592. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3593. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3594. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3595. // compress data over 4GiB
  3596. std::string compressed_data;
  3597. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3598. httplib::detail::gzip_compressor compressor;
  3599. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3600. data.size() * sizeof(std::uint32_t), true,
  3601. [&](const char *data, size_t size) {
  3602. compressed_data.insert(
  3603. compressed_data.size(), data, size);
  3604. return true;
  3605. });
  3606. ASSERT_TRUE(result);
  3607. // FIXME: compressed data size is expected to be greater than 4GiB,
  3608. // but there is no guarantee
  3609. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3610. // decompress data over 4GiB
  3611. std::string decompressed_data;
  3612. decompressed_data.reserve(data_size);
  3613. httplib::detail::gzip_decompressor decompressor;
  3614. result = decompressor.decompress(
  3615. compressed_data.data(), compressed_data.size(),
  3616. [&](const char *data, size_t size) {
  3617. decompressed_data.insert(decompressed_data.size(), data, size);
  3618. return true;
  3619. });
  3620. ASSERT_TRUE(result);
  3621. // compare
  3622. ASSERT_EQ(data_size, decompressed_data.size());
  3623. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3624. 0);
  3625. }
  3626. #endif
  3627. #endif
  3628. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3629. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3630. Headers headers;
  3631. headers.emplace("Accept-Encoding", "br");
  3632. auto res = cli_.Get("/streamed-chunked", headers);
  3633. ASSERT_TRUE(res);
  3634. EXPECT_EQ(StatusCode::OK_200, res->status);
  3635. EXPECT_EQ(std::string("123456789"), res->body);
  3636. }
  3637. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3638. Headers headers;
  3639. headers.emplace("Accept-Encoding", "br");
  3640. auto res = cli_.Get("/streamed-chunked2", headers);
  3641. ASSERT_TRUE(res);
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ(std::string("123456789"), res->body);
  3644. }
  3645. #endif
  3646. TEST_F(ServerTest, Patch) {
  3647. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3648. ASSERT_TRUE(res);
  3649. EXPECT_EQ(StatusCode::OK_200, res->status);
  3650. EXPECT_EQ("PATCH", res->body);
  3651. }
  3652. TEST_F(ServerTest, Delete) {
  3653. auto res = cli_.Delete("/delete");
  3654. ASSERT_TRUE(res);
  3655. EXPECT_EQ(StatusCode::OK_200, res->status);
  3656. EXPECT_EQ("DELETE", res->body);
  3657. }
  3658. TEST_F(ServerTest, DeleteContentReceiver) {
  3659. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3660. ASSERT_TRUE(res);
  3661. EXPECT_EQ(StatusCode::OK_200, res->status);
  3662. EXPECT_EQ("content", res->body);
  3663. }
  3664. TEST_F(ServerTest, Options) {
  3665. auto res = cli_.Options("*");
  3666. ASSERT_TRUE(res);
  3667. EXPECT_EQ(StatusCode::OK_200, res->status);
  3668. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3669. EXPECT_TRUE(res->body.empty());
  3670. }
  3671. TEST_F(ServerTest, URL) {
  3672. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3673. ASSERT_TRUE(res);
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. }
  3676. TEST_F(ServerTest, ArrayParam) {
  3677. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST_F(ServerTest, NoMultipleHeaders) {
  3682. Headers headers = {{"Content-Length", "5"}};
  3683. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3684. "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::OK_200, res->status);
  3687. }
  3688. TEST_F(ServerTest, PostContentReceiver) {
  3689. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3690. ASSERT_TRUE(res);
  3691. ASSERT_EQ(StatusCode::OK_200, res->status);
  3692. ASSERT_EQ("content", res->body);
  3693. }
  3694. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3695. MultipartFormDataItems items = {
  3696. {"text1", "text default", "", ""},
  3697. {"text2", "aωb", "", ""},
  3698. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3699. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3700. {"file3", "", "", "application/octet-stream"},
  3701. };
  3702. auto res = cli_.Post("/content_receiver", items);
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. }
  3706. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3707. MultipartFormDataItems items = {
  3708. {"text1", "text default", "", ""},
  3709. {"text2", "aωb", "", ""},
  3710. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3711. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3712. {"file3", "", "", "application/octet-stream"},
  3713. };
  3714. auto boundary = std::string("+++++");
  3715. std::string body;
  3716. for (const auto &item : items) {
  3717. body += "--" + boundary + "\r\n";
  3718. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3719. if (!item.filename.empty()) {
  3720. body += "; filename=\"" + item.filename + "\"";
  3721. }
  3722. body += "\r\n";
  3723. if (!item.content_type.empty()) {
  3724. body += "Content-Type: " + item.content_type + "\r\n";
  3725. }
  3726. body += "\r\n";
  3727. body += item.content + "\r\n";
  3728. }
  3729. body += "--" + boundary + "--\r\n";
  3730. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3731. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3732. ASSERT_TRUE(res);
  3733. EXPECT_EQ(StatusCode::OK_200, res->status);
  3734. }
  3735. TEST_F(ServerTest, PostContentReceiverGzip) {
  3736. cli_.set_compress(true);
  3737. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3738. ASSERT_TRUE(res);
  3739. ASSERT_EQ(StatusCode::OK_200, res->status);
  3740. ASSERT_EQ("content", res->body);
  3741. }
  3742. TEST_F(ServerTest, PutContentReceiver) {
  3743. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3744. ASSERT_TRUE(res);
  3745. ASSERT_EQ(StatusCode::OK_200, res->status);
  3746. ASSERT_EQ("content", res->body);
  3747. }
  3748. TEST_F(ServerTest, PatchContentReceiver) {
  3749. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3750. ASSERT_TRUE(res);
  3751. ASSERT_EQ(StatusCode::OK_200, res->status);
  3752. ASSERT_EQ("content", res->body);
  3753. }
  3754. TEST_F(ServerTest, PostQueryStringAndBody) {
  3755. auto res =
  3756. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3757. ASSERT_TRUE(res);
  3758. ASSERT_EQ(StatusCode::OK_200, res->status);
  3759. }
  3760. TEST_F(ServerTest, HTTP2Magic) {
  3761. Request req;
  3762. req.method = "PRI";
  3763. req.path = "*";
  3764. req.body = "SM";
  3765. auto res = std::make_shared<Response>();
  3766. auto error = Error::Success;
  3767. auto ret = cli_.send(req, *res, error);
  3768. ASSERT_TRUE(ret);
  3769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3770. }
  3771. TEST_F(ServerTest, KeepAlive) {
  3772. auto res = cli_.Get("/hi");
  3773. ASSERT_TRUE(res);
  3774. EXPECT_EQ(StatusCode::OK_200, res->status);
  3775. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3776. EXPECT_EQ("Hello World!", res->body);
  3777. res = cli_.Get("/hi");
  3778. ASSERT_TRUE(res);
  3779. EXPECT_EQ(StatusCode::OK_200, res->status);
  3780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3781. EXPECT_EQ("Hello World!", res->body);
  3782. res = cli_.Get("/hi");
  3783. ASSERT_TRUE(res);
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3786. EXPECT_EQ("Hello World!", res->body);
  3787. res = cli_.Get("/not-exist");
  3788. ASSERT_TRUE(res);
  3789. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3790. res = cli_.Post("/empty", "", "text/plain");
  3791. ASSERT_TRUE(res);
  3792. EXPECT_EQ(StatusCode::OK_200, res->status);
  3793. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3794. EXPECT_EQ("empty", res->body);
  3795. EXPECT_EQ("close", res->get_header_value("Connection"));
  3796. res = cli_.Post(
  3797. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3798. "text/plain");
  3799. ASSERT_TRUE(res);
  3800. EXPECT_EQ(StatusCode::OK_200, res->status);
  3801. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3802. EXPECT_EQ("empty", res->body);
  3803. cli_.set_keep_alive(false);
  3804. res = cli_.Get("/last-request");
  3805. ASSERT_TRUE(res);
  3806. EXPECT_EQ(StatusCode::OK_200, res->status);
  3807. EXPECT_EQ("close", res->get_header_value("Connection"));
  3808. }
  3809. TEST_F(ServerTest, TooManyRedirect) {
  3810. cli_.set_follow_location(true);
  3811. auto res = cli_.Get("/redirect/0");
  3812. ASSERT_TRUE(!res);
  3813. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3814. }
  3815. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3816. TEST_F(ServerTest, Gzip) {
  3817. Headers headers;
  3818. headers.emplace("Accept-Encoding", "gzip, deflate");
  3819. auto res = cli_.Get("/compress", headers);
  3820. ASSERT_TRUE(res);
  3821. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3823. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3824. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3825. "7890123456789012345678901234567890",
  3826. res->body);
  3827. EXPECT_EQ(StatusCode::OK_200, res->status);
  3828. }
  3829. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3830. auto res = cli_.Get("/compress");
  3831. ASSERT_TRUE(res);
  3832. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3833. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3834. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3835. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3836. "7890123456789012345678901234567890",
  3837. res->body);
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. }
  3840. TEST_F(ServerTest, GzipWithContentReceiver) {
  3841. Headers headers;
  3842. headers.emplace("Accept-Encoding", "gzip, deflate");
  3843. std::string body;
  3844. auto res = cli_.Get("/compress", headers,
  3845. [&](const char *data, uint64_t data_length) {
  3846. EXPECT_EQ(100U, data_length);
  3847. body.append(data, data_length);
  3848. return true;
  3849. });
  3850. ASSERT_TRUE(res);
  3851. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3852. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3853. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3854. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3855. "7890123456789012345678901234567890",
  3856. body);
  3857. EXPECT_EQ(StatusCode::OK_200, res->status);
  3858. }
  3859. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3860. Headers headers;
  3861. headers.emplace("Accept-Encoding", "gzip, deflate");
  3862. cli_.set_decompress(false);
  3863. auto res = cli_.Get("/compress", headers);
  3864. ASSERT_TRUE(res);
  3865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3867. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3868. EXPECT_EQ(33U, res->body.size());
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3872. std::string body;
  3873. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3874. EXPECT_EQ(100U, data_length);
  3875. body.append(data, data_length);
  3876. return true;
  3877. });
  3878. ASSERT_TRUE(res);
  3879. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3880. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3881. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3882. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3883. "7890123456789012345678901234567890",
  3884. body);
  3885. EXPECT_EQ(StatusCode::OK_200, res->status);
  3886. }
  3887. TEST_F(ServerTest, NoGzip) {
  3888. Headers headers;
  3889. headers.emplace("Accept-Encoding", "gzip, deflate");
  3890. auto res = cli_.Get("/nocompress", headers);
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3893. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3894. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3895. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3896. "7890123456789012345678901234567890",
  3897. res->body);
  3898. EXPECT_EQ(StatusCode::OK_200, res->status);
  3899. }
  3900. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3901. Headers headers;
  3902. headers.emplace("Accept-Encoding", "gzip, deflate");
  3903. std::string body;
  3904. auto res = cli_.Get("/nocompress", headers,
  3905. [&](const char *data, uint64_t data_length) {
  3906. EXPECT_EQ(100U, data_length);
  3907. body.append(data, data_length);
  3908. return true;
  3909. });
  3910. ASSERT_TRUE(res);
  3911. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3912. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3913. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3914. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3915. "7890123456789012345678901234567890",
  3916. body);
  3917. EXPECT_EQ(StatusCode::OK_200, res->status);
  3918. }
  3919. TEST_F(ServerTest, MultipartFormDataGzip) {
  3920. MultipartFormDataItems items = {
  3921. {"key1", "test", "", ""},
  3922. {"key2", "--abcdefg123", "", ""},
  3923. };
  3924. cli_.set_compress(true);
  3925. auto res = cli_.Post("/compress-multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. #endif
  3930. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3931. TEST_F(ServerTest, Brotli) {
  3932. Headers headers;
  3933. headers.emplace("Accept-Encoding", "br");
  3934. auto res = cli_.Get("/compress", headers);
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3937. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3938. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3939. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3940. "7890123456789012345678901234567890",
  3941. res->body);
  3942. EXPECT_EQ(StatusCode::OK_200, res->status);
  3943. }
  3944. #endif
  3945. // Sends a raw request to a server listening at HOST:PORT.
  3946. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3947. std::string *resp = nullptr) {
  3948. auto error = Error::Success;
  3949. auto client_sock = detail::create_client_socket(
  3950. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3951. /*connection_timeout_sec=*/5, 0,
  3952. /*read_timeout_sec=*/5, 0,
  3953. /*write_timeout_sec=*/5, 0, std::string(), error);
  3954. if (client_sock == INVALID_SOCKET) { return false; }
  3955. auto ret = detail::process_client_socket(
  3956. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3957. if (req.size() !=
  3958. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3959. return false;
  3960. }
  3961. char buf[512];
  3962. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3963. while (line_reader.getline()) {
  3964. if (resp) { *resp += line_reader.ptr(); }
  3965. }
  3966. return true;
  3967. });
  3968. detail::close_socket(client_sock);
  3969. return ret;
  3970. }
  3971. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3972. Server svr;
  3973. std::string header_value;
  3974. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3975. header_value = req.get_header_value("foo");
  3976. res.set_content("ok", "text/plain");
  3977. });
  3978. thread t = thread([&] { svr.listen(HOST, PORT); });
  3979. auto se = detail::scope_exit([&] {
  3980. svr.stop();
  3981. t.join();
  3982. ASSERT_FALSE(svr.is_running());
  3983. });
  3984. svr.wait_until_ready();
  3985. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3986. // like characters are not treated the same - use vertical tab and escape.
  3987. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3988. "foo: \t \v bar \x1B\t \r\n"
  3989. "Connection: close\r\n"
  3990. "\r\n";
  3991. ASSERT_TRUE(send_request(5, req));
  3992. EXPECT_EQ(header_value, "\v bar \x1B");
  3993. }
  3994. // Sends a raw request and verifies that there isn't a crash or exception.
  3995. static void test_raw_request(const std::string &req,
  3996. std::string *out = nullptr) {
  3997. Server svr;
  3998. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3999. res.set_content("ok", "text/plain");
  4000. });
  4001. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4002. res.set_content("ok", "text/plain");
  4003. });
  4004. svr.Get("/header_field_value_check", [&](const Request &/*req*/, Response &res) {
  4005. res.set_content("ok", "text/plain");
  4006. });
  4007. // Server read timeout must be longer than the client read timeout for the
  4008. // bug to reproduce, probably to force the server to process a request
  4009. // without a trailing blank line.
  4010. const time_t client_read_timeout_sec = 1;
  4011. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4012. bool listen_thread_ok = false;
  4013. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4014. auto se = detail::scope_exit([&] {
  4015. svr.stop();
  4016. t.join();
  4017. ASSERT_FALSE(svr.is_running());
  4018. EXPECT_TRUE(listen_thread_ok);
  4019. });
  4020. svr.wait_until_ready();
  4021. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4022. }
  4023. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4024. // A certain header line causes an exception if the header property is parsed
  4025. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4026. test_raw_request(
  4027. "GET /hi HTTP/1.1\r\n"
  4028. " : "
  4029. " "
  4030. " ");
  4031. }
  4032. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4033. // A certain header line causes an exception if the header property *name* is
  4034. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4035. // greedy matcher and requires backtracking when there are a lot of ":"
  4036. // characters.
  4037. // This occurs with libc++ but not libstdc++.
  4038. test_raw_request(
  4039. "GET /hi HTTP/1.1\r\n"
  4040. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4041. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4042. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4043. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4044. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4045. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4046. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4047. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4048. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4049. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4050. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4051. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4052. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4053. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4054. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4055. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4056. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4057. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4058. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4059. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4060. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4061. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4062. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4063. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4064. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4065. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4066. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4067. "&&&%%%");
  4068. }
  4069. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4070. // Make sure this doesn't crash the server.
  4071. // In a previous version of the header line regex, the "\r" rendered the line
  4072. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4073. // a new position where the leading white space ended and the field value
  4074. // began.
  4075. // The crash occurs with libc++ but not libstdc++.
  4076. test_raw_request("GET /hi HTTP/1.1\r\n"
  4077. "a:" +
  4078. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4079. "\r\n"
  4080. "\r\n");
  4081. }
  4082. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4083. std::string out;
  4084. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4085. "Content-Type: text/plain\r\n"
  4086. "Transfer-Encoding: chunked\r\n"
  4087. "\r\n"
  4088. "nothex\r\n",
  4089. &out);
  4090. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4091. }
  4092. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4093. std::string out;
  4094. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4095. "Content-Type: text/plain\r\n"
  4096. "Transfer-Encoding: chunked\r\n"
  4097. "\r\n"
  4098. "3\r\n"
  4099. "xyz\r\n"
  4100. "NaN\r\n",
  4101. &out);
  4102. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4103. }
  4104. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4105. std::string out;
  4106. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4107. "Content-Type: text/plain\r\n"
  4108. "Transfer-Encoding: chunked\r\n"
  4109. "\r\n"
  4110. // Length is too large for 64 bits.
  4111. "1ffffffffffffffff\r\n"
  4112. "xyz\r\n",
  4113. &out);
  4114. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4115. }
  4116. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4117. test_raw_request("GET /hi HTTP/1.1\r\n"
  4118. "Content-Type: text/plain\r\n\r");
  4119. }
  4120. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4121. std::string out;
  4122. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4123. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4124. }
  4125. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4126. std::string out;
  4127. std::string request(
  4128. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4129. test_raw_request(request, &out);
  4130. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4131. }
  4132. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4133. Server svr;
  4134. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4135. res.set_header("Cache-Control", "no-cache");
  4136. res.set_chunked_content_provider(
  4137. "text/event-stream", [](size_t offset, DataSink &sink) {
  4138. std::string s = "data:";
  4139. s += std::to_string(offset);
  4140. s += "\n\n";
  4141. auto ret = sink.write(s.data(), s.size());
  4142. EXPECT_TRUE(ret);
  4143. std::this_thread::sleep_for(std::chrono::seconds(1));
  4144. return true;
  4145. });
  4146. });
  4147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4148. svr.wait_until_ready();
  4149. Client client(HOST, PORT);
  4150. const Headers headers = {{"Accept", "text/event-stream"}};
  4151. auto get_thread = std::thread([&client, &headers]() {
  4152. auto res = client.Get(
  4153. "/events", headers,
  4154. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4155. });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. get_thread.join();
  4159. listen_thread.join();
  4160. ASSERT_FALSE(svr.is_running());
  4161. });
  4162. // Give GET time to get a few messages.
  4163. std::this_thread::sleep_for(std::chrono::seconds(2));
  4164. }
  4165. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4166. httplib::Server svr;
  4167. svr.Post("/hi",
  4168. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4169. res.status = StatusCode::OK_200;
  4170. });
  4171. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4172. svr.wait_until_ready();
  4173. Client cli(HOST, PORT);
  4174. auto res = cli.Post("/hi", "data", "text/plain");
  4175. ASSERT_TRUE(res);
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. svr.stop();
  4178. thread.join();
  4179. ASSERT_FALSE(svr.is_running());
  4180. res = cli.Post("/hi", "data", "text/plain");
  4181. ASSERT_FALSE(res);
  4182. }
  4183. TEST(ServerStopTest, ListenFailure) {
  4184. Server svr;
  4185. auto t = thread([&]() {
  4186. auto ret = svr.listen("????", PORT);
  4187. EXPECT_FALSE(ret);
  4188. });
  4189. svr.wait_until_ready();
  4190. svr.stop();
  4191. t.join();
  4192. }
  4193. TEST(ServerStopTest, Decommision) {
  4194. Server svr;
  4195. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4196. for (int i = 0; i < 4; i++) {
  4197. auto is_even = !(i % 2);
  4198. std::thread t{[&] {
  4199. try {
  4200. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4201. if (is_even) {
  4202. throw std::runtime_error("Some thing that happens to go wrong.");
  4203. }
  4204. svr.listen(HOST, PORT);
  4205. } catch (...) { svr.decommission(); }
  4206. }};
  4207. svr.wait_until_ready();
  4208. // Server is up
  4209. {
  4210. Client cli(HOST, PORT);
  4211. auto res = cli.Get("/hi");
  4212. if (is_even) {
  4213. EXPECT_FALSE(res);
  4214. } else {
  4215. EXPECT_TRUE(res);
  4216. EXPECT_EQ("hi...", res->body);
  4217. }
  4218. }
  4219. svr.stop();
  4220. t.join();
  4221. // Server is down...
  4222. {
  4223. Client cli(HOST, PORT);
  4224. auto res = cli.Get("/hi");
  4225. EXPECT_FALSE(res);
  4226. }
  4227. }
  4228. }
  4229. TEST(StreamingTest, NoContentLengthStreaming) {
  4230. Server svr;
  4231. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4232. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4233. if (offset < 6) {
  4234. sink.os << (offset < 3 ? "a" : "b");
  4235. } else {
  4236. sink.done();
  4237. }
  4238. return true;
  4239. });
  4240. });
  4241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4242. auto listen_se = detail::scope_exit([&] {
  4243. svr.stop();
  4244. listen_thread.join();
  4245. ASSERT_FALSE(svr.is_running());
  4246. });
  4247. svr.wait_until_ready();
  4248. Client client(HOST, PORT);
  4249. auto get_thread = std::thread([&client]() {
  4250. std::string s;
  4251. auto res =
  4252. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4253. s += std::string(data, len);
  4254. return true;
  4255. });
  4256. EXPECT_EQ("aaabbb", s);
  4257. });
  4258. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4259. // Give GET time to get a few messages.
  4260. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4261. }
  4262. TEST(MountTest, Unmount) {
  4263. Server svr;
  4264. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4265. auto se = detail::scope_exit([&] {
  4266. svr.stop();
  4267. listen_thread.join();
  4268. ASSERT_FALSE(svr.is_running());
  4269. });
  4270. svr.wait_until_ready();
  4271. Client cli("localhost", PORT);
  4272. svr.set_mount_point("/mount2", "./www2");
  4273. auto res = cli.Get("/");
  4274. ASSERT_TRUE(res);
  4275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4276. res = cli.Get("/mount2/dir/test.html");
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::OK_200, res->status);
  4279. svr.set_mount_point("/", "./www");
  4280. res = cli.Get("/dir/");
  4281. ASSERT_TRUE(res);
  4282. EXPECT_EQ(StatusCode::OK_200, res->status);
  4283. svr.remove_mount_point("/");
  4284. res = cli.Get("/dir/");
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4287. svr.remove_mount_point("/mount2");
  4288. res = cli.Get("/mount2/dir/test.html");
  4289. ASSERT_TRUE(res);
  4290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4291. }
  4292. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4293. TEST(ExceptionTest, ThrowExceptionInHandler) {
  4294. Server svr;
  4295. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4296. throw std::runtime_error("exception...");
  4297. });
  4298. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4299. throw std::runtime_error("exception\r\n...");
  4300. });
  4301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4302. auto se = detail::scope_exit([&] {
  4303. svr.stop();
  4304. listen_thread.join();
  4305. ASSERT_FALSE(svr.is_running());
  4306. });
  4307. svr.wait_until_ready();
  4308. Client cli("localhost", PORT);
  4309. {
  4310. auto res = cli.Get("/exception");
  4311. ASSERT_TRUE(res);
  4312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4313. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4314. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  4315. }
  4316. {
  4317. auto res = cli.Get("/unknown");
  4318. ASSERT_TRUE(res);
  4319. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4320. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4321. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  4322. }
  4323. }
  4324. #endif
  4325. TEST(KeepAliveTest, ReadTimeout) {
  4326. Server svr;
  4327. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4328. std::this_thread::sleep_for(std::chrono::seconds(2));
  4329. res.set_content("a", "text/plain");
  4330. });
  4331. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4332. res.set_content("b", "text/plain");
  4333. });
  4334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4335. auto se = detail::scope_exit([&] {
  4336. svr.stop();
  4337. listen_thread.join();
  4338. ASSERT_FALSE(svr.is_running());
  4339. });
  4340. svr.wait_until_ready();
  4341. Client cli("localhost", PORT);
  4342. cli.set_keep_alive(true);
  4343. cli.set_read_timeout(std::chrono::seconds(1));
  4344. auto resa = cli.Get("/a");
  4345. ASSERT_FALSE(resa);
  4346. EXPECT_EQ(Error::Read, resa.error());
  4347. auto resb = cli.Get("/b");
  4348. ASSERT_TRUE(resb);
  4349. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4350. EXPECT_EQ("b", resb->body);
  4351. }
  4352. TEST(KeepAliveTest, Issue1041) {
  4353. Server svr;
  4354. svr.set_keep_alive_timeout(3);
  4355. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4356. res.set_content("Hello World!", "text/plain");
  4357. });
  4358. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. listen_thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. Client cli(HOST, PORT);
  4366. cli.set_keep_alive(true);
  4367. auto result = cli.Get("/hi");
  4368. ASSERT_TRUE(result);
  4369. EXPECT_EQ(StatusCode::OK_200, result->status);
  4370. std::this_thread::sleep_for(std::chrono::seconds(5));
  4371. result = cli.Get("/hi");
  4372. ASSERT_TRUE(result);
  4373. EXPECT_EQ(StatusCode::OK_200, result->status);
  4374. }
  4375. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4376. TEST(KeepAliveTest, SSLClientReconnection) {
  4377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4378. ASSERT_TRUE(svr.is_valid());
  4379. svr.set_keep_alive_timeout(1);
  4380. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4381. res.set_content("Hello World!", "text/plain");
  4382. });
  4383. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4384. auto se = detail::scope_exit([&] {
  4385. svr.stop();
  4386. listen_thread.join();
  4387. ASSERT_FALSE(svr.is_running());
  4388. });
  4389. svr.wait_until_ready();
  4390. SSLClient cli(HOST, PORT);
  4391. cli.enable_server_certificate_verification(false);
  4392. cli.set_keep_alive(true);
  4393. auto result = cli.Get("/hi");
  4394. ASSERT_TRUE(result);
  4395. EXPECT_EQ(StatusCode::OK_200, result->status);
  4396. result = cli.Get("/hi");
  4397. ASSERT_TRUE(result);
  4398. EXPECT_EQ(StatusCode::OK_200, result->status);
  4399. std::this_thread::sleep_for(std::chrono::seconds(2));
  4400. // Recoonect
  4401. result = cli.Get("/hi");
  4402. ASSERT_TRUE(result);
  4403. EXPECT_EQ(StatusCode::OK_200, result->status);
  4404. result = cli.Get("/hi");
  4405. ASSERT_TRUE(result);
  4406. EXPECT_EQ(StatusCode::OK_200, result->status);
  4407. }
  4408. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4409. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4410. ASSERT_TRUE(svr.is_valid());
  4411. svr.set_keep_alive_timeout(1);
  4412. std::string content = "reconnect";
  4413. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4414. res.set_content("Hello World!", "text/plain");
  4415. });
  4416. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4417. auto se = detail::scope_exit([&] {
  4418. svr.stop();
  4419. listen_thread.join();
  4420. ASSERT_FALSE(svr.is_running());
  4421. });
  4422. svr.wait_until_ready();
  4423. SSLClient cli(HOST, PORT);
  4424. cli.enable_server_certificate_verification(false);
  4425. cli.set_keep_alive(true);
  4426. auto result = cli.Post(
  4427. "/hi", content.size(),
  4428. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4429. sink.write(content.c_str(), content.size());
  4430. return true;
  4431. },
  4432. "text/plain");
  4433. ASSERT_TRUE(result);
  4434. EXPECT_EQ(200, result->status);
  4435. std::this_thread::sleep_for(std::chrono::seconds(2));
  4436. // Recoonect
  4437. result = cli.Post(
  4438. "/hi", content.size(),
  4439. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4440. sink.write(content.c_str(), content.size());
  4441. return true;
  4442. },
  4443. "text/plain");
  4444. ASSERT_TRUE(result);
  4445. EXPECT_EQ(200, result->status);
  4446. result = cli.Post(
  4447. "/hi", content.size(),
  4448. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4449. sink.write(content.c_str(), content.size());
  4450. return true;
  4451. },
  4452. "text/plain");
  4453. ASSERT_TRUE(result);
  4454. EXPECT_EQ(200, result->status);
  4455. }
  4456. #endif
  4457. TEST(ClientProblemDetectionTest, ContentProvider) {
  4458. Server svr;
  4459. size_t content_length = 1024 * 1024;
  4460. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4461. res.set_content_provider(
  4462. content_length, "text/plain",
  4463. [&](size_t offset, size_t length, DataSink &sink) {
  4464. auto out_len = std::min(length, static_cast<size_t>(1024));
  4465. std::string out(out_len, '@');
  4466. sink.write(out.data(), out_len);
  4467. return offset < 4096;
  4468. },
  4469. [](bool success) { ASSERT_FALSE(success); });
  4470. });
  4471. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4472. res.set_content_provider(
  4473. 0, "text/plain",
  4474. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4475. EXPECT_TRUE(false);
  4476. return true;
  4477. },
  4478. [](bool success) { ASSERT_FALSE(success); });
  4479. });
  4480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. listen_thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli("localhost", PORT);
  4488. {
  4489. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4490. size_t /*data_length*/) { return false; });
  4491. ASSERT_FALSE(res);
  4492. }
  4493. {
  4494. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4495. size_t /*data_length*/) { return false; });
  4496. ASSERT_TRUE(res);
  4497. }
  4498. }
  4499. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4500. Server svr;
  4501. svr.set_error_handler([](Request const &, Response &res) -> void {
  4502. res.set_chunked_content_provider(
  4503. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4504. sink.os << "hello";
  4505. sink.os << "world";
  4506. sink.done();
  4507. return true;
  4508. });
  4509. });
  4510. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4511. auto se = detail::scope_exit([&] {
  4512. svr.stop();
  4513. listen_thread.join();
  4514. ASSERT_FALSE(svr.is_running());
  4515. });
  4516. svr.wait_until_ready();
  4517. Client cli("localhost", PORT);
  4518. auto res = cli.Get("/");
  4519. ASSERT_TRUE(res);
  4520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4521. EXPECT_EQ("helloworld", res->body);
  4522. }
  4523. TEST(LongPollingTest, ClientCloseDetection) {
  4524. Server svr;
  4525. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4526. res.set_chunked_content_provider(
  4527. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4528. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4529. sink.os << "hello";
  4530. auto count = 10;
  4531. while (count > 0 && sink.is_writable()) {
  4532. this_thread::sleep_for(chrono::milliseconds(10));
  4533. }
  4534. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4535. return true;
  4536. });
  4537. });
  4538. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4539. auto se = detail::scope_exit([&] {
  4540. svr.stop();
  4541. listen_thread.join();
  4542. ASSERT_FALSE(svr.is_running());
  4543. });
  4544. svr.wait_until_ready();
  4545. Client cli("localhost", PORT);
  4546. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4547. EXPECT_EQ("hello", string(data, data_length));
  4548. return false; // close the socket immediately.
  4549. });
  4550. ASSERT_FALSE(res);
  4551. }
  4552. TEST(GetWithParametersTest, GetWithParameters) {
  4553. Server svr;
  4554. svr.Get("/", [&](const Request &req, Response &) {
  4555. EXPECT_EQ("world", req.get_param_value("hello"));
  4556. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4557. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4558. });
  4559. svr.Get("/params", [&](const Request &req, Response &) {
  4560. EXPECT_EQ("world", req.get_param_value("hello"));
  4561. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4562. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4563. });
  4564. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4565. EXPECT_EQ("resource-id", req.matches[1]);
  4566. EXPECT_EQ("foo", req.get_param_value("param1"));
  4567. EXPECT_EQ("bar", req.get_param_value("param2"));
  4568. });
  4569. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4570. EXPECT_EQ("user-id", req.path_params.at("id"));
  4571. EXPECT_EQ("foo", req.get_param_value("param1"));
  4572. EXPECT_EQ("bar", req.get_param_value("param2"));
  4573. });
  4574. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4575. auto se = detail::scope_exit([&] {
  4576. svr.stop();
  4577. listen_thread.join();
  4578. ASSERT_FALSE(svr.is_running());
  4579. });
  4580. svr.wait_until_ready();
  4581. {
  4582. Client cli(HOST, PORT);
  4583. Params params;
  4584. params.emplace("hello", "world");
  4585. params.emplace("hello2", "world2");
  4586. params.emplace("hello3", "world3");
  4587. auto res = cli.Get("/", params, Headers{});
  4588. ASSERT_TRUE(res);
  4589. EXPECT_EQ(StatusCode::OK_200, res->status);
  4590. }
  4591. {
  4592. Client cli(HOST, PORT);
  4593. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4594. ASSERT_TRUE(res);
  4595. EXPECT_EQ(StatusCode::OK_200, res->status);
  4596. }
  4597. {
  4598. Client cli(HOST, PORT);
  4599. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4600. ASSERT_TRUE(res);
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. {
  4604. Client cli(HOST, PORT);
  4605. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. }
  4609. }
  4610. TEST(GetWithParametersTest, GetWithParameters2) {
  4611. Server svr;
  4612. svr.Get("/", [&](const Request &req, Response &res) {
  4613. auto text = req.get_param_value("hello");
  4614. res.set_content(text, "text/plain");
  4615. });
  4616. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4617. auto se = detail::scope_exit([&] {
  4618. svr.stop();
  4619. listen_thread.join();
  4620. ASSERT_FALSE(svr.is_running());
  4621. });
  4622. svr.wait_until_ready();
  4623. Client cli("localhost", PORT);
  4624. Params params;
  4625. params.emplace("hello", "world");
  4626. std::string body;
  4627. auto res = cli.Get("/", params, Headers{},
  4628. [&](const char *data, size_t data_length) {
  4629. body.append(data, data_length);
  4630. return true;
  4631. });
  4632. ASSERT_TRUE(res);
  4633. EXPECT_EQ(StatusCode::OK_200, res->status);
  4634. EXPECT_EQ("world", body);
  4635. }
  4636. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4637. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4638. auto host = "httpbin.org";
  4639. auto path = std::string{"/range/32"};
  4640. #else
  4641. auto host = "nghttp2.org";
  4642. auto path = std::string{"/httpbin/range/32"};
  4643. #endif
  4644. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4645. SSLClient cli(host);
  4646. #else
  4647. Client cli(host);
  4648. #endif
  4649. cli.set_default_headers({make_range_header({{1, 10}})});
  4650. cli.set_connection_timeout(5);
  4651. {
  4652. auto res = cli.Get(path);
  4653. ASSERT_TRUE(res);
  4654. EXPECT_EQ("bcdefghijk", res->body);
  4655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4656. }
  4657. {
  4658. auto res = cli.Get(path);
  4659. ASSERT_TRUE(res);
  4660. EXPECT_EQ("bcdefghijk", res->body);
  4661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4662. }
  4663. }
  4664. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4665. Server svr;
  4666. svr.set_default_headers({{"Hello", "World"}});
  4667. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4668. res.set_content("ok", "text/plain");
  4669. });
  4670. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. listen_thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. Client cli("localhost", PORT);
  4678. auto res = cli.Get("/");
  4679. ASSERT_TRUE(res);
  4680. EXPECT_EQ(StatusCode::OK_200, res->status);
  4681. EXPECT_EQ("ok", res->body);
  4682. EXPECT_EQ("World", res->get_header_value("Hello"));
  4683. }
  4684. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4685. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4687. ASSERT_TRUE(svr.is_valid());
  4688. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4689. std::this_thread::sleep_for(std::chrono::seconds(2));
  4690. res.set_content("a", "text/plain");
  4691. });
  4692. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4693. res.set_content("b", "text/plain");
  4694. });
  4695. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4696. auto se = detail::scope_exit([&] {
  4697. svr.stop();
  4698. listen_thread.join();
  4699. ASSERT_FALSE(svr.is_running());
  4700. });
  4701. svr.wait_until_ready();
  4702. SSLClient cli("localhost", PORT);
  4703. cli.enable_server_certificate_verification(false);
  4704. cli.set_keep_alive(true);
  4705. cli.set_read_timeout(std::chrono::seconds(1));
  4706. auto resa = cli.Get("/a");
  4707. ASSERT_TRUE(!resa);
  4708. EXPECT_EQ(Error::Read, resa.error());
  4709. auto resb = cli.Get("/b");
  4710. ASSERT_TRUE(resb);
  4711. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4712. EXPECT_EQ("b", resb->body);
  4713. }
  4714. #endif
  4715. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4716. protected:
  4717. ServerTestWithAI_PASSIVE()
  4718. : cli_(HOST, PORT)
  4719. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4720. ,
  4721. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4722. #endif
  4723. {
  4724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4725. cli_.enable_server_certificate_verification(false);
  4726. #endif
  4727. }
  4728. virtual void SetUp() {
  4729. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4730. res.set_content("Hello World!", "text/plain");
  4731. });
  4732. t_ = thread(
  4733. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4734. svr_.wait_until_ready();
  4735. }
  4736. virtual void TearDown() {
  4737. svr_.stop();
  4738. t_.join();
  4739. }
  4740. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4741. SSLClient cli_;
  4742. SSLServer svr_;
  4743. #else
  4744. Client cli_;
  4745. Server svr_;
  4746. #endif
  4747. thread t_;
  4748. };
  4749. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4750. auto res = cli_.Get("/hi");
  4751. ASSERT_TRUE(res);
  4752. EXPECT_EQ(StatusCode::OK_200, res->status);
  4753. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4754. EXPECT_EQ("Hello World!", res->body);
  4755. }
  4756. class ServerUpDownTest : public ::testing::Test {
  4757. protected:
  4758. ServerUpDownTest() : cli_(HOST, PORT) {}
  4759. virtual void SetUp() {
  4760. t_ = thread([&]() {
  4761. svr_.bind_to_any_port(HOST);
  4762. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4763. ASSERT_TRUE(svr_.listen_after_bind());
  4764. });
  4765. svr_.wait_until_ready();
  4766. }
  4767. virtual void TearDown() {
  4768. svr_.stop();
  4769. t_.join();
  4770. }
  4771. Client cli_;
  4772. Server svr_;
  4773. thread t_;
  4774. };
  4775. TEST_F(ServerUpDownTest, QuickStartStop) {
  4776. // Should not crash, especially when run with
  4777. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4778. }
  4779. class PayloadMaxLengthTest : public ::testing::Test {
  4780. protected:
  4781. PayloadMaxLengthTest()
  4782. : cli_(HOST, PORT)
  4783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4784. ,
  4785. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4786. #endif
  4787. {
  4788. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4789. cli_.enable_server_certificate_verification(false);
  4790. #endif
  4791. }
  4792. virtual void SetUp() {
  4793. svr_.set_payload_max_length(8);
  4794. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4795. res.set_content("test", "text/plain");
  4796. });
  4797. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4798. svr_.wait_until_ready();
  4799. }
  4800. virtual void TearDown() {
  4801. svr_.stop();
  4802. t_.join();
  4803. }
  4804. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4805. SSLClient cli_;
  4806. SSLServer svr_;
  4807. #else
  4808. Client cli_;
  4809. Server svr_;
  4810. #endif
  4811. thread t_;
  4812. };
  4813. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4814. auto res = cli_.Post("/test", "123456789", "text/plain");
  4815. ASSERT_TRUE(res);
  4816. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4817. res = cli_.Post("/test", "12345678", "text/plain");
  4818. ASSERT_TRUE(res);
  4819. EXPECT_EQ(StatusCode::OK_200, res->status);
  4820. }
  4821. TEST(HostAndPortPropertiesTest, NoSSL) {
  4822. httplib::Client cli("www.google.com", 1234);
  4823. ASSERT_EQ("www.google.com", cli.host());
  4824. ASSERT_EQ(1234, cli.port());
  4825. }
  4826. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4827. httplib::Client cli("www.google.com:1234");
  4828. ASSERT_EQ("www.google.com", cli.host());
  4829. ASSERT_EQ(1234, cli.port());
  4830. }
  4831. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4832. TEST(HostAndPortPropertiesTest, SSL) {
  4833. httplib::SSLClient cli("www.google.com");
  4834. ASSERT_EQ("www.google.com", cli.host());
  4835. ASSERT_EQ(443, cli.port());
  4836. }
  4837. #endif
  4838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4839. TEST(SSLClientTest, UpdateCAStore) {
  4840. httplib::SSLClient httplib_client("www.google.com");
  4841. auto ca_store_1 = X509_STORE_new();
  4842. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4843. nullptr);
  4844. httplib_client.set_ca_cert_store(ca_store_1);
  4845. auto ca_store_2 = X509_STORE_new();
  4846. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4847. nullptr);
  4848. httplib_client.set_ca_cert_store(ca_store_2);
  4849. }
  4850. TEST(SSLClientTest, ServerNameIndication_Online) {
  4851. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4852. auto host = "httpbin.org";
  4853. auto path = std::string{"/get"};
  4854. #else
  4855. auto host = "nghttp2.org";
  4856. auto path = std::string{"/httpbin/get"};
  4857. #endif
  4858. SSLClient cli(host, 443);
  4859. auto res = cli.Get(path);
  4860. ASSERT_TRUE(res);
  4861. ASSERT_EQ(StatusCode::OK_200, res->status);
  4862. }
  4863. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4864. Client cli("https://google.com");
  4865. auto res = cli.Get("/");
  4866. ASSERT_TRUE(res);
  4867. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4868. }
  4869. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4870. SSLClient cli("google.com");
  4871. cli.enable_server_certificate_verification(true);
  4872. cli.set_ca_cert_path("hello");
  4873. auto res = cli.Get("/");
  4874. ASSERT_TRUE(!res);
  4875. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4876. }
  4877. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4878. SSLClient cli("google.com");
  4879. cli.set_ca_cert_path(CA_CERT_FILE);
  4880. auto res = cli.Get("/");
  4881. ASSERT_TRUE(res);
  4882. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4883. }
  4884. TEST(SSLClientTest, ServerCertificateVerification4) {
  4885. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4886. ASSERT_TRUE(svr.is_valid());
  4887. svr.Get("/test", [&](const Request &, Response &res) {
  4888. res.set_content("test", "text/plain");
  4889. svr.stop();
  4890. ASSERT_TRUE(true);
  4891. });
  4892. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4893. auto se = detail::scope_exit([&] {
  4894. t.join();
  4895. ASSERT_FALSE(svr.is_running());
  4896. });
  4897. svr.wait_until_ready();
  4898. SSLClient cli("127.0.0.1", PORT);
  4899. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4900. cli.enable_server_certificate_verification(true);
  4901. cli.set_connection_timeout(30);
  4902. auto res = cli.Get("/test");
  4903. ASSERT_TRUE(res);
  4904. ASSERT_EQ(StatusCode::OK_200, res->status);
  4905. }
  4906. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4907. std::string cert;
  4908. detail::read_file(CA_CERT_FILE, cert);
  4909. SSLClient cli("google.com");
  4910. cli.load_ca_cert_store(cert.data(), cert.size());
  4911. const auto res = cli.Get("/");
  4912. ASSERT_TRUE(res);
  4913. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4914. }
  4915. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4916. // clang-format off
  4917. static constexpr char cert[] =
  4918. "GlobalSign Root CA\n"
  4919. "==================\n"
  4920. "-----BEGIN CERTIFICATE-----\n"
  4921. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4922. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4923. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4924. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4925. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4926. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4927. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4928. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4929. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4930. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4931. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4932. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4933. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  4934. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  4935. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  4936. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  4937. "-----END CERTIFICATE-----\n";
  4938. // clang-format on
  4939. SSLClient cli("google.com");
  4940. cli.load_ca_cert_store(cert, sizeof(cert));
  4941. const auto res = cli.Get("/");
  4942. ASSERT_TRUE(res);
  4943. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4944. }
  4945. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4946. SSLClient cli("www.youtube.com");
  4947. cli.set_ca_cert_path(CA_CERT_FILE);
  4948. cli.enable_server_certificate_verification(true);
  4949. cli.set_follow_location(true);
  4950. auto res = cli.Get("/");
  4951. ASSERT_TRUE(res);
  4952. ASSERT_EQ(StatusCode::OK_200, res->status);
  4953. }
  4954. #if 0
  4955. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4956. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4957. ASSERT_TRUE(cli != nullptr);
  4958. cli->set_address_family(AF_INET6);
  4959. cli->set_interface("en0");
  4960. auto res = cli->Get("/get");
  4961. ASSERT_TRUE(res);
  4962. ASSERT_EQ(StatusCode::OK_200, res->status);
  4963. }
  4964. #endif
  4965. void ClientCertPresent(
  4966. const std::string &client_cert_file,
  4967. const std::string &client_private_key_file,
  4968. const std::string &client_encrypted_private_key_pass = std::string()) {
  4969. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4970. CLIENT_CA_CERT_DIR);
  4971. ASSERT_TRUE(svr.is_valid());
  4972. svr.Get("/test", [&](const Request &req, Response &res) {
  4973. res.set_content("test", "text/plain");
  4974. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4975. ASSERT_TRUE(peer_cert != nullptr);
  4976. auto subject_name = X509_get_subject_name(peer_cert);
  4977. ASSERT_TRUE(subject_name != nullptr);
  4978. std::string common_name;
  4979. {
  4980. char name[BUFSIZ];
  4981. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4982. name, sizeof(name));
  4983. common_name.assign(name, static_cast<size_t>(name_len));
  4984. }
  4985. EXPECT_EQ("Common Name", common_name);
  4986. X509_free(peer_cert);
  4987. });
  4988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4989. auto se = detail::scope_exit([&] {
  4990. svr.stop();
  4991. t.join();
  4992. ASSERT_FALSE(svr.is_running());
  4993. });
  4994. svr.wait_until_ready();
  4995. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  4996. client_encrypted_private_key_pass);
  4997. cli.enable_server_certificate_verification(false);
  4998. cli.set_connection_timeout(30);
  4999. auto res = cli.Get("/test");
  5000. ASSERT_TRUE(res);
  5001. ASSERT_EQ(StatusCode::OK_200, res->status);
  5002. }
  5003. TEST(SSLClientServerTest, ClientCertPresent) {
  5004. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5005. }
  5006. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5007. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5008. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5009. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5010. }
  5011. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5012. void MemoryClientCertPresent(
  5013. const std::string &client_cert_file,
  5014. const std::string &client_private_key_file,
  5015. const std::string &client_encrypted_private_key_pass = std::string()) {
  5016. auto f = fopen(SERVER_CERT_FILE, "r+");
  5017. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5018. fclose(f);
  5019. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5020. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5021. fclose(f);
  5022. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5023. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5024. auto client_ca_cert_store = X509_STORE_new();
  5025. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5026. X509_free(client_cert);
  5027. fclose(f);
  5028. f = fopen(client_cert_file.c_str(), "r+");
  5029. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5030. fclose(f);
  5031. f = fopen(client_private_key_file.c_str(), "r+");
  5032. auto client_private_key = PEM_read_PrivateKey(
  5033. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5034. fclose(f);
  5035. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5036. ASSERT_TRUE(svr.is_valid());
  5037. svr.Get("/test", [&](const Request &req, Response &res) {
  5038. res.set_content("test", "text/plain");
  5039. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5040. ASSERT_TRUE(peer_cert != nullptr);
  5041. auto subject_name = X509_get_subject_name(peer_cert);
  5042. ASSERT_TRUE(subject_name != nullptr);
  5043. std::string common_name;
  5044. {
  5045. char name[BUFSIZ];
  5046. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5047. name, sizeof(name));
  5048. common_name.assign(name, static_cast<size_t>(name_len));
  5049. }
  5050. EXPECT_EQ("Common Name", common_name);
  5051. X509_free(peer_cert);
  5052. });
  5053. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5054. auto se = detail::scope_exit([&] {
  5055. svr.stop();
  5056. t.join();
  5057. ASSERT_FALSE(svr.is_running());
  5058. });
  5059. svr.wait_until_ready();
  5060. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5061. client_encrypted_private_key_pass);
  5062. cli.enable_server_certificate_verification(false);
  5063. cli.set_connection_timeout(30);
  5064. auto res = cli.Get("/test");
  5065. ASSERT_TRUE(res);
  5066. ASSERT_EQ(StatusCode::OK_200, res->status);
  5067. X509_free(server_cert);
  5068. EVP_PKEY_free(server_private_key);
  5069. X509_free(client_cert);
  5070. EVP_PKEY_free(client_private_key);
  5071. }
  5072. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5073. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5074. }
  5075. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5076. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5077. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5078. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5079. }
  5080. #endif
  5081. TEST(SSLClientServerTest, ClientCertMissing) {
  5082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5083. CLIENT_CA_CERT_DIR);
  5084. ASSERT_TRUE(svr.is_valid());
  5085. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5086. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5087. auto se = detail::scope_exit([&] {
  5088. svr.stop();
  5089. t.join();
  5090. ASSERT_FALSE(svr.is_running());
  5091. });
  5092. svr.wait_until_ready();
  5093. SSLClient cli(HOST, PORT);
  5094. auto res = cli.Get("/test");
  5095. cli.set_connection_timeout(30);
  5096. ASSERT_TRUE(!res);
  5097. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5098. }
  5099. TEST(SSLClientServerTest, TrustDirOptional) {
  5100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5101. ASSERT_TRUE(svr.is_valid());
  5102. svr.Get("/test", [&](const Request &, Response &res) {
  5103. res.set_content("test", "text/plain");
  5104. });
  5105. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5106. auto se = detail::scope_exit([&] {
  5107. svr.stop();
  5108. t.join();
  5109. ASSERT_FALSE(svr.is_running());
  5110. });
  5111. svr.wait_until_ready();
  5112. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5113. cli.enable_server_certificate_verification(false);
  5114. cli.set_connection_timeout(30);
  5115. auto res = cli.Get("/test");
  5116. ASSERT_TRUE(res);
  5117. ASSERT_EQ(StatusCode::OK_200, res->status);
  5118. }
  5119. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5120. class NoListenSSLServer : public SSLServer {
  5121. public:
  5122. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5123. const char *client_ca_cert_file_path,
  5124. const char *client_ca_cert_dir_path = nullptr)
  5125. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5126. client_ca_cert_dir_path),
  5127. stop_(false) {}
  5128. std::atomic_bool stop_;
  5129. private:
  5130. bool process_and_close_socket(socket_t /*sock*/) override {
  5131. // Don't create SSL context
  5132. while (!stop_.load()) {
  5133. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5134. }
  5135. return true;
  5136. }
  5137. };
  5138. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5139. CLIENT_CA_CERT_FILE);
  5140. ASSERT_TRUE(svr.is_valid());
  5141. svr.Get("/test", [&](const Request &, Response &res) {
  5142. res.set_content("test", "text/plain");
  5143. });
  5144. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5145. auto se = detail::scope_exit([&] {
  5146. svr.stop_ = true;
  5147. svr.stop();
  5148. t.join();
  5149. ASSERT_FALSE(svr.is_running());
  5150. });
  5151. svr.wait_until_ready();
  5152. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5153. cli.enable_server_certificate_verification(false);
  5154. cli.set_connection_timeout(1);
  5155. auto res = cli.Get("/test");
  5156. ASSERT_TRUE(!res);
  5157. EXPECT_EQ(Error::SSLConnection, res.error());
  5158. }
  5159. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5160. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5161. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5162. SSL_CTX_set_options(&ssl_ctx,
  5163. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5164. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5165. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5166. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5167. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5168. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5169. "ECDHE-DSS-AES128-SHA256:"
  5170. "ECDHE-RSA-AES256-SHA256:"
  5171. "ECDHE-DSS-AES256-SHA256:";
  5172. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5173. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5174. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5175. SSL_FILETYPE_PEM) != 1) {
  5176. return false;
  5177. }
  5178. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5179. CLIENT_CA_CERT_DIR);
  5180. SSL_CTX_set_verify(
  5181. &ssl_ctx,
  5182. SSL_VERIFY_PEER |
  5183. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5184. nullptr);
  5185. return true;
  5186. };
  5187. SSLServer svr(setup_ssl_ctx_callback);
  5188. ASSERT_TRUE(svr.is_valid());
  5189. svr.Get("/test", [&](const Request &req, Response &res) {
  5190. res.set_content("test", "text/plain");
  5191. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5192. ASSERT_TRUE(peer_cert != nullptr);
  5193. auto subject_name = X509_get_subject_name(peer_cert);
  5194. ASSERT_TRUE(subject_name != nullptr);
  5195. std::string common_name;
  5196. {
  5197. char name[BUFSIZ];
  5198. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5199. name, sizeof(name));
  5200. common_name.assign(name, static_cast<size_t>(name_len));
  5201. }
  5202. EXPECT_EQ("Common Name", common_name);
  5203. X509_free(peer_cert);
  5204. });
  5205. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5206. auto se = detail::scope_exit([&] {
  5207. svr.stop();
  5208. t.join();
  5209. ASSERT_FALSE(svr.is_running());
  5210. });
  5211. svr.wait_until_ready();
  5212. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5213. cli.enable_server_certificate_verification(false);
  5214. cli.set_connection_timeout(30);
  5215. auto res = cli.Get("/test");
  5216. ASSERT_TRUE(res);
  5217. ASSERT_EQ(StatusCode::OK_200, res->status);
  5218. }
  5219. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5220. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5221. // prepare large data
  5222. std::random_device seed_gen;
  5223. std::mt19937 random(seed_gen());
  5224. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5225. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5226. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5227. // server
  5228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5229. ASSERT_TRUE(svr.is_valid());
  5230. svr.Post("/binary", [&](const Request &req, Response &res) {
  5231. EXPECT_EQ(large_size_byte, req.body.size());
  5232. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5233. res.set_content(req.body, "application/octet-stream");
  5234. });
  5235. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5236. auto se = detail::scope_exit([&] {
  5237. svr.stop();
  5238. listen_thread.join();
  5239. ASSERT_FALSE(svr.is_running());
  5240. });
  5241. svr.wait_until_ready();
  5242. // client POST
  5243. SSLClient cli("localhost", PORT);
  5244. cli.enable_server_certificate_verification(false);
  5245. cli.set_read_timeout(std::chrono::seconds(100));
  5246. cli.set_write_timeout(std::chrono::seconds(100));
  5247. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5248. large_size_byte, "application/octet-stream");
  5249. // compare
  5250. EXPECT_EQ(StatusCode::OK_200, res->status);
  5251. EXPECT_EQ(large_size_byte, res->body.size());
  5252. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5253. }
  5254. #endif
  5255. #ifdef _WIN32
  5256. TEST(CleanupTest, WSACleanup) {
  5257. int ret = WSACleanup();
  5258. ASSERT_EQ(0, ret);
  5259. }
  5260. #endif
  5261. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5262. TEST(NoSSLSupport, SimpleInterface) {
  5263. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5264. }
  5265. #endif
  5266. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5267. TEST(InvalidScheme, SimpleInterface) {
  5268. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5269. }
  5270. #endif
  5271. TEST(NoScheme, SimpleInterface) {
  5272. Client cli("yahoo.com:80");
  5273. ASSERT_TRUE(cli.is_valid());
  5274. }
  5275. TEST(SendAPI, SimpleInterface_Online) {
  5276. Client cli("http://yahoo.com");
  5277. Request req;
  5278. req.method = "GET";
  5279. req.path = "/";
  5280. auto res = cli.send(req);
  5281. ASSERT_TRUE(res);
  5282. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5283. }
  5284. TEST(ClientImplMethods, GetSocketTest) {
  5285. httplib::Server svr;
  5286. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5287. res.status = StatusCode::OK_200;
  5288. });
  5289. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5290. auto se = detail::scope_exit([&] {
  5291. svr.stop();
  5292. thread.join();
  5293. ASSERT_FALSE(svr.is_running());
  5294. });
  5295. svr.wait_until_ready();
  5296. {
  5297. httplib::Client cli("http://127.0.0.1:3333");
  5298. cli.set_keep_alive(true);
  5299. // Use the behavior of cpp-httplib of opening the connection
  5300. // only when the first request happens. If that changes,
  5301. // this test would be obsolete.
  5302. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5303. // This also implicitly tests the server. But other tests would fail much
  5304. // earlier than this one to be considered.
  5305. auto res = cli.Get("/");
  5306. ASSERT_TRUE(res);
  5307. EXPECT_EQ(StatusCode::OK_200, res->status);
  5308. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5309. }
  5310. }
  5311. // Disabled due to out-of-memory problem on GitHub Actions
  5312. #ifdef _WIN64
  5313. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5314. // allocate content size larger than 2GB in memory
  5315. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5316. char *content = (char *)malloc(content_size);
  5317. ASSERT_TRUE(content);
  5318. Server svr;
  5319. svr.Get("/foo",
  5320. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5321. res.set_content(content, content_size, "application/octet-stream");
  5322. });
  5323. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5324. auto se = detail::scope_exit([&] {
  5325. svr.stop();
  5326. listen_thread.join();
  5327. if (content) free(content);
  5328. ASSERT_FALSE(svr.is_running());
  5329. });
  5330. svr.wait_until_ready();
  5331. Client cli(HOST, PORT);
  5332. auto res = cli.Get("/foo");
  5333. ASSERT_TRUE(res);
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ(content_size, res->body.length());
  5336. }
  5337. #endif
  5338. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5339. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5340. Client cli("http://yahoo.com");
  5341. auto res = cli.Get("/");
  5342. ASSERT_TRUE(res);
  5343. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5344. cli.set_follow_location(true);
  5345. res = cli.Get("/");
  5346. ASSERT_TRUE(res);
  5347. EXPECT_EQ(StatusCode::OK_200, res->status);
  5348. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5349. }
  5350. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5351. Client cli("https://yahoo.com");
  5352. auto res = cli.Get("/");
  5353. ASSERT_TRUE(res);
  5354. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5355. cli.set_follow_location(true);
  5356. res = cli.Get("/");
  5357. ASSERT_TRUE(res);
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5360. }
  5361. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5362. Client cli("https://yahoo.com");
  5363. auto res = cli.Get("/");
  5364. ASSERT_TRUE(res);
  5365. ASSERT_FALSE(!res);
  5366. ASSERT_TRUE(res);
  5367. ASSERT_FALSE(res == nullptr);
  5368. ASSERT_TRUE(res != nullptr);
  5369. EXPECT_EQ(Error::Success, res.error());
  5370. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5371. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5372. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5373. cli.set_follow_location(true);
  5374. res = cli.Get("/");
  5375. ASSERT_TRUE(res);
  5376. EXPECT_EQ(Error::Success, res.error());
  5377. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5378. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5379. EXPECT_EQ(StatusCode::OK_200, res->status);
  5380. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5381. }
  5382. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5383. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5384. Client cli("https://cdnjs.cloudflare.com");
  5385. auto res =
  5386. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(StatusCode::OK_200, res->status);
  5389. EXPECT_EQ(287630U, res->body.size());
  5390. EXPECT_EQ("application/javascript; charset=utf-8",
  5391. res->get_header_value("Content-Type"));
  5392. }
  5393. #endif
  5394. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5395. Client cli("https://nghttp2.org");
  5396. cli.set_follow_location(true);
  5397. auto res =
  5398. cli.Get("/httpbin/"
  5399. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5400. ASSERT_TRUE(res);
  5401. EXPECT_EQ(StatusCode::OK_200, res->status);
  5402. }
  5403. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5404. Client cli("https://nghttp2.org");
  5405. cli.set_follow_location(true);
  5406. Params params;
  5407. params.emplace("url", "http://www.google.com");
  5408. params.emplace("status_code", "302");
  5409. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5410. ASSERT_TRUE(res);
  5411. EXPECT_EQ(StatusCode::OK_200, res->status);
  5412. }
  5413. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5414. Client cli("https://nghttp2.org");
  5415. cli.set_follow_location(true);
  5416. Params params;
  5417. params.emplace("url", "http://www.google.com");
  5418. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. }
  5422. TEST(HttpToHttpsRedirectTest, CertFile) {
  5423. Server svr;
  5424. ASSERT_TRUE(svr.is_valid());
  5425. svr.Get("/index", [&](const Request &, Response &res) {
  5426. res.set_redirect("https://127.0.0.1:1235/index");
  5427. svr.stop();
  5428. });
  5429. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5430. ASSERT_TRUE(ssl_svr.is_valid());
  5431. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5432. res.set_content("test", "text/plain");
  5433. ssl_svr.stop();
  5434. });
  5435. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5436. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5437. auto se = detail::scope_exit([&] {
  5438. t2.join();
  5439. t.join();
  5440. ASSERT_FALSE(svr.is_running());
  5441. });
  5442. svr.wait_until_ready();
  5443. ssl_svr.wait_until_ready();
  5444. Client cli("127.0.0.1", PORT);
  5445. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5446. cli.enable_server_certificate_verification(true);
  5447. cli.set_follow_location(true);
  5448. cli.set_connection_timeout(30);
  5449. auto res = cli.Get("/index");
  5450. ASSERT_TRUE(res);
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. }
  5453. TEST(MultipartFormDataTest, LargeData) {
  5454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5455. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5456. const ContentReader &content_reader) {
  5457. if (req.is_multipart_form_data()) {
  5458. MultipartFormDataItems files;
  5459. content_reader(
  5460. [&](const MultipartFormData &file) {
  5461. files.push_back(file);
  5462. return true;
  5463. },
  5464. [&](const char *data, size_t data_length) {
  5465. files.back().content.append(data, data_length);
  5466. return true;
  5467. });
  5468. EXPECT_TRUE(std::string(files[0].name) == "document");
  5469. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5470. EXPECT_TRUE(files[0].filename == "2MB_data");
  5471. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5472. EXPECT_TRUE(files[1].name == "hello");
  5473. EXPECT_TRUE(files[1].content == "world");
  5474. EXPECT_TRUE(files[1].filename == "");
  5475. EXPECT_TRUE(files[1].content_type == "");
  5476. } else {
  5477. std::string body;
  5478. content_reader([&](const char *data, size_t data_length) {
  5479. body.append(data, data_length);
  5480. return true;
  5481. });
  5482. }
  5483. });
  5484. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5485. auto se = detail::scope_exit([&] {
  5486. svr.stop();
  5487. t.join();
  5488. ASSERT_FALSE(svr.is_running());
  5489. });
  5490. svr.wait_until_ready();
  5491. {
  5492. std::string data(1024 * 1024 * 2, '.');
  5493. std::stringstream buffer;
  5494. buffer << data;
  5495. Client cli("https://localhost:8080");
  5496. cli.enable_server_certificate_verification(false);
  5497. MultipartFormDataItems items{
  5498. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5499. {"hello", "world", "", ""},
  5500. };
  5501. auto res = cli.Post("/post", items);
  5502. ASSERT_TRUE(res);
  5503. ASSERT_EQ(StatusCode::OK_200, res->status);
  5504. }
  5505. }
  5506. TEST(MultipartFormDataTest, DataProviderItems) {
  5507. std::random_device seed_gen;
  5508. std::mt19937 random(seed_gen());
  5509. std::string rand1;
  5510. rand1.resize(1000);
  5511. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5512. std::string rand2;
  5513. rand2.resize(3000);
  5514. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5516. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5517. const ContentReader &content_reader) {
  5518. ASSERT_FALSE(req.is_multipart_form_data());
  5519. std::string body;
  5520. content_reader([&](const char *data, size_t data_length) {
  5521. body.append(data, data_length);
  5522. return true;
  5523. });
  5524. EXPECT_EQ(body, "");
  5525. });
  5526. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5527. const ContentReader &content_reader) {
  5528. ASSERT_TRUE(req.is_multipart_form_data());
  5529. MultipartFormDataItems files;
  5530. content_reader(
  5531. [&](const MultipartFormData &file) {
  5532. files.push_back(file);
  5533. return true;
  5534. },
  5535. [&](const char *data, size_t data_length) {
  5536. files.back().content.append(data, data_length);
  5537. return true;
  5538. });
  5539. ASSERT_TRUE(files.size() == 2);
  5540. EXPECT_EQ(std::string(files[0].name), "name1");
  5541. EXPECT_EQ(files[0].content, "Testing123");
  5542. EXPECT_EQ(files[0].filename, "filename1");
  5543. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5544. EXPECT_EQ(files[1].name, "name2");
  5545. EXPECT_EQ(files[1].content, "Testing456");
  5546. EXPECT_EQ(files[1].filename, "");
  5547. EXPECT_EQ(files[1].content_type, "");
  5548. });
  5549. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5550. const ContentReader &content_reader) {
  5551. ASSERT_TRUE(req.is_multipart_form_data());
  5552. MultipartFormDataItems files;
  5553. content_reader(
  5554. [&](const MultipartFormData &file) {
  5555. files.push_back(file);
  5556. return true;
  5557. },
  5558. [&](const char *data, size_t data_length) {
  5559. files.back().content.append(data, data_length);
  5560. return true;
  5561. });
  5562. ASSERT_TRUE(files.size() == 2);
  5563. EXPECT_EQ(files[0].name, "name3");
  5564. EXPECT_EQ(files[0].content, rand1);
  5565. EXPECT_EQ(files[0].filename, "filename3");
  5566. EXPECT_EQ(files[0].content_type, "");
  5567. EXPECT_EQ(files[1].name, "name4");
  5568. EXPECT_EQ(files[1].content, rand2);
  5569. EXPECT_EQ(files[1].filename, "filename4");
  5570. EXPECT_EQ(files[1].content_type, "");
  5571. });
  5572. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5573. const ContentReader &content_reader) {
  5574. ASSERT_TRUE(req.is_multipart_form_data());
  5575. MultipartFormDataItems files;
  5576. content_reader(
  5577. [&](const MultipartFormData &file) {
  5578. files.push_back(file);
  5579. return true;
  5580. },
  5581. [&](const char *data, size_t data_length) {
  5582. files.back().content.append(data, data_length);
  5583. return true;
  5584. });
  5585. ASSERT_TRUE(files.size() == 4);
  5586. EXPECT_EQ(std::string(files[0].name), "name1");
  5587. EXPECT_EQ(files[0].content, "Testing123");
  5588. EXPECT_EQ(files[0].filename, "filename1");
  5589. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5590. EXPECT_EQ(files[1].name, "name2");
  5591. EXPECT_EQ(files[1].content, "Testing456");
  5592. EXPECT_EQ(files[1].filename, "");
  5593. EXPECT_EQ(files[1].content_type, "");
  5594. EXPECT_EQ(files[2].name, "name3");
  5595. EXPECT_EQ(files[2].content, rand1);
  5596. EXPECT_EQ(files[2].filename, "filename3");
  5597. EXPECT_EQ(files[2].content_type, "");
  5598. EXPECT_EQ(files[3].name, "name4");
  5599. EXPECT_EQ(files[3].content, rand2);
  5600. EXPECT_EQ(files[3].filename, "filename4");
  5601. EXPECT_EQ(files[3].content_type, "");
  5602. });
  5603. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5604. auto se = detail::scope_exit([&] {
  5605. svr.stop();
  5606. t.join();
  5607. ASSERT_FALSE(svr.is_running());
  5608. });
  5609. svr.wait_until_ready();
  5610. {
  5611. Client cli("https://localhost:8080");
  5612. cli.enable_server_certificate_verification(false);
  5613. MultipartFormDataItems items{
  5614. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5615. {"name2", "Testing456", "", ""}, // not a file
  5616. };
  5617. {
  5618. auto res = cli.Post("/post-none", {}, {}, {});
  5619. ASSERT_TRUE(res);
  5620. ASSERT_EQ(StatusCode::OK_200, res->status);
  5621. }
  5622. MultipartFormDataProviderItems providers;
  5623. {
  5624. auto res =
  5625. cli.Post("/post-items", {}, items, providers); // empty providers
  5626. ASSERT_TRUE(res);
  5627. ASSERT_EQ(StatusCode::OK_200, res->status);
  5628. }
  5629. providers.push_back({"name3",
  5630. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5631. // test the offset is given correctly at each step
  5632. if (!offset)
  5633. sink.os.write(rand1.data(), 30);
  5634. else if (offset == 30)
  5635. sink.os.write(rand1.data() + 30, 300);
  5636. else if (offset == 330)
  5637. sink.os.write(rand1.data() + 330, 670);
  5638. else if (offset == rand1.size())
  5639. sink.done();
  5640. return true;
  5641. },
  5642. "filename3",
  5643. {}});
  5644. providers.push_back({"name4",
  5645. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5646. // test the offset is given correctly at each step
  5647. if (!offset)
  5648. sink.os.write(rand2.data(), 2000);
  5649. else if (offset == 2000)
  5650. sink.os.write(rand2.data() + 2000, 1);
  5651. else if (offset == 2001)
  5652. sink.os.write(rand2.data() + 2001, 999);
  5653. else if (offset == rand2.size())
  5654. sink.done();
  5655. return true;
  5656. },
  5657. "filename4",
  5658. {}});
  5659. {
  5660. auto res = cli.Post("/post-providers", {}, {}, providers);
  5661. ASSERT_TRUE(res);
  5662. ASSERT_EQ(StatusCode::OK_200, res->status);
  5663. }
  5664. {
  5665. auto res = cli.Post("/post-both", {}, items, providers);
  5666. ASSERT_TRUE(res);
  5667. ASSERT_EQ(StatusCode::OK_200, res->status);
  5668. }
  5669. }
  5670. }
  5671. TEST(MultipartFormDataTest, BadHeader) {
  5672. Server svr;
  5673. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5674. res.set_content("ok", "text/plain");
  5675. });
  5676. thread t = thread([&] { svr.listen(HOST, PORT); });
  5677. auto se = detail::scope_exit([&] {
  5678. svr.stop();
  5679. t.join();
  5680. ASSERT_FALSE(svr.is_running());
  5681. });
  5682. svr.wait_until_ready();
  5683. const std::string body =
  5684. "This is the preamble. It is to be ignored, though it\r\n"
  5685. "is a handy place for composition agents to include an\r\n"
  5686. "explanatory note to non-MIME conformant readers.\r\n"
  5687. "\r\n"
  5688. "\r\n"
  5689. "--simple boundary\r\n"
  5690. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5691. ": BAD...\r\n"
  5692. "\r\n"
  5693. "value1\r\n"
  5694. "--simple boundary\r\n"
  5695. "Content-Disposition: form-data; name=\"field2\"; "
  5696. "filename=\"example.txt\"\r\n"
  5697. "\r\n"
  5698. "value2\r\n"
  5699. "--simple boundary--\r\n"
  5700. "This is the epilogue. It is also to be ignored.\r\n";
  5701. std::string content_type =
  5702. R"(multipart/form-data; boundary="simple boundary")";
  5703. Client cli(HOST, PORT);
  5704. auto res = cli.Post("/post", body, content_type.c_str());
  5705. ASSERT_TRUE(res);
  5706. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5707. }
  5708. TEST(MultipartFormDataTest, WithPreamble) {
  5709. Server svr;
  5710. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5711. res.set_content("ok", "text/plain");
  5712. });
  5713. thread t = thread([&] { svr.listen(HOST, PORT); });
  5714. auto se = detail::scope_exit([&] {
  5715. svr.stop();
  5716. t.join();
  5717. ASSERT_FALSE(svr.is_running());
  5718. });
  5719. svr.wait_until_ready();
  5720. const std::string body =
  5721. "This is the preamble. It is to be ignored, though it\r\n"
  5722. "is a handy place for composition agents to include an\r\n"
  5723. "explanatory note to non-MIME conformant readers.\r\n"
  5724. "\r\n"
  5725. "\r\n"
  5726. "--simple boundary\r\n"
  5727. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5728. "\r\n"
  5729. "value1\r\n"
  5730. "--simple boundary\r\n"
  5731. "Content-Disposition: form-data; name=\"field2\"; "
  5732. "filename=\"example.txt\"\r\n"
  5733. "\r\n"
  5734. "value2\r\n"
  5735. "--simple boundary--\r\n"
  5736. "This is the epilogue. It is also to be ignored.\r\n";
  5737. std::string content_type =
  5738. R"(multipart/form-data; boundary="simple boundary")";
  5739. Client cli(HOST, PORT);
  5740. auto res = cli.Post("/post", body, content_type.c_str());
  5741. ASSERT_TRUE(res);
  5742. EXPECT_EQ(StatusCode::OK_200, res->status);
  5743. }
  5744. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5746. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5747. const ContentReader &content_reader) {
  5748. if (req.is_multipart_form_data()) {
  5749. MultipartFormDataItems files;
  5750. content_reader(
  5751. [&](const MultipartFormData &file) {
  5752. files.push_back(file);
  5753. return true;
  5754. },
  5755. [&](const char *data, size_t data_length) {
  5756. files.back().content.append(data, data_length);
  5757. return true;
  5758. });
  5759. EXPECT_TRUE(std::string(files[0].name) == "document");
  5760. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5761. EXPECT_TRUE(files[0].filename == "2MB_data");
  5762. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5763. EXPECT_TRUE(files[1].name == "hello");
  5764. EXPECT_TRUE(files[1].content == "world");
  5765. EXPECT_TRUE(files[1].filename == "");
  5766. EXPECT_TRUE(files[1].content_type == "");
  5767. } else {
  5768. std::string body;
  5769. content_reader([&](const char *data, size_t data_length) {
  5770. body.append(data, data_length);
  5771. return true;
  5772. });
  5773. }
  5774. });
  5775. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5776. auto se = detail::scope_exit([&] {
  5777. svr.stop();
  5778. t.join();
  5779. ASSERT_FALSE(svr.is_running());
  5780. });
  5781. svr.wait_until_ready();
  5782. {
  5783. std::string data(1024 * 1024 * 2, '.');
  5784. std::stringstream buffer;
  5785. buffer << data;
  5786. Client cli("https://localhost:8080");
  5787. cli.enable_server_certificate_verification(false);
  5788. MultipartFormDataItems items{
  5789. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5790. {"hello", "world", "", ""},
  5791. };
  5792. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5793. ASSERT_TRUE(res);
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. }
  5796. }
  5797. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5798. std::string data(1024 * 1024 * 2, '&');
  5799. std::stringstream buffer;
  5800. buffer << data;
  5801. Client cli("https://localhost:8080");
  5802. MultipartFormDataItems items{
  5803. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5804. {"hello", "world", "", ""},
  5805. };
  5806. for (const char &c : " \t\r\n") {
  5807. auto res =
  5808. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5809. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5810. ASSERT_FALSE(res);
  5811. }
  5812. }
  5813. TEST(MultipartFormDataTest, PutFormData) {
  5814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5815. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5816. const ContentReader &content_reader) {
  5817. if (req.is_multipart_form_data()) {
  5818. MultipartFormDataItems files;
  5819. content_reader(
  5820. [&](const MultipartFormData &file) {
  5821. files.push_back(file);
  5822. return true;
  5823. },
  5824. [&](const char *data, size_t data_length) {
  5825. files.back().content.append(data, data_length);
  5826. return true;
  5827. });
  5828. EXPECT_TRUE(std::string(files[0].name) == "document");
  5829. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5830. EXPECT_TRUE(files[0].filename == "2MB_data");
  5831. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5832. EXPECT_TRUE(files[1].name == "hello");
  5833. EXPECT_TRUE(files[1].content == "world");
  5834. EXPECT_TRUE(files[1].filename == "");
  5835. EXPECT_TRUE(files[1].content_type == "");
  5836. } else {
  5837. std::string body;
  5838. content_reader([&](const char *data, size_t data_length) {
  5839. body.append(data, data_length);
  5840. return true;
  5841. });
  5842. }
  5843. });
  5844. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5845. auto se = detail::scope_exit([&] {
  5846. svr.stop();
  5847. t.join();
  5848. ASSERT_FALSE(svr.is_running());
  5849. });
  5850. svr.wait_until_ready();
  5851. {
  5852. std::string data(1024 * 1024 * 2, '&');
  5853. std::stringstream buffer;
  5854. buffer << data;
  5855. Client cli("https://localhost:8080");
  5856. cli.enable_server_certificate_verification(false);
  5857. MultipartFormDataItems items{
  5858. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5859. {"hello", "world", "", ""},
  5860. };
  5861. auto res = cli.Put("/put", items);
  5862. ASSERT_TRUE(res);
  5863. ASSERT_EQ(StatusCode::OK_200, res->status);
  5864. }
  5865. }
  5866. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5868. svr.Put("/put_customboundary",
  5869. [&](const Request &req, const Response & /*res*/,
  5870. const ContentReader &content_reader) {
  5871. if (req.is_multipart_form_data()) {
  5872. MultipartFormDataItems files;
  5873. content_reader(
  5874. [&](const MultipartFormData &file) {
  5875. files.push_back(file);
  5876. return true;
  5877. },
  5878. [&](const char *data, size_t data_length) {
  5879. files.back().content.append(data, data_length);
  5880. return true;
  5881. });
  5882. EXPECT_TRUE(std::string(files[0].name) == "document");
  5883. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5884. EXPECT_TRUE(files[0].filename == "2MB_data");
  5885. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5886. EXPECT_TRUE(files[1].name == "hello");
  5887. EXPECT_TRUE(files[1].content == "world");
  5888. EXPECT_TRUE(files[1].filename == "");
  5889. EXPECT_TRUE(files[1].content_type == "");
  5890. } else {
  5891. std::string body;
  5892. content_reader([&](const char *data, size_t data_length) {
  5893. body.append(data, data_length);
  5894. return true;
  5895. });
  5896. }
  5897. });
  5898. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5899. auto se = detail::scope_exit([&] {
  5900. svr.stop();
  5901. t.join();
  5902. ASSERT_FALSE(svr.is_running());
  5903. });
  5904. svr.wait_until_ready();
  5905. {
  5906. std::string data(1024 * 1024 * 2, '&');
  5907. std::stringstream buffer;
  5908. buffer << data;
  5909. Client cli("https://localhost:8080");
  5910. cli.enable_server_certificate_verification(false);
  5911. MultipartFormDataItems items{
  5912. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5913. {"hello", "world", "", ""},
  5914. };
  5915. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5916. ASSERT_TRUE(res);
  5917. ASSERT_EQ(StatusCode::OK_200, res->status);
  5918. }
  5919. }
  5920. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5921. std::string data(1024 * 1024 * 2, '&');
  5922. std::stringstream buffer;
  5923. buffer << data;
  5924. Client cli("https://localhost:8080");
  5925. cli.enable_server_certificate_verification(false);
  5926. MultipartFormDataItems items{
  5927. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5928. {"hello", "world", "", ""},
  5929. };
  5930. for (const char &c : " \t\r\n") {
  5931. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5932. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5933. ASSERT_FALSE(res);
  5934. }
  5935. }
  5936. TEST(MultipartFormDataTest, AlternateFilename) {
  5937. auto handled = false;
  5938. Server svr;
  5939. svr.Post("/test", [&](const Request &req, Response &res) {
  5940. ASSERT_EQ(3u, req.files.size());
  5941. auto it = req.files.begin();
  5942. ASSERT_EQ("file1", it->second.name);
  5943. ASSERT_EQ("A.txt", it->second.filename);
  5944. ASSERT_EQ("text/plain", it->second.content_type);
  5945. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  5946. ++it;
  5947. ASSERT_EQ("file2", it->second.name);
  5948. ASSERT_EQ("a.html", it->second.filename);
  5949. ASSERT_EQ("text/html", it->second.content_type);
  5950. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  5951. it->second.content);
  5952. ++it;
  5953. ASSERT_EQ("text", it->second.name);
  5954. ASSERT_EQ("", it->second.filename);
  5955. ASSERT_EQ("", it->second.content_type);
  5956. ASSERT_EQ("text default", it->second.content);
  5957. res.set_content("ok", "text/plain");
  5958. handled = true;
  5959. });
  5960. thread t = thread([&] { svr.listen(HOST, PORT); });
  5961. auto se = detail::scope_exit([&] {
  5962. svr.stop();
  5963. t.join();
  5964. ASSERT_FALSE(svr.is_running());
  5965. ASSERT_TRUE(handled);
  5966. });
  5967. svr.wait_until_ready();
  5968. auto req = "POST /test HTTP/1.1\r\n"
  5969. "Content-Type: multipart/form-data;boundary=--------\r\n"
  5970. "Content-Length: 399\r\n"
  5971. "\r\n"
  5972. "----------\r\n"
  5973. "Content-Disposition: form-data; name=\"text\"\r\n"
  5974. "\r\n"
  5975. "text default\r\n"
  5976. "----------\r\n"
  5977. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  5978. "filename=\"a.txt\"; name=\"file1\"\r\n"
  5979. "Content-Type: text/plain\r\n"
  5980. "\r\n"
  5981. "Content of a.txt.\r\n"
  5982. "\r\n"
  5983. "----------\r\n"
  5984. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  5985. "\"a.html\"\r\n"
  5986. "Content-Type: text/html\r\n"
  5987. "\r\n"
  5988. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  5989. "\r\n"
  5990. "------------\r\n";
  5991. ASSERT_TRUE(send_request(1, req));
  5992. }
  5993. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  5994. auto handled = false;
  5995. Server svr;
  5996. svr.Post("/test", [&](const Request &req, Response &) {
  5997. ASSERT_EQ(2u, req.files.size());
  5998. auto it = req.files.begin();
  5999. ASSERT_EQ("text1", it->second.name);
  6000. ASSERT_EQ("text1", it->second.content);
  6001. ++it;
  6002. ASSERT_EQ("text2", it->second.name);
  6003. ASSERT_EQ("text2", it->second.content);
  6004. handled = true;
  6005. });
  6006. thread t = thread([&] { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. ASSERT_FALSE(svr.is_running());
  6011. ASSERT_TRUE(handled);
  6012. });
  6013. svr.wait_until_ready();
  6014. auto req = "POST /test HTTP/1.1\r\n"
  6015. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6016. "Content-Length: 146\r\n"
  6017. "\r\n----------\r\n"
  6018. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6019. "\r\n"
  6020. "text1"
  6021. "\r\n----------\r\n"
  6022. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6023. "\r\n"
  6024. "text2"
  6025. "\r\n------------";
  6026. std::string resonse;
  6027. ASSERT_TRUE(send_request(1, req, &resonse));
  6028. ASSERT_EQ("200", resonse.substr(9, 3));
  6029. }
  6030. TEST(MultipartFormDataTest, ContentLength) {
  6031. auto handled = false;
  6032. Server svr;
  6033. svr.Post("/test", [&](const Request &req, Response &) {
  6034. ASSERT_EQ(2u, req.files.size());
  6035. auto it = req.files.begin();
  6036. ASSERT_EQ("text1", it->second.name);
  6037. ASSERT_EQ("text1", it->second.content);
  6038. ++it;
  6039. ASSERT_EQ("text2", it->second.name);
  6040. ASSERT_EQ("text2", it->second.content);
  6041. handled = true;
  6042. });
  6043. thread t = thread([&] { svr.listen(HOST, PORT); });
  6044. auto se = detail::scope_exit([&] {
  6045. svr.stop();
  6046. t.join();
  6047. ASSERT_FALSE(svr.is_running());
  6048. ASSERT_TRUE(handled);
  6049. });
  6050. svr.wait_until_ready();
  6051. auto req = "POST /test HTTP/1.1\r\n"
  6052. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6053. "Content-Length: 167\r\n"
  6054. "\r\n----------\r\n"
  6055. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6056. "Content-Length: 5\r\n"
  6057. "\r\n"
  6058. "text1"
  6059. "\r\n----------\r\n"
  6060. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6061. "\r\n"
  6062. "text2"
  6063. "\r\n------------\r\n";
  6064. std::string resonse;
  6065. ASSERT_TRUE(send_request(1, req, &resonse));
  6066. ASSERT_EQ("200", resonse.substr(9, 3));
  6067. }
  6068. #endif
  6069. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6070. static constexpr unsigned int number_of_tasks{1000000};
  6071. std::atomic_uint count{0};
  6072. std::unique_ptr<TaskQueue> task_queue{
  6073. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6074. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6075. auto queued = task_queue->enqueue(
  6076. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6077. EXPECT_TRUE(queued);
  6078. }
  6079. EXPECT_NO_THROW(task_queue->shutdown());
  6080. EXPECT_EQ(number_of_tasks, count.load());
  6081. }
  6082. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6083. static constexpr unsigned int number_of_tasks{1000000};
  6084. static constexpr unsigned int qlimit{2};
  6085. unsigned int queued_count{0};
  6086. std::atomic_uint count{0};
  6087. std::unique_ptr<TaskQueue> task_queue{
  6088. new ThreadPool{/*num_threads=*/1, qlimit}};
  6089. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6090. if (task_queue->enqueue(
  6091. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6092. queued_count++;
  6093. }
  6094. }
  6095. EXPECT_NO_THROW(task_queue->shutdown());
  6096. EXPECT_EQ(queued_count, count.load());
  6097. EXPECT_TRUE(queued_count <= number_of_tasks);
  6098. EXPECT_TRUE(queued_count >= qlimit);
  6099. }
  6100. TEST(TaskQueueTest, MaxQueuedRequests) {
  6101. static constexpr unsigned int qlimit{3};
  6102. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6103. std::condition_variable sem_cv;
  6104. std::mutex sem_mtx;
  6105. int credits = 0;
  6106. bool queued;
  6107. /* Fill up the queue with tasks that will block until we give them credits to
  6108. * complete. */
  6109. for (unsigned int n = 0; n <= qlimit;) {
  6110. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6111. std::unique_lock<std::mutex> lock(sem_mtx);
  6112. while (credits <= 0) {
  6113. sem_cv.wait(lock);
  6114. }
  6115. /* Consume the credit and signal the test code if they are all gone. */
  6116. if (--credits == 0) { sem_cv.notify_one(); }
  6117. });
  6118. if (n < qlimit) {
  6119. /* The first qlimit enqueues must succeed. */
  6120. EXPECT_TRUE(queued);
  6121. } else {
  6122. /* The last one will succeed only when the worker thread
  6123. * starts and dequeues the first blocking task. Although
  6124. * not necessary for the correctness of this test, we sleep for
  6125. * a short while to avoid busy waiting. */
  6126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6127. }
  6128. if (queued) { n++; }
  6129. }
  6130. /* Further enqueues must fail since the queue is full. */
  6131. for (auto i = 0; i < 4; i++) {
  6132. queued = task_queue->enqueue([] {});
  6133. EXPECT_FALSE(queued);
  6134. }
  6135. /* Give the credits to allow the previous tasks to complete. */
  6136. {
  6137. std::unique_lock<std::mutex> lock(sem_mtx);
  6138. credits += qlimit + 1;
  6139. }
  6140. sem_cv.notify_all();
  6141. /* Wait for all the credits to be consumed. */
  6142. {
  6143. std::unique_lock<std::mutex> lock(sem_mtx);
  6144. while (credits > 0) {
  6145. sem_cv.wait(lock);
  6146. }
  6147. }
  6148. /* Check that we are able again to enqueue at least qlimit tasks. */
  6149. for (unsigned int i = 0; i < qlimit; i++) {
  6150. queued = task_queue->enqueue([] {});
  6151. EXPECT_TRUE(queued);
  6152. }
  6153. EXPECT_NO_THROW(task_queue->shutdown());
  6154. }
  6155. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6156. Server svr;
  6157. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6158. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6159. });
  6160. svr.Get("/hello", [](const Request &req, Response &res) {
  6161. res.set_content(req.get_param_value("key"), "text/plain");
  6162. });
  6163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6164. auto se = detail::scope_exit([&] {
  6165. svr.stop();
  6166. thread.join();
  6167. ASSERT_FALSE(svr.is_running());
  6168. });
  6169. svr.wait_until_ready();
  6170. {
  6171. Client cli(HOST, PORT);
  6172. cli.set_follow_location(true);
  6173. auto res = cli.Get("/");
  6174. ASSERT_TRUE(res);
  6175. EXPECT_EQ(StatusCode::OK_200, res->status);
  6176. EXPECT_EQ("val&key2=val2", res->body);
  6177. }
  6178. }
  6179. TEST(VulnerabilityTest, CRLFInjection) {
  6180. Server svr;
  6181. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6182. res.set_content("Hello 1", "text/plain");
  6183. });
  6184. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6185. res.set_content("Hello 2", "text/plain");
  6186. });
  6187. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6188. res.set_content("Hello 3", "text/plain");
  6189. });
  6190. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6191. res.set_content("Hello 4", "text/plain");
  6192. });
  6193. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6194. for (const auto &x : req.headers) {
  6195. auto key = x.first;
  6196. EXPECT_STRNE("evil", key.c_str());
  6197. }
  6198. });
  6199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6200. auto se = detail::scope_exit([&] {
  6201. svr.stop();
  6202. thread.join();
  6203. ASSERT_FALSE(svr.is_running());
  6204. });
  6205. svr.wait_until_ready();
  6206. {
  6207. Client cli(HOST, PORT);
  6208. cli.Post("/test1", "A=B",
  6209. "application/x-www-form-urlencoded\r\nevil: hello1");
  6210. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6211. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6212. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6213. }
  6214. }
  6215. TEST(PathParamsTest, StaticMatch) {
  6216. const auto pattern = "/users/all";
  6217. detail::PathParamsMatcher matcher(pattern);
  6218. Request request;
  6219. request.path = "/users/all";
  6220. ASSERT_TRUE(matcher.match(request));
  6221. std::unordered_map<std::string, std::string> expected_params = {};
  6222. EXPECT_EQ(request.path_params, expected_params);
  6223. }
  6224. TEST(PathParamsTest, StaticMismatch) {
  6225. const auto pattern = "/users/all";
  6226. detail::PathParamsMatcher matcher(pattern);
  6227. Request request;
  6228. request.path = "/users/1";
  6229. ASSERT_FALSE(matcher.match(request));
  6230. }
  6231. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6232. const auto pattern = "/users/:id/subscriptions";
  6233. detail::PathParamsMatcher matcher(pattern);
  6234. Request request;
  6235. request.path = "/users/42/subscriptions";
  6236. ASSERT_TRUE(matcher.match(request));
  6237. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6238. EXPECT_EQ(request.path_params, expected_params);
  6239. }
  6240. TEST(PathParamsTest, SingleParamInTheEnd) {
  6241. const auto pattern = "/users/:id";
  6242. detail::PathParamsMatcher matcher(pattern);
  6243. Request request;
  6244. request.path = "/users/24";
  6245. ASSERT_TRUE(matcher.match(request));
  6246. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6247. EXPECT_EQ(request.path_params, expected_params);
  6248. }
  6249. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6250. const auto pattern = "/users/:id/";
  6251. detail::PathParamsMatcher matcher(pattern);
  6252. Request request;
  6253. request.path = "/users/42/";
  6254. ASSERT_TRUE(matcher.match(request));
  6255. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6256. EXPECT_EQ(request.path_params, expected_params);
  6257. }
  6258. TEST(PathParamsTest, EmptyParam) {
  6259. const auto pattern = "/users/:id/";
  6260. detail::PathParamsMatcher matcher(pattern);
  6261. Request request;
  6262. request.path = "/users//";
  6263. ASSERT_TRUE(matcher.match(request));
  6264. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6265. EXPECT_EQ(request.path_params, expected_params);
  6266. }
  6267. TEST(PathParamsTest, FragmentMismatch) {
  6268. const auto pattern = "/users/:id/";
  6269. detail::PathParamsMatcher matcher(pattern);
  6270. Request request;
  6271. request.path = "/admins/24/";
  6272. ASSERT_FALSE(matcher.match(request));
  6273. }
  6274. TEST(PathParamsTest, ExtraFragments) {
  6275. const auto pattern = "/users/:id";
  6276. detail::PathParamsMatcher matcher(pattern);
  6277. Request request;
  6278. request.path = "/users/42/subscriptions";
  6279. ASSERT_FALSE(matcher.match(request));
  6280. }
  6281. TEST(PathParamsTest, MissingTrailingParam) {
  6282. const auto pattern = "/users/:id";
  6283. detail::PathParamsMatcher matcher(pattern);
  6284. Request request;
  6285. request.path = "/users";
  6286. ASSERT_FALSE(matcher.match(request));
  6287. }
  6288. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6289. const auto pattern = "/users/:id/subscriptions";
  6290. detail::PathParamsMatcher matcher(pattern);
  6291. Request request;
  6292. request.path = "/users/subscriptions";
  6293. ASSERT_FALSE(matcher.match(request));
  6294. }
  6295. TEST(PathParamsTest, MultipleParams) {
  6296. const auto pattern = "/users/:userid/subscriptions/:subid";
  6297. detail::PathParamsMatcher matcher(pattern);
  6298. Request request;
  6299. request.path = "/users/42/subscriptions/2";
  6300. ASSERT_TRUE(matcher.match(request));
  6301. std::unordered_map<std::string, std::string> expected_params = {
  6302. {"userid", "42"}, {"subid", "2"}};
  6303. EXPECT_EQ(request.path_params, expected_params);
  6304. }
  6305. TEST(PathParamsTest, SequenceOfParams) {
  6306. const auto pattern = "/values/:x/:y/:z";
  6307. detail::PathParamsMatcher matcher(pattern);
  6308. Request request;
  6309. request.path = "/values/1/2/3";
  6310. ASSERT_TRUE(matcher.match(request));
  6311. std::unordered_map<std::string, std::string> expected_params = {
  6312. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6313. EXPECT_EQ(request.path_params, expected_params);
  6314. }
  6315. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6316. // If ipv6 regex working, regex match codepath is taken.
  6317. // else port will default to 80 in Client impl
  6318. int clientImplMagicPort = 80;
  6319. int port = 4321;
  6320. // above ports must be different to avoid false negative
  6321. EXPECT_NE(clientImplMagicPort, port);
  6322. std::string ipV6TestURL = "http://[ff06::c3]";
  6323. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6324. CLIENT_PRIVATE_KEY_FILE);
  6325. EXPECT_EQ(cli.port(), port);
  6326. }
  6327. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6328. auto file_path = "./www/dir/index.html";
  6329. auto dir_path = "./www/dir";
  6330. EXPECT_TRUE(detail::is_file(file_path));
  6331. EXPECT_FALSE(detail::is_dir(file_path));
  6332. EXPECT_FALSE(detail::is_file(dir_path));
  6333. EXPECT_TRUE(detail::is_dir(dir_path));
  6334. }
  6335. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6336. Server svr;
  6337. svr.Get("/test", [&](const Request &/*req*/, Response &res) {
  6338. EXPECT_EQ(res.status, 400);
  6339. });
  6340. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6341. auto se = detail::scope_exit([&] {
  6342. svr.stop();
  6343. thread.join();
  6344. ASSERT_FALSE(svr.is_running());
  6345. });
  6346. svr.wait_until_ready();
  6347. Client cli(HOST, PORT);
  6348. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6349. }