1
0

test.cc 432 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <chrono>
  17. #include <cstdio>
  18. #include <fstream>
  19. #include <future>
  20. #include <limits>
  21. #include <memory>
  22. #include <sstream>
  23. #include <stdexcept>
  24. #include <thread>
  25. #include <type_traits>
  26. #include <vector>
  27. #define SERVER_CERT_FILE "./cert.pem"
  28. #define SERVER_CERT2_FILE "./cert2.pem"
  29. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  30. #define CA_CERT_FILE "./ca-bundle.crt"
  31. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  32. #define CLIENT_CA_CERT_DIR "."
  33. #define CLIENT_CERT_FILE "./client.cert.pem"
  34. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  35. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  36. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  37. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  38. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  39. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  40. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  41. using namespace std;
  42. using namespace httplib;
  43. const char *HOST = "localhost";
  44. const int PORT = 1234;
  45. const string LONG_QUERY_VALUE = string(25000, '@');
  46. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  47. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  48. const string TOO_LONG_QUERY_URL =
  49. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  50. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  51. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  52. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  53. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  54. return file.name == key;
  55. });
  56. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  57. return *it;
  58. #else
  59. if (it != items.end()) { return *it; }
  60. throw std::runtime_error("invalid multipart form data name error");
  61. #endif
  62. }
  63. static void read_file(const std::string &path, std::string &out) {
  64. std::ifstream fs(path, std::ios_base::binary);
  65. if (!fs) throw std::runtime_error("File not found: " + path);
  66. fs.seekg(0, std::ios_base::end);
  67. auto size = fs.tellg();
  68. fs.seekg(0);
  69. out.resize(static_cast<size_t>(size));
  70. fs.read(&out[0], static_cast<std::streamsize>(size));
  71. }
  72. void performance_test(const char *host) {
  73. Server svr;
  74. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  75. res.set_content("Benchmark Response", "text/plain");
  76. });
  77. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  78. auto se = detail::scope_exit([&] {
  79. svr.stop();
  80. listen_thread.join();
  81. ASSERT_FALSE(svr.is_running());
  82. });
  83. svr.wait_until_ready();
  84. Client cli(host, PORT);
  85. // Warm-up request to establish connection and resolve DNS
  86. auto warmup_res = cli.Get("/benchmark");
  87. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  88. // Run multiple trials and collect timings
  89. const int num_trials = 20;
  90. std::vector<int64_t> timings;
  91. timings.reserve(num_trials);
  92. for (int i = 0; i < num_trials; i++) {
  93. auto start = std::chrono::high_resolution_clock::now();
  94. auto res = cli.Get("/benchmark");
  95. auto end = std::chrono::high_resolution_clock::now();
  96. auto elapsed =
  97. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  98. .count();
  99. // Assertions after timing measurement to avoid overhead
  100. ASSERT_TRUE(res);
  101. EXPECT_EQ(StatusCode::OK_200, res->status);
  102. timings.push_back(elapsed);
  103. }
  104. // Calculate 25th percentile (lower quartile)
  105. std::sort(timings.begin(), timings.end());
  106. auto p25 = timings[num_trials / 4];
  107. // Format timings for output
  108. std::ostringstream timings_str;
  109. timings_str << "[";
  110. for (size_t i = 0; i < timings.size(); i++) {
  111. if (i > 0) timings_str << ", ";
  112. timings_str << timings[i];
  113. }
  114. timings_str << "]";
  115. // Localhost HTTP GET should be fast even in CI environments
  116. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  117. << "ms (Issue #1777). Timings: " << timings_str.str();
  118. }
  119. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  120. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  121. class UnixSocketTest : public ::testing::Test {
  122. protected:
  123. void TearDown() override { std::remove(pathname_.c_str()); }
  124. void client_GET(const std::string &addr) {
  125. httplib::Client cli{addr};
  126. cli.set_address_family(AF_UNIX);
  127. ASSERT_TRUE(cli.is_valid());
  128. const auto &result = cli.Get(pattern_);
  129. ASSERT_TRUE(result) << "error: " << result.error();
  130. const auto &resp = result.value();
  131. EXPECT_EQ(resp.status, StatusCode::OK_200);
  132. EXPECT_EQ(resp.body, content_);
  133. }
  134. const std::string pathname_{"./httplib-server.sock"};
  135. const std::string pattern_{"/hi"};
  136. const std::string content_{"Hello World!"};
  137. };
  138. TEST_F(UnixSocketTest, pathname) {
  139. httplib::Server svr;
  140. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  141. res.set_content(content_, "text/plain");
  142. });
  143. std::thread t{[&] {
  144. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  145. }};
  146. auto se = detail::scope_exit([&] {
  147. svr.stop();
  148. t.join();
  149. ASSERT_FALSE(svr.is_running());
  150. });
  151. svr.wait_until_ready();
  152. ASSERT_TRUE(svr.is_running());
  153. client_GET(pathname_);
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_EQ(0, close(fds[1]));
  246. EXPECT_FALSE(s0.wait_writable());
  247. return true;
  248. });
  249. EXPECT_EQ(0, close(fds[0]));
  250. }
  251. TEST(SocketStream, wait_writable_INET) {
  252. sockaddr_in addr;
  253. memset(&addr, 0, sizeof(addr));
  254. addr.sin_family = AF_INET;
  255. addr.sin_port = htons(PORT + 1);
  256. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  257. int disconnected_svr_sock = -1;
  258. std::thread svr{[&] {
  259. const int s = socket(AF_INET, SOCK_STREAM, 0);
  260. ASSERT_LE(0, s);
  261. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  262. ASSERT_EQ(0, listen(s, 1));
  263. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  264. ASSERT_EQ(0, close(s));
  265. }};
  266. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  267. std::thread cli{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. cli.join();
  274. svr.join();
  275. ASSERT_NE(disconnected_svr_sock, -1);
  276. const auto asSocketStream = [&](socket_t fd,
  277. std::function<bool(Stream &)> func) {
  278. return detail::process_client_socket(
  279. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  280. };
  281. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  282. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  283. EXPECT_FALSE(ss.wait_writable());
  284. return true;
  285. });
  286. ASSERT_EQ(0, close(disconnected_svr_sock));
  287. }
  288. #endif // #ifndef _WIN32
  289. TEST(ClientTest, MoveConstructible) {
  290. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  291. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  292. }
  293. TEST(ClientTest, MoveAssignable) {
  294. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  295. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  296. }
  297. #ifdef _WIN32
  298. TEST(StartupTest, WSAStartup) {
  299. WSADATA wsaData;
  300. int ret = WSAStartup(0x0002, &wsaData);
  301. ASSERT_EQ(0, ret);
  302. }
  303. #endif
  304. TEST(DecodePathTest, PercentCharacter) {
  305. EXPECT_EQ(
  306. decode_path_component(
  307. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  308. u8"descrip=Gastos áéíóúñÑ 6");
  309. }
  310. TEST(DecodePathTest, PercentCharacterNUL) {
  311. string expected;
  312. expected.push_back('x');
  313. expected.push_back('\0');
  314. expected.push_back('x');
  315. EXPECT_EQ(decode_path_component("x%00x"), expected);
  316. }
  317. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  318. string unescapedCharacters = "-_.!~*'()";
  319. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  320. }
  321. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  322. string reservedCharacters = ";,/?:@&=+$";
  323. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  324. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  325. }
  326. TEST(ClientQueryOrder, PreserveOrder) {
  327. // This test reproduces Issue #2259: client may reorder query parameters
  328. // when sending a GET request. The expected behavior is that the client
  329. // preserves the original query string order when the caller supplied it
  330. // as part of the path.
  331. Server svr;
  332. svr.Get("/", [&](const Request &req, Response &res) {
  333. // Echo back the raw target so the test can assert ordering
  334. res.set_content(req.target, "text/plain");
  335. });
  336. std::thread t{[&] { svr.listen(HOST, PORT); }};
  337. auto se = detail::scope_exit([&] {
  338. svr.stop();
  339. t.join();
  340. ASSERT_FALSE(svr.is_running());
  341. });
  342. svr.wait_until_ready();
  343. Client cli(HOST, PORT);
  344. ASSERT_TRUE(cli.is_valid());
  345. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  346. auto res = cli.Get(original);
  347. ASSERT_TRUE(res);
  348. // Expect the echoed target to exactly match the original path (order
  349. // preserved)
  350. EXPECT_EQ(res->body, original);
  351. }
  352. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  353. string chineseCharacters = u8"中国語";
  354. string russianCharacters = u8"дом";
  355. string brazilianCharacters = u8"óculos";
  356. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  357. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  358. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  359. "%D0%B4%D0%BE%D0%BC");
  360. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  361. }
  362. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  363. string unescapedCharacters = "-_.!~*'()";
  364. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  365. }
  366. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  367. string reservedCharacters = ";,/?:@&=+$";
  368. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  369. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  370. }
  371. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  372. string chineseCharacters = u8"中国語";
  373. string russianCharacters = u8"дом";
  374. string brazilianCharacters = u8"óculos";
  375. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  376. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  377. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  378. "%D0%B4%D0%BE%D0%BC");
  379. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  380. }
  381. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  382. // Issue #2082 use case: encoding path component with ampersand
  383. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  384. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  385. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  386. }
  387. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  388. string unescapedCharacters = "-_.!~*'()";
  389. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  390. }
  391. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  392. string reservedCharacters = ";,/?:@&=+$#";
  393. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  394. }
  395. TEST(EncodeUriTest, TestUTF8Characters) {
  396. string chineseCharacters = u8"中国語";
  397. string russianCharacters = u8"дом";
  398. string brazilianCharacters = u8"óculos";
  399. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  400. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  401. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  402. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  403. }
  404. TEST(EncodeUriTest, TestCompleteUri) {
  405. string uri =
  406. "https://example.com/path/to/resource?query=value&param=test#fragment";
  407. EXPECT_EQ(
  408. httplib::encode_uri(uri),
  409. "https://example.com/path/to/resource?query=value&param=test#fragment");
  410. }
  411. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  412. string uri =
  413. "https://example.com/path with spaces/file name.html?q=hello world";
  414. EXPECT_EQ(httplib::encode_uri(uri),
  415. "https://example.com/path%20with%20spaces/"
  416. "file%20name.html?q=hello%20world");
  417. }
  418. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  419. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  420. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  421. }
  422. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  423. string unescapedCharacters = "-_.!~*'()";
  424. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  425. }
  426. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  427. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  428. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  429. string encodedBrazilian = "%C3%B3culos";
  430. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), u8"中国語");
  431. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), u8"дом");
  432. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), u8"óculos");
  433. }
  434. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  435. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  436. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  437. "Piri Tommy Villiers - on & on");
  438. }
  439. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  440. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  441. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  442. }
  443. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  444. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  445. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  446. }
  447. TEST(DecodeUriTest, TestUTF8Characters) {
  448. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  449. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  450. string encodedBrazilian = "%C3%B3culos";
  451. EXPECT_EQ(httplib::decode_uri(encodedChinese), u8"中国語");
  452. EXPECT_EQ(httplib::decode_uri(encodedRussian), u8"дом");
  453. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), u8"óculos");
  454. }
  455. TEST(DecodeUriTest, TestCompleteUri) {
  456. string encodedUri = "https://example.com/path%20with%20spaces/"
  457. "file%20name.html?q=hello%20world";
  458. EXPECT_EQ(
  459. httplib::decode_uri(encodedUri),
  460. "https://example.com/path with spaces/file name.html?q=hello world");
  461. }
  462. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  463. string original =
  464. "https://example.com/path with spaces/file name.html?q=hello world";
  465. string encoded = httplib::encode_uri(original);
  466. string decoded = httplib::decode_uri(encoded);
  467. EXPECT_EQ(decoded, original);
  468. }
  469. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  470. string original = "Piri Tommy Villiers - on & on";
  471. string encoded = httplib::encode_uri_component(original);
  472. string decoded = httplib::decode_uri_component(encoded);
  473. EXPECT_EQ(decoded, original);
  474. }
  475. TEST(TrimTests, TrimStringTests) {
  476. EXPECT_EQ("abc", detail::trim_copy("abc"));
  477. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  478. EXPECT_TRUE(detail::trim_copy("").empty());
  479. }
  480. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  481. // Simple case without quality values
  482. std::vector<std::string> result1;
  483. EXPECT_TRUE(detail::parse_accept_header(
  484. "text/html,application/json,text/plain", result1));
  485. EXPECT_EQ(result1.size(), 3U);
  486. EXPECT_EQ(result1[0], "text/html");
  487. EXPECT_EQ(result1[1], "application/json");
  488. EXPECT_EQ(result1[2], "text/plain");
  489. // With quality values
  490. std::vector<std::string> result2;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  493. EXPECT_EQ(result2.size(), 3U);
  494. EXPECT_EQ(result2[0], "application/json"); // highest q value
  495. EXPECT_EQ(result2[1], "text/html");
  496. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  497. }
  498. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  499. // Mixed with and without quality values
  500. std::vector<std::string> result;
  501. EXPECT_TRUE(detail::parse_accept_header(
  502. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  503. EXPECT_EQ(result.size(), 3U);
  504. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  505. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  506. EXPECT_EQ(result[2], "application/json"); // q=0.5
  507. }
  508. TEST(ParseAcceptHeaderTest, EdgeCases) {
  509. // Empty header
  510. std::vector<std::string> empty_result;
  511. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  512. EXPECT_TRUE(empty_result.empty());
  513. // Single type
  514. std::vector<std::string> single_result;
  515. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  516. EXPECT_EQ(single_result.size(), 1U);
  517. EXPECT_EQ(single_result[0], "application/json");
  518. // Wildcard types
  519. std::vector<std::string> wildcard_result;
  520. EXPECT_TRUE(detail::parse_accept_header(
  521. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  522. EXPECT_EQ(wildcard_result.size(), 3U);
  523. EXPECT_EQ(wildcard_result[0], "application/json");
  524. EXPECT_EQ(wildcard_result[1], "text/*");
  525. EXPECT_EQ(wildcard_result[2], "*/*");
  526. }
  527. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  528. // Common browser Accept header
  529. std::vector<std::string> browser_result;
  530. EXPECT_TRUE(
  531. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  532. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  533. browser_result));
  534. EXPECT_EQ(browser_result.size(), 6U);
  535. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  536. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  537. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  538. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  539. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  540. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  541. // API client header
  542. std::vector<std::string> api_result;
  543. EXPECT_TRUE(detail::parse_accept_header(
  544. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  545. api_result));
  546. EXPECT_EQ(api_result.size(), 3U);
  547. EXPECT_EQ(api_result[0], "application/json");
  548. EXPECT_EQ(api_result[1], "application/xml");
  549. EXPECT_EQ(api_result[2], "text/plain");
  550. }
  551. TEST(ParseAcceptHeaderTest, SpecialCases) {
  552. // Quality value with 3 decimal places
  553. std::vector<std::string> decimal_result;
  554. EXPECT_TRUE(detail::parse_accept_header(
  555. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  556. EXPECT_EQ(decimal_result.size(), 2U);
  557. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  558. EXPECT_EQ(decimal_result[1], "text/html");
  559. // Zero quality (should still be included but with lowest priority)
  560. std::vector<std::string> zero_q_result;
  561. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  562. zero_q_result));
  563. EXPECT_EQ(zero_q_result.size(), 2U);
  564. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  565. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  566. // No spaces around commas
  567. std::vector<std::string> no_space_result;
  568. EXPECT_TRUE(detail::parse_accept_header(
  569. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  570. no_space_result));
  571. EXPECT_EQ(no_space_result.size(), 3U);
  572. EXPECT_EQ(no_space_result[0], "text/html");
  573. EXPECT_EQ(no_space_result[1], "application/json");
  574. EXPECT_EQ(no_space_result[2], "text/plain");
  575. }
  576. TEST(ParseAcceptHeaderTest, InvalidCases) {
  577. std::vector<std::string> result;
  578. // Invalid quality value (> 1.0)
  579. EXPECT_FALSE(
  580. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  581. // Invalid quality value (< 0.0)
  582. EXPECT_FALSE(
  583. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  584. // Invalid quality value (not a number)
  585. EXPECT_FALSE(detail::parse_accept_header(
  586. "text/html;q=invalid,application/json", result));
  587. // Empty quality value
  588. EXPECT_FALSE(
  589. detail::parse_accept_header("text/html;q=,application/json", result));
  590. // Invalid media type format (no slash and not wildcard)
  591. EXPECT_FALSE(
  592. detail::parse_accept_header("invalidtype,application/json", result));
  593. // Empty media type
  594. result.clear();
  595. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  596. // Only commas
  597. result.clear();
  598. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  599. // Valid cases should still work
  600. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  601. EXPECT_EQ(result.size(), 1U);
  602. EXPECT_EQ(result[0], "*/*");
  603. EXPECT_TRUE(detail::parse_accept_header("*", result));
  604. EXPECT_EQ(result.size(), 1U);
  605. EXPECT_EQ(result[0], "*");
  606. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  607. EXPECT_EQ(result.size(), 1U);
  608. EXPECT_EQ(result[0], "text/*");
  609. }
  610. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  611. Server svr;
  612. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  613. EXPECT_EQ(req.accept_content_types.size(), 3U);
  614. EXPECT_EQ(req.accept_content_types[0], "application/json");
  615. EXPECT_EQ(req.accept_content_types[1], "text/html");
  616. EXPECT_EQ(req.accept_content_types[2], "*/*");
  617. res.set_content("ok", "text/plain");
  618. });
  619. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  620. EXPECT_TRUE(false);
  621. res.set_content("bad request", "text/plain");
  622. });
  623. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  624. auto se = detail::scope_exit([&] {
  625. svr.stop();
  626. listen_thread.join();
  627. ASSERT_FALSE(svr.is_running());
  628. });
  629. svr.wait_until_ready();
  630. Client cli("localhost", PORT);
  631. {
  632. auto res =
  633. cli.Get("/accept_ok",
  634. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  635. ASSERT_TRUE(res);
  636. EXPECT_EQ(StatusCode::OK_200, res->status);
  637. }
  638. {
  639. auto res = cli.Get("/accept_bad_request",
  640. {{"Accept", "text/html;q=abc,application/json"}});
  641. ASSERT_TRUE(res);
  642. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  643. }
  644. }
  645. TEST(DivideTest, DivideStringTests) {
  646. auto divide = [](const std::string &str, char d) {
  647. std::string lhs;
  648. std::string rhs;
  649. detail::divide(str, d,
  650. [&](const char *lhs_data, std::size_t lhs_size,
  651. const char *rhs_data, std::size_t rhs_size) {
  652. lhs.assign(lhs_data, lhs_size);
  653. rhs.assign(rhs_data, rhs_size);
  654. });
  655. return std::make_pair(std::move(lhs), std::move(rhs));
  656. };
  657. {
  658. const auto res = divide("", '=');
  659. EXPECT_EQ(res.first, "");
  660. EXPECT_EQ(res.second, "");
  661. }
  662. {
  663. const auto res = divide("=", '=');
  664. EXPECT_EQ(res.first, "");
  665. EXPECT_EQ(res.second, "");
  666. }
  667. {
  668. const auto res = divide(" ", '=');
  669. EXPECT_EQ(res.first, " ");
  670. EXPECT_EQ(res.second, "");
  671. }
  672. {
  673. const auto res = divide("a", '=');
  674. EXPECT_EQ(res.first, "a");
  675. EXPECT_EQ(res.second, "");
  676. }
  677. {
  678. const auto res = divide("a=", '=');
  679. EXPECT_EQ(res.first, "a");
  680. EXPECT_EQ(res.second, "");
  681. }
  682. {
  683. const auto res = divide("=b", '=');
  684. EXPECT_EQ(res.first, "");
  685. EXPECT_EQ(res.second, "b");
  686. }
  687. {
  688. const auto res = divide("a=b", '=');
  689. EXPECT_EQ(res.first, "a");
  690. EXPECT_EQ(res.second, "b");
  691. }
  692. {
  693. const auto res = divide("a=b=", '=');
  694. EXPECT_EQ(res.first, "a");
  695. EXPECT_EQ(res.second, "b=");
  696. }
  697. {
  698. const auto res = divide("a=b=c", '=');
  699. EXPECT_EQ(res.first, "a");
  700. EXPECT_EQ(res.second, "b=c");
  701. }
  702. }
  703. TEST(SplitTest, ParseQueryString) {
  704. string s = "key1=val1&key2=val2&key3=val3";
  705. Params dic;
  706. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  707. [&](const char *b, const char *e) {
  708. string key, val;
  709. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  710. if (key.empty()) {
  711. key.assign(b2, e2);
  712. } else {
  713. val.assign(b2, e2);
  714. }
  715. });
  716. dic.emplace(key, val);
  717. });
  718. EXPECT_EQ("val1", dic.find("key1")->second);
  719. EXPECT_EQ("val2", dic.find("key2")->second);
  720. EXPECT_EQ("val3", dic.find("key3")->second);
  721. }
  722. TEST(SplitTest, ParseInvalidQueryTests) {
  723. {
  724. string s = " ";
  725. Params dict;
  726. detail::parse_query_text(s, dict);
  727. EXPECT_TRUE(dict.empty());
  728. }
  729. {
  730. string s = " = =";
  731. Params dict;
  732. detail::parse_query_text(s, dict);
  733. EXPECT_TRUE(dict.empty());
  734. }
  735. }
  736. TEST(ParseQueryTest, ParseQueryString) {
  737. {
  738. std::string s = "key1=val1&key2=val2&key3=val3";
  739. Params dic;
  740. detail::parse_query_text(s, dic);
  741. EXPECT_EQ("val1", dic.find("key1")->second);
  742. EXPECT_EQ("val2", dic.find("key2")->second);
  743. EXPECT_EQ("val3", dic.find("key3")->second);
  744. }
  745. {
  746. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("", dic.find("key1")->second);
  750. EXPECT_EQ("val1", dic.find("key2")->second);
  751. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  752. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  753. }
  754. }
  755. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  756. Params dic;
  757. EXPECT_EQ(detail::params_to_query_str(dic), "");
  758. dic.emplace("key1", "val1");
  759. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  760. dic.emplace("key2", "val2");
  761. dic.emplace("key3", "val3");
  762. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  763. }
  764. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  765. string content_type = "multipart/form-data; boundary=something";
  766. string boundary;
  767. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  768. EXPECT_TRUE(ret);
  769. EXPECT_EQ(boundary, "something");
  770. }
  771. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  772. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  773. string boundary;
  774. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  775. EXPECT_TRUE(ret);
  776. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  777. }
  778. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  779. string content_type =
  780. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  793. }
  794. TEST(GetHeaderValueTest, DefaultValue) {
  795. Headers headers = {{"Dummy", "Dummy"}};
  796. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  797. EXPECT_STREQ("text/plain", val);
  798. }
  799. TEST(GetHeaderValueTest, DefaultValueInt) {
  800. Headers headers = {{"Dummy", "Dummy"}};
  801. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  802. EXPECT_EQ(100ull, val);
  803. }
  804. TEST(GetHeaderValueTest, RegularValue) {
  805. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  806. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  807. EXPECT_STREQ("text/html", val);
  808. }
  809. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  810. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  811. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  812. EXPECT_STREQ("text/html", val);
  813. }
  814. TEST(GetHeaderValueTest, SetContent) {
  815. Response res;
  816. res.set_content("html", "text/html");
  817. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  818. res.set_content("text", "text/plain");
  819. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  820. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  821. }
  822. TEST(GetHeaderValueTest, RegularValueInt) {
  823. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  824. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  825. EXPECT_EQ(100ull, val);
  826. }
  827. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  828. Headers headers = {{"Content-Length", "x"}};
  829. auto is_invalid_value = false;
  830. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  831. is_invalid_value);
  832. EXPECT_EQ(0ull, val);
  833. EXPECT_TRUE(is_invalid_value);
  834. }
  835. TEST(GetHeaderValueTest, Range) {
  836. {
  837. Headers headers = {make_range_header({{1, -1}})};
  838. auto val = detail::get_header_value(headers, "Range", 0, 0);
  839. EXPECT_STREQ("bytes=1-", val);
  840. }
  841. {
  842. Headers headers = {make_range_header({{-1, 1}})};
  843. auto val = detail::get_header_value(headers, "Range", 0, 0);
  844. EXPECT_STREQ("bytes=-1", val);
  845. }
  846. {
  847. Headers headers = {make_range_header({{1, 10}})};
  848. auto val = detail::get_header_value(headers, "Range", 0, 0);
  849. EXPECT_STREQ("bytes=1-10", val);
  850. }
  851. {
  852. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  853. auto val = detail::get_header_value(headers, "Range", 0, 0);
  854. EXPECT_STREQ("bytes=1-10, 100-", val);
  855. }
  856. {
  857. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  859. EXPECT_STREQ("bytes=1-10, 100-200", val);
  860. }
  861. {
  862. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  863. auto val = detail::get_header_value(headers, "Range", 0, 0);
  864. EXPECT_STREQ("bytes=0-0, -1", val);
  865. }
  866. }
  867. TEST(ParseHeaderValueTest, Range) {
  868. {
  869. Ranges ranges;
  870. auto ret = detail::parse_range_header("bytes=1-", ranges);
  871. EXPECT_TRUE(ret);
  872. EXPECT_EQ(1u, ranges.size());
  873. EXPECT_EQ(1u, ranges[0].first);
  874. EXPECT_EQ(-1, ranges[0].second);
  875. }
  876. {
  877. Ranges ranges;
  878. auto ret = detail::parse_range_header("bytes=-1", ranges);
  879. EXPECT_TRUE(ret);
  880. EXPECT_EQ(1u, ranges.size());
  881. EXPECT_EQ(-1, ranges[0].first);
  882. EXPECT_EQ(1u, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(1u, ranges[0].first);
  890. EXPECT_EQ(10u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  895. EXPECT_FALSE(ret);
  896. }
  897. {
  898. Ranges ranges;
  899. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  900. EXPECT_TRUE(ret);
  901. EXPECT_EQ(2u, ranges.size());
  902. EXPECT_EQ(1u, ranges[0].first);
  903. EXPECT_EQ(10u, ranges[0].second);
  904. EXPECT_EQ(100u, ranges[1].first);
  905. EXPECT_EQ(-1, ranges[1].second);
  906. }
  907. {
  908. Ranges ranges;
  909. auto ret =
  910. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  911. EXPECT_TRUE(ret);
  912. EXPECT_EQ(3u, ranges.size());
  913. EXPECT_EQ(1u, ranges[0].first);
  914. EXPECT_EQ(10u, ranges[0].second);
  915. EXPECT_EQ(100u, ranges[1].first);
  916. EXPECT_EQ(200u, ranges[1].second);
  917. EXPECT_EQ(300u, ranges[2].first);
  918. EXPECT_EQ(400u, ranges[2].second);
  919. }
  920. {
  921. Ranges ranges;
  922. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  923. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  924. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  925. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  926. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  927. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  928. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  929. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  930. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  935. EXPECT_TRUE(ranges.empty());
  936. }
  937. }
  938. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  939. Request req;
  940. req.set_header("Accept-Encoding", "gzip");
  941. Response res;
  942. res.set_header("Content-Type", "text/plain");
  943. auto ret = detail::encoding_type(req, res);
  944. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  945. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  946. #else
  947. EXPECT_TRUE(ret == detail::EncodingType::None);
  948. #endif
  949. }
  950. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  951. Request req;
  952. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  953. Response res;
  954. res.set_header("Content-Type", "text/plain");
  955. auto ret = detail::encoding_type(req, res);
  956. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  957. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  958. #elif CPPHTTPLIB_ZLIB_SUPPORT
  959. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  960. #elif CPPHTTPLIB_ZSTD_SUPPORT
  961. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  962. #else
  963. EXPECT_TRUE(ret == detail::EncodingType::None);
  964. #endif
  965. }
  966. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  967. Request req;
  968. req.set_header("Accept-Encoding",
  969. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  970. Response res;
  971. res.set_header("Content-Type", "text/plain");
  972. auto ret = detail::encoding_type(req, res);
  973. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  974. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  975. #elif CPPHTTPLIB_ZLIB_SUPPORT
  976. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  977. #elif CPPHTTPLIB_ZSTD_SUPPORT
  978. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  979. #else
  980. EXPECT_TRUE(ret == detail::EncodingType::None);
  981. #endif
  982. }
  983. TEST(BufferStreamTest, read) {
  984. detail::BufferStream strm1;
  985. Stream &strm = strm1;
  986. EXPECT_EQ(5, strm.write("hello"));
  987. char buf[512];
  988. EXPECT_EQ(2, strm.read(buf, 2));
  989. EXPECT_EQ('h', buf[0]);
  990. EXPECT_EQ('e', buf[1]);
  991. EXPECT_EQ(2, strm.read(buf, 2));
  992. EXPECT_EQ('l', buf[0]);
  993. EXPECT_EQ('l', buf[1]);
  994. EXPECT_EQ(1, strm.read(buf, 1));
  995. EXPECT_EQ('o', buf[0]);
  996. EXPECT_EQ(0, strm.read(buf, 1));
  997. }
  998. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  999. auto host = "www.httpwatch.com";
  1000. auto ip = hosted_at(host);
  1001. EXPECT_EQ("23.96.13.243", ip);
  1002. std::vector<std::string> addrs;
  1003. hosted_at(host, addrs);
  1004. EXPECT_EQ(1u, addrs.size());
  1005. }
  1006. #if 0 // It depends on each test environment...
  1007. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1008. auto host = "www.youtube.com";
  1009. std::vector<std::string> addrs;
  1010. hosted_at(host, addrs);
  1011. EXPECT_EQ(20u, addrs.size());
  1012. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1013. EXPECT_TRUE(it != addrs.end());
  1014. }
  1015. #endif
  1016. class ChunkedEncodingTest : public ::testing::Test {
  1017. protected:
  1018. ChunkedEncodingTest()
  1019. : cli_(HOST, PORT)
  1020. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1021. ,
  1022. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1023. #endif
  1024. {
  1025. cli_.set_connection_timeout(2);
  1026. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1027. cli_.enable_server_certificate_verification(false);
  1028. #endif
  1029. }
  1030. virtual void SetUp() {
  1031. read_file("./image.jpg", image_data_);
  1032. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1033. res.set_content("Hello World!", "text/plain");
  1034. });
  1035. svr_.Get(
  1036. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1037. res.set_chunked_content_provider(
  1038. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1039. size_t remaining = image_data_.size() - offset;
  1040. if (remaining == 0) {
  1041. sink.done();
  1042. } else {
  1043. constexpr size_t CHUNK_SIZE = 1024;
  1044. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1045. sink.write(&image_data_[offset], send_size);
  1046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1047. }
  1048. return true;
  1049. });
  1050. });
  1051. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1052. svr_.wait_until_ready();
  1053. }
  1054. virtual void TearDown() {
  1055. svr_.stop();
  1056. if (!request_threads_.empty()) {
  1057. std::this_thread::sleep_for(std::chrono::seconds(1));
  1058. for (auto &t : request_threads_) {
  1059. t.join();
  1060. }
  1061. }
  1062. t_.join();
  1063. }
  1064. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1065. SSLClient cli_;
  1066. SSLServer svr_;
  1067. #else
  1068. Client cli_;
  1069. Server svr_;
  1070. #endif
  1071. thread t_;
  1072. std::vector<thread> request_threads_;
  1073. std::string image_data_;
  1074. };
  1075. TEST_F(ChunkedEncodingTest, NormalGet) {
  1076. auto res = cli_.Get("/chunked");
  1077. ASSERT_TRUE(res);
  1078. std::string out;
  1079. read_file("./image.jpg", out);
  1080. EXPECT_EQ(StatusCode::OK_200, res->status);
  1081. EXPECT_EQ(out, res->body);
  1082. }
  1083. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1084. std::string body;
  1085. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1086. body.append(data, data_length);
  1087. return true;
  1088. });
  1089. ASSERT_TRUE(res);
  1090. std::string out;
  1091. read_file("./image.jpg", out);
  1092. EXPECT_EQ(StatusCode::OK_200, res->status);
  1093. EXPECT_EQ(out, body);
  1094. }
  1095. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1096. std::string body;
  1097. auto res = cli_.Get(
  1098. "/chunked",
  1099. [&](const Response &response) {
  1100. EXPECT_EQ(StatusCode::OK_200, response.status);
  1101. return true;
  1102. },
  1103. [&](const char *data, size_t data_length) {
  1104. body.append(data, data_length);
  1105. return true;
  1106. });
  1107. ASSERT_TRUE(res);
  1108. std::string out;
  1109. read_file("./image.jpg", out);
  1110. EXPECT_EQ(StatusCode::OK_200, res->status);
  1111. EXPECT_EQ(out, body);
  1112. }
  1113. TEST(RangeTest, FromHTTPBin_Online) {
  1114. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1115. auto host = "httpcan.org";
  1116. auto path = std::string{"/range/32"};
  1117. #else
  1118. auto host = "nghttp2.org";
  1119. auto path = std::string{"/httpbin/range/32"};
  1120. #endif
  1121. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1122. auto port = 443;
  1123. SSLClient cli(host, port);
  1124. #else
  1125. auto port = 80;
  1126. Client cli(host, port);
  1127. #endif
  1128. cli.set_connection_timeout(5);
  1129. {
  1130. auto res = cli.Get(path);
  1131. ASSERT_TRUE(res);
  1132. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1133. EXPECT_EQ(StatusCode::OK_200, res->status);
  1134. }
  1135. {
  1136. Headers headers = {make_range_header({{1, -1}})};
  1137. auto res = cli.Get(path, headers);
  1138. ASSERT_TRUE(res);
  1139. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1141. }
  1142. {
  1143. Headers headers = {make_range_header({{1, 10}})};
  1144. auto res = cli.Get(path, headers);
  1145. ASSERT_TRUE(res);
  1146. EXPECT_EQ("bcdefghijk", res->body);
  1147. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1148. }
  1149. {
  1150. Headers headers = {make_range_header({{0, 31}})};
  1151. auto res = cli.Get(path, headers);
  1152. ASSERT_TRUE(res);
  1153. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. Headers headers = {make_range_header({{0, -1}})};
  1158. auto res = cli.Get(path, headers);
  1159. ASSERT_TRUE(res);
  1160. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. Headers headers = {make_range_header({{0, 32}})};
  1165. auto res = cli.Get(path, headers);
  1166. ASSERT_TRUE(res);
  1167. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1168. }
  1169. }
  1170. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1171. auto host = "unresolvableaddress.local";
  1172. auto path = std::string{"/"};
  1173. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1174. auto port = 443;
  1175. SSLClient cli(host, port);
  1176. #else
  1177. auto port = 80;
  1178. Client cli(host, port);
  1179. #endif
  1180. cli.set_connection_timeout(1);
  1181. {
  1182. auto res = cli.Get(path);
  1183. ASSERT_FALSE(res);
  1184. }
  1185. std::this_thread::sleep_for(std::chrono::seconds(8));
  1186. }
  1187. TEST(ConnectionErrorTest, InvalidHost) {
  1188. auto host = "-abcde.com";
  1189. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1190. auto port = 443;
  1191. SSLClient cli(host, port);
  1192. #else
  1193. auto port = 80;
  1194. Client cli(host, port);
  1195. #endif
  1196. cli.set_connection_timeout(std::chrono::seconds(2));
  1197. auto res = cli.Get("/");
  1198. ASSERT_TRUE(!res);
  1199. EXPECT_EQ(Error::Connection, res.error());
  1200. }
  1201. TEST(ConnectionErrorTest, InvalidHost2) {
  1202. auto host = "httpcan.org/";
  1203. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1204. SSLClient cli(host);
  1205. #else
  1206. Client cli(host);
  1207. #endif
  1208. cli.set_connection_timeout(std::chrono::seconds(2));
  1209. auto res = cli.Get("/");
  1210. ASSERT_TRUE(!res);
  1211. EXPECT_EQ(Error::Connection, res.error());
  1212. }
  1213. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1214. auto host = "httpcan.org/";
  1215. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1216. SSLClient cli(host);
  1217. #else
  1218. Client cli(host);
  1219. #endif
  1220. cli.set_connection_timeout(std::chrono::seconds(2));
  1221. auto res = cli.Get("/");
  1222. ASSERT_TRUE(!res);
  1223. stringstream s;
  1224. s << "error code: " << res.error();
  1225. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1226. }
  1227. TEST(ConnectionErrorTest, InvalidPort) {
  1228. auto host = "localhost";
  1229. auto port = 44380;
  1230. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1231. SSLClient cli(host, port);
  1232. #else
  1233. Client cli(host, port);
  1234. #endif
  1235. cli.set_connection_timeout(std::chrono::seconds(2));
  1236. auto res = cli.Get("/");
  1237. ASSERT_TRUE(!res);
  1238. EXPECT_TRUE(Error::Connection == res.error() ||
  1239. Error::ConnectionTimeout == res.error());
  1240. }
  1241. TEST(ConnectionErrorTest, Timeout_Online) {
  1242. auto host = "google.com";
  1243. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1244. auto port = 44380;
  1245. SSLClient cli(host, port);
  1246. #else
  1247. auto port = 8080;
  1248. Client cli(host, port);
  1249. #endif
  1250. cli.set_connection_timeout(std::chrono::seconds(2));
  1251. // only probe one address type so that the error reason
  1252. // correlates to the timed-out IPv4, not the unsupported
  1253. // IPv6 connection attempt
  1254. cli.set_address_family(AF_INET);
  1255. auto res = cli.Get("/");
  1256. ASSERT_TRUE(!res);
  1257. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1258. }
  1259. TEST(CancelTest, NoCancel_Online) {
  1260. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1261. auto host = "httpcan.org";
  1262. auto path = std::string{"/range/32"};
  1263. #else
  1264. auto host = "nghttp2.org";
  1265. auto path = std::string{"/httpbin/range/32"};
  1266. #endif
  1267. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1268. auto port = 443;
  1269. SSLClient cli(host, port);
  1270. #else
  1271. auto port = 80;
  1272. Client cli(host, port);
  1273. #endif
  1274. cli.set_connection_timeout(std::chrono::seconds(5));
  1275. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1276. ASSERT_TRUE(res);
  1277. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1278. EXPECT_EQ(StatusCode::OK_200, res->status);
  1279. }
  1280. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1281. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1282. auto host = "httpcan.org";
  1283. auto path = std::string{"/range/32"};
  1284. #else
  1285. auto host = "nghttp2.org";
  1286. auto path = std::string{"/httpbin/range/32"};
  1287. #endif
  1288. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1289. auto port = 443;
  1290. SSLClient cli(host, port);
  1291. #else
  1292. auto port = 80;
  1293. Client cli(host, port);
  1294. #endif
  1295. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1296. cli.set_connection_timeout(std::chrono::seconds(5));
  1297. ASSERT_TRUE(!res);
  1298. EXPECT_EQ(Error::Canceled, res.error());
  1299. }
  1300. TEST(CancelTest, WithCancelLargePayload_Online) {
  1301. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1302. auto host = "httpcan.org";
  1303. auto path = std::string{"/range/65536"};
  1304. #else
  1305. auto host = "nghttp2.org";
  1306. auto path = std::string{"/httpbin/range/65536"};
  1307. #endif
  1308. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1309. auto port = 443;
  1310. SSLClient cli(host, port);
  1311. #else
  1312. auto port = 80;
  1313. Client cli(host, port);
  1314. #endif
  1315. cli.set_connection_timeout(std::chrono::seconds(5));
  1316. uint32_t count = 0;
  1317. auto res =
  1318. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1319. ASSERT_TRUE(!res);
  1320. EXPECT_EQ(Error::Canceled, res.error());
  1321. }
  1322. TEST(CancelTest, NoCancelPost) {
  1323. Server svr;
  1324. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1325. res.set_content("Hello World!", "text/plain");
  1326. });
  1327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. thread.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. Client cli(HOST, PORT);
  1335. cli.set_connection_timeout(std::chrono::seconds(5));
  1336. auto res =
  1337. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1338. "application/json", [](uint64_t, uint64_t) { return true; });
  1339. ASSERT_TRUE(res);
  1340. EXPECT_EQ("Hello World!", res->body);
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. }
  1343. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1344. Server svr;
  1345. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1346. res.set_content("Hello World!", "text/plain");
  1347. });
  1348. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1349. auto se = detail::scope_exit([&] {
  1350. svr.stop();
  1351. thread.join();
  1352. ASSERT_FALSE(svr.is_running());
  1353. });
  1354. svr.wait_until_ready();
  1355. Client cli(HOST, PORT);
  1356. cli.set_connection_timeout(std::chrono::seconds(5));
  1357. auto res =
  1358. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1359. "application/json", [](uint64_t, uint64_t) { return false; });
  1360. ASSERT_TRUE(!res);
  1361. EXPECT_EQ(Error::Canceled, res.error());
  1362. }
  1363. TEST(CancelTest, WithCancelLargePayloadPost) {
  1364. Server svr;
  1365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1366. res.set_content(LARGE_DATA, "text/plain");
  1367. });
  1368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. thread.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. Client cli(HOST, PORT);
  1376. cli.set_connection_timeout(std::chrono::seconds(5));
  1377. auto res =
  1378. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1379. "application/json", [](uint64_t, uint64_t) { return false; });
  1380. ASSERT_TRUE(!res);
  1381. EXPECT_EQ(Error::Canceled, res.error());
  1382. }
  1383. TEST(CancelTest, NoCancelPut) {
  1384. Server svr;
  1385. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1386. res.set_content("Hello World!", "text/plain");
  1387. });
  1388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. thread.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, PORT);
  1396. cli.set_connection_timeout(std::chrono::seconds(5));
  1397. auto res =
  1398. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1399. "application/json", [](uint64_t, uint64_t) { return true; });
  1400. ASSERT_TRUE(res);
  1401. EXPECT_EQ("Hello World!", res->body);
  1402. EXPECT_EQ(StatusCode::OK_200, res->status);
  1403. }
  1404. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1405. Server svr;
  1406. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1407. res.set_content("Hello World!", "text/plain");
  1408. });
  1409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1410. auto se = detail::scope_exit([&] {
  1411. svr.stop();
  1412. thread.join();
  1413. ASSERT_FALSE(svr.is_running());
  1414. });
  1415. svr.wait_until_ready();
  1416. Client cli(HOST, PORT);
  1417. cli.set_connection_timeout(std::chrono::seconds(5));
  1418. auto res =
  1419. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1420. "application/json", [](uint64_t, uint64_t) { return false; });
  1421. ASSERT_TRUE(!res);
  1422. EXPECT_EQ(Error::Canceled, res.error());
  1423. }
  1424. TEST(CancelTest, WithCancelLargePayloadPut) {
  1425. Server svr;
  1426. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1427. res.set_content(LARGE_DATA, "text/plain");
  1428. });
  1429. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1430. auto se = detail::scope_exit([&] {
  1431. svr.stop();
  1432. thread.join();
  1433. ASSERT_FALSE(svr.is_running());
  1434. });
  1435. svr.wait_until_ready();
  1436. Client cli(HOST, PORT);
  1437. cli.set_connection_timeout(std::chrono::seconds(5));
  1438. auto res =
  1439. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1440. "application/json", [](uint64_t, uint64_t) { return false; });
  1441. ASSERT_TRUE(!res);
  1442. EXPECT_EQ(Error::Canceled, res.error());
  1443. }
  1444. TEST(CancelTest, NoCancelPatch) {
  1445. Server svr;
  1446. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1447. res.set_content("Hello World!", "text/plain");
  1448. });
  1449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1450. auto se = detail::scope_exit([&] {
  1451. svr.stop();
  1452. thread.join();
  1453. ASSERT_FALSE(svr.is_running());
  1454. });
  1455. svr.wait_until_ready();
  1456. Client cli(HOST, PORT);
  1457. cli.set_connection_timeout(std::chrono::seconds(5));
  1458. auto res =
  1459. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1460. "application/json", [](uint64_t, uint64_t) { return true; });
  1461. ASSERT_TRUE(res);
  1462. EXPECT_EQ("Hello World!", res->body);
  1463. EXPECT_EQ(StatusCode::OK_200, res->status);
  1464. }
  1465. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1466. Server svr;
  1467. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1468. res.set_content("Hello World!", "text/plain");
  1469. });
  1470. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1471. auto se = detail::scope_exit([&] {
  1472. svr.stop();
  1473. thread.join();
  1474. ASSERT_FALSE(svr.is_running());
  1475. });
  1476. svr.wait_until_ready();
  1477. Client cli(HOST, PORT);
  1478. cli.set_connection_timeout(std::chrono::seconds(5));
  1479. auto res =
  1480. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1481. "application/json", [](uint64_t, uint64_t) { return false; });
  1482. ASSERT_TRUE(!res);
  1483. EXPECT_EQ(Error::Canceled, res.error());
  1484. }
  1485. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1486. Server svr;
  1487. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1488. res.set_content(LARGE_DATA, "text/plain");
  1489. });
  1490. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. thread.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. Client cli(HOST, PORT);
  1498. cli.set_connection_timeout(std::chrono::seconds(5));
  1499. auto res =
  1500. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1501. "application/json", [](uint64_t, uint64_t) { return false; });
  1502. ASSERT_TRUE(!res);
  1503. EXPECT_EQ(Error::Canceled, res.error());
  1504. }
  1505. TEST(CancelTest, NoCancelDelete) {
  1506. Server svr;
  1507. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1508. res.set_content("Hello World!", "text/plain");
  1509. });
  1510. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1511. auto se = detail::scope_exit([&] {
  1512. svr.stop();
  1513. thread.join();
  1514. ASSERT_FALSE(svr.is_running());
  1515. });
  1516. svr.wait_until_ready();
  1517. Client cli(HOST, PORT);
  1518. cli.set_connection_timeout(std::chrono::seconds(5));
  1519. auto res =
  1520. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1521. "application/json", [](uint64_t, uint64_t) { return true; });
  1522. ASSERT_TRUE(res);
  1523. EXPECT_EQ("Hello World!", res->body);
  1524. EXPECT_EQ(StatusCode::OK_200, res->status);
  1525. }
  1526. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1527. Server svr;
  1528. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1529. res.set_content("Hello World!", "text/plain");
  1530. });
  1531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. thread.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. Client cli(HOST, PORT);
  1539. cli.set_connection_timeout(std::chrono::seconds(5));
  1540. auto res =
  1541. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1542. "application/json", [](uint64_t, uint64_t) { return false; });
  1543. ASSERT_TRUE(!res);
  1544. EXPECT_EQ(Error::Canceled, res.error());
  1545. }
  1546. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1547. Server svr;
  1548. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1549. res.set_content(LARGE_DATA, "text/plain");
  1550. });
  1551. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. thread.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. Client cli(HOST, PORT);
  1559. cli.set_connection_timeout(std::chrono::seconds(5));
  1560. auto res =
  1561. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1562. "application/json", [](uint64_t, uint64_t) { return false; });
  1563. ASSERT_TRUE(!res);
  1564. EXPECT_EQ(Error::Canceled, res.error());
  1565. }
  1566. static std::string remove_whitespace(const std::string &input) {
  1567. std::string output;
  1568. output.reserve(input.size());
  1569. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1570. [](unsigned char c) { return !std::isspace(c); });
  1571. return output;
  1572. }
  1573. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1574. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1575. auto host = "httpcan.org";
  1576. auto path = std::string{"/basic-auth/hello/world"};
  1577. #else
  1578. auto host = "nghttp2.org";
  1579. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1580. #endif
  1581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1582. auto port = 443;
  1583. SSLClient cli(host, port);
  1584. #else
  1585. auto port = 80;
  1586. Client cli(host, port);
  1587. #endif
  1588. {
  1589. auto res = cli.Get(path);
  1590. ASSERT_TRUE(res);
  1591. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1592. }
  1593. {
  1594. auto res =
  1595. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  1596. ASSERT_TRUE(res);
  1597. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1598. remove_whitespace(res->body));
  1599. EXPECT_EQ(StatusCode::OK_200, res->status);
  1600. }
  1601. {
  1602. cli.set_basic_auth("hello", "world");
  1603. auto res = cli.Get(path);
  1604. ASSERT_TRUE(res);
  1605. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1606. remove_whitespace(res->body));
  1607. EXPECT_EQ(StatusCode::OK_200, res->status);
  1608. }
  1609. {
  1610. cli.set_basic_auth("hello", "bad");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1614. }
  1615. {
  1616. cli.set_basic_auth("bad", "world");
  1617. auto res = cli.Get(path);
  1618. ASSERT_TRUE(res);
  1619. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1620. }
  1621. }
  1622. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1623. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1624. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1625. auto host = "httpcan.org";
  1626. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1627. auto paths = std::vector<std::string>{
  1628. "/digest-auth/auth/hello/world/MD5",
  1629. "/digest-auth/auth/hello/world/SHA-256",
  1630. "/digest-auth/auth/hello/world/SHA-512",
  1631. };
  1632. #else
  1633. auto host = "nghttp2.org";
  1634. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/httpbin/digest-auth/auth/hello/world/MD5",
  1637. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1638. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1639. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1640. };
  1641. #endif
  1642. auto port = 443;
  1643. SSLClient cli(host, port);
  1644. {
  1645. auto res = cli.Get(unauth_path);
  1646. ASSERT_TRUE(res);
  1647. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1648. }
  1649. {
  1650. cli.set_digest_auth("hello", "world");
  1651. for (const auto &path : paths) {
  1652. auto res = cli.Get(path.c_str());
  1653. ASSERT_TRUE(res);
  1654. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1655. std::string algo(path.substr(path.rfind('/') + 1));
  1656. EXPECT_EQ(
  1657. remove_whitespace("{\"algorithm\":\"" + algo +
  1658. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1659. remove_whitespace(res->body));
  1660. #else
  1661. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1662. remove_whitespace(res->body));
  1663. #endif
  1664. EXPECT_EQ(StatusCode::OK_200, res->status);
  1665. }
  1666. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1667. cli.set_digest_auth("hello", "bad");
  1668. for (const auto &path : paths) {
  1669. auto res = cli.Get(path.c_str());
  1670. ASSERT_TRUE(res);
  1671. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1672. }
  1673. #endif
  1674. }
  1675. }
  1676. #endif
  1677. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1678. auto host = "google.com";
  1679. auto another_host = "example.com";
  1680. auto wrong_ip = "0.0.0.0";
  1681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1682. SSLClient cli(host);
  1683. #else
  1684. Client cli(host);
  1685. #endif
  1686. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1687. auto res = cli.Get("/");
  1688. ASSERT_TRUE(res);
  1689. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1690. }
  1691. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1692. auto host = "google.com";
  1693. auto wrong_ip = "0.0.0.0";
  1694. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1695. SSLClient cli(host);
  1696. #else
  1697. Client cli(host);
  1698. #endif
  1699. cli.set_hostname_addr_map({{host, wrong_ip}});
  1700. auto res = cli.Get("/");
  1701. ASSERT_TRUE(!res);
  1702. EXPECT_EQ(Error::Connection, res.error());
  1703. }
  1704. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1705. auto host = "nghttp2.org";
  1706. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1707. SSLClient cli(host);
  1708. #else
  1709. Client cli(host);
  1710. #endif
  1711. cli.set_follow_location(true);
  1712. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1713. ASSERT_TRUE(res);
  1714. EXPECT_EQ(StatusCode::OK_200, res->status);
  1715. }
  1716. TEST(RedirectTest, Redirect_Online) {
  1717. auto host = "nghttp2.org";
  1718. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1719. SSLClient cli(host);
  1720. #else
  1721. Client cli(host);
  1722. #endif
  1723. cli.set_follow_location(true);
  1724. auto res = cli.Get("/httpbin/redirect/3");
  1725. ASSERT_TRUE(res);
  1726. EXPECT_EQ(StatusCode::OK_200, res->status);
  1727. }
  1728. TEST(RelativeRedirectTest, Redirect_Online) {
  1729. auto host = "nghttp2.org";
  1730. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1731. SSLClient cli(host);
  1732. #else
  1733. Client cli(host);
  1734. #endif
  1735. cli.set_follow_location(true);
  1736. auto res = cli.Get("/httpbin/relative-redirect/3");
  1737. ASSERT_TRUE(res);
  1738. EXPECT_EQ(StatusCode::OK_200, res->status);
  1739. }
  1740. TEST(TooManyRedirectTest, Redirect_Online) {
  1741. auto host = "nghttp2.org";
  1742. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1743. SSLClient cli(host);
  1744. #else
  1745. Client cli(host);
  1746. #endif
  1747. cli.set_follow_location(true);
  1748. auto res = cli.Get("/httpbin/redirect/21");
  1749. ASSERT_TRUE(!res);
  1750. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1751. }
  1752. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1753. TEST(YahooRedirectTest, Redirect_Online) {
  1754. Client cli("yahoo.com");
  1755. auto res = cli.Get("/");
  1756. ASSERT_TRUE(res);
  1757. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1758. cli.set_follow_location(true);
  1759. res = cli.Get("/");
  1760. ASSERT_TRUE(res);
  1761. EXPECT_EQ(StatusCode::OK_200, res->status);
  1762. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1763. }
  1764. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1765. #define REDIR_HOST "httpbingo.org"
  1766. #define REDIR_PATH "/redirect-to"
  1767. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1768. SSLClient cli(REDIR_HOST);
  1769. cli.set_follow_location(true);
  1770. auto res =
  1771. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1772. ASSERT_TRUE(res);
  1773. EXPECT_EQ(StatusCode::OK_200, res->status);
  1774. }
  1775. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. Params params;
  1779. params.emplace("url", "http://example.com");
  1780. params.emplace("status_code", "302");
  1781. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1782. ASSERT_TRUE(res);
  1783. EXPECT_EQ(StatusCode::OK_200, res->status);
  1784. }
  1785. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1786. SSLClient cli(REDIR_HOST);
  1787. cli.set_follow_location(true);
  1788. Params params;
  1789. params.emplace("url", "http://example.com");
  1790. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1791. ASSERT_TRUE(res);
  1792. EXPECT_EQ(StatusCode::OK_200, res->status);
  1793. }
  1794. TEST(UrlWithSpace, Redirect_Online) {
  1795. SSLClient cli("edge.forgecdn.net");
  1796. cli.set_follow_location(true);
  1797. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1798. ASSERT_TRUE(res);
  1799. EXPECT_EQ(StatusCode::OK_200, res->status);
  1800. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1801. }
  1802. #endif
  1803. #if !defined(_WIN32) && !defined(_WIN64)
  1804. TEST(ReceiveSignals, Signal) {
  1805. auto setupSignalHandlers = []() {
  1806. struct sigaction act;
  1807. sigemptyset(&act.sa_mask);
  1808. act.sa_flags = SA_SIGINFO;
  1809. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1810. switch (sig) {
  1811. case SIGINT:
  1812. default: break;
  1813. }
  1814. };
  1815. ::sigaction(SIGINT, &act, nullptr);
  1816. };
  1817. Server svr;
  1818. int port = 0;
  1819. auto thread = std::thread([&]() {
  1820. setupSignalHandlers();
  1821. port = svr.bind_to_any_port(HOST);
  1822. svr.listen_after_bind();
  1823. });
  1824. auto se = detail::scope_exit([&] {
  1825. svr.stop();
  1826. thread.join();
  1827. ASSERT_FALSE(svr.is_running());
  1828. });
  1829. svr.wait_until_ready();
  1830. ASSERT_TRUE(svr.is_running());
  1831. pthread_kill(thread.native_handle(), SIGINT);
  1832. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1833. ASSERT_TRUE(svr.is_running());
  1834. }
  1835. #endif
  1836. TEST(RedirectToDifferentPort, Redirect) {
  1837. Server svr1;
  1838. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1839. res.set_content("Hello World!", "text/plain");
  1840. });
  1841. int svr1_port = 0;
  1842. auto thread1 = std::thread([&]() {
  1843. svr1_port = svr1.bind_to_any_port(HOST);
  1844. svr1.listen_after_bind();
  1845. });
  1846. Server svr2;
  1847. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1848. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1849. });
  1850. int svr2_port = 0;
  1851. auto thread2 = std::thread([&]() {
  1852. svr2_port = svr2.bind_to_any_port(HOST);
  1853. svr2.listen_after_bind();
  1854. });
  1855. auto se = detail::scope_exit([&] {
  1856. svr2.stop();
  1857. thread2.join();
  1858. svr1.stop();
  1859. thread1.join();
  1860. ASSERT_FALSE(svr2.is_running());
  1861. ASSERT_FALSE(svr1.is_running());
  1862. });
  1863. svr1.wait_until_ready();
  1864. svr2.wait_until_ready();
  1865. Client cli("localhost", svr2_port);
  1866. cli.set_follow_location(true);
  1867. auto res = cli.Get("/2");
  1868. ASSERT_TRUE(res);
  1869. EXPECT_EQ(StatusCode::OK_200, res->status);
  1870. EXPECT_EQ("Hello World!", res->body);
  1871. }
  1872. TEST(RedirectFromPageWithContent, Redirect) {
  1873. Server svr;
  1874. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1875. res.set_content("___", "text/plain");
  1876. res.set_redirect("/2");
  1877. });
  1878. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1879. res.set_content("Hello World!", "text/plain");
  1880. });
  1881. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. th.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. {
  1889. Client cli("localhost", PORT);
  1890. cli.set_follow_location(true);
  1891. std::string body;
  1892. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1893. body.append(data, data_length);
  1894. return true;
  1895. });
  1896. ASSERT_TRUE(res);
  1897. EXPECT_EQ(StatusCode::OK_200, res->status);
  1898. EXPECT_EQ("Hello World!", body);
  1899. }
  1900. {
  1901. Client cli("localhost", PORT);
  1902. std::string body;
  1903. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1904. body.append(data, data_length);
  1905. return true;
  1906. });
  1907. ASSERT_TRUE(res);
  1908. EXPECT_EQ(StatusCode::Found_302, res->status);
  1909. EXPECT_EQ("___", body);
  1910. }
  1911. }
  1912. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1913. Server svr;
  1914. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1915. res.set_content("___", "text/plain");
  1916. // res.set_redirect("/2");
  1917. res.set_redirect("http://[::1]:1234/2");
  1918. });
  1919. svr.Get("/2", [&](const Request &req, Response &res) {
  1920. auto host_header = req.headers.find("Host");
  1921. ASSERT_TRUE(host_header != req.headers.end());
  1922. EXPECT_EQ("[::1]:1234", host_header->second);
  1923. res.set_content("Hello World!", "text/plain");
  1924. });
  1925. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1926. auto se = detail::scope_exit([&] {
  1927. svr.stop();
  1928. th.join();
  1929. ASSERT_FALSE(svr.is_running());
  1930. });
  1931. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1932. // actually starts anything, so the condition !svr.is_running() will
  1933. // always remain true, and the loop never stops.
  1934. // This basically counts how many milliseconds have passed since the
  1935. // call to svr.listen(), and if after 5 seconds nothing started yet
  1936. // aborts the test.
  1937. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1938. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1939. ASSERT_LT(milliseconds, 5000U);
  1940. }
  1941. {
  1942. Client cli("http://[::1]:1234");
  1943. cli.set_follow_location(true);
  1944. std::string body;
  1945. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res);
  1950. EXPECT_EQ(StatusCode::OK_200, res->status);
  1951. EXPECT_EQ("Hello World!", body);
  1952. }
  1953. {
  1954. Client cli("http://[::1]:1234");
  1955. std::string body;
  1956. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1957. body.append(data, data_length);
  1958. return true;
  1959. });
  1960. ASSERT_TRUE(res);
  1961. EXPECT_EQ(StatusCode::Found_302, res->status);
  1962. EXPECT_EQ("___", body);
  1963. }
  1964. }
  1965. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1966. Server svr;
  1967. svr.Get("/foo", [](const Request &req, Response &res) {
  1968. auto a = req.params.find("a");
  1969. if (a != req.params.end()) {
  1970. res.set_content((*a).second, "text/plain");
  1971. res.status = StatusCode::OK_200;
  1972. } else {
  1973. res.status = StatusCode::BadRequest_400;
  1974. }
  1975. });
  1976. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1977. auto se = detail::scope_exit([&] {
  1978. svr.stop();
  1979. thread.join();
  1980. ASSERT_FALSE(svr.is_running());
  1981. });
  1982. svr.wait_until_ready();
  1983. {
  1984. Client cli(HOST, PORT);
  1985. cli.set_path_encode(false);
  1986. auto res = cli.Get("/foo?a=explicitly+encoded");
  1987. ASSERT_TRUE(res);
  1988. EXPECT_EQ(StatusCode::OK_200, res->status);
  1989. // This expects it back with a space, as the `+` won't have been
  1990. // url-encoded, and server-side the params get decoded turning `+`
  1991. // into spaces.
  1992. EXPECT_EQ("explicitly encoded", res->body);
  1993. }
  1994. }
  1995. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  1996. Server svr;
  1997. svr.Get("/", [](const Request &req, Response &) {
  1998. EXPECT_EQ("\x0A", req.get_param_value("something"));
  1999. });
  2000. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2001. auto se = detail::scope_exit([&] {
  2002. svr.stop();
  2003. thread.join();
  2004. ASSERT_FALSE(svr.is_running());
  2005. });
  2006. svr.wait_until_ready();
  2007. {
  2008. Client cli(HOST, PORT);
  2009. cli.set_path_encode(false);
  2010. auto res = cli.Get("/?something=%0A");
  2011. ASSERT_TRUE(res);
  2012. EXPECT_EQ(StatusCode::OK_200, res->status);
  2013. }
  2014. }
  2015. TEST(BindServerTest, DISABLED_BindDualStack) {
  2016. Server svr;
  2017. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2018. res.set_content("Hello World!", "text/plain");
  2019. });
  2020. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2021. auto se = detail::scope_exit([&] {
  2022. svr.stop();
  2023. thread.join();
  2024. ASSERT_FALSE(svr.is_running());
  2025. });
  2026. svr.wait_until_ready();
  2027. {
  2028. Client cli("127.0.0.1", PORT);
  2029. auto res = cli.Get("/1");
  2030. ASSERT_TRUE(res);
  2031. EXPECT_EQ(StatusCode::OK_200, res->status);
  2032. EXPECT_EQ("Hello World!", res->body);
  2033. }
  2034. {
  2035. Client cli("::1", PORT);
  2036. auto res = cli.Get("/1");
  2037. ASSERT_TRUE(res);
  2038. EXPECT_EQ(StatusCode::OK_200, res->status);
  2039. EXPECT_EQ("Hello World!", res->body);
  2040. }
  2041. }
  2042. TEST(BindServerTest, BindAndListenSeparately) {
  2043. Server svr;
  2044. int port = svr.bind_to_any_port("0.0.0.0");
  2045. ASSERT_TRUE(svr.is_valid());
  2046. ASSERT_TRUE(port > 0);
  2047. svr.stop();
  2048. }
  2049. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2050. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2051. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2052. CLIENT_CA_CERT_DIR);
  2053. int port = svr.bind_to_any_port("0.0.0.0");
  2054. ASSERT_TRUE(svr.is_valid());
  2055. ASSERT_TRUE(port > 0);
  2056. svr.stop();
  2057. }
  2058. #endif
  2059. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2060. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2061. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2062. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2063. int port = svr.bind_to_any_port("0.0.0.0");
  2064. ASSERT_TRUE(svr.is_valid());
  2065. ASSERT_TRUE(port > 0);
  2066. svr.stop();
  2067. }
  2068. #endif
  2069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2070. X509 *readCertificate(const std::string &strFileName) {
  2071. std::ifstream inStream(strFileName);
  2072. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2073. std::istreambuf_iterator<char>());
  2074. if (strCertPEM.empty()) return (nullptr);
  2075. BIO *pbCert = BIO_new(BIO_s_mem());
  2076. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2077. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2078. BIO_free(pbCert);
  2079. return (pCert);
  2080. }
  2081. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2082. std::ifstream inStream(strFileName);
  2083. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2084. std::istreambuf_iterator<char>());
  2085. if (strPrivateKeyPEM.empty()) return (nullptr);
  2086. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2087. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2088. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2089. BIO_free(pbPrivKey);
  2090. return (pPrivateKey);
  2091. }
  2092. TEST(BindServerTest, UpdateCerts) {
  2093. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2094. int port = svr.bind_to_any_port("0.0.0.0");
  2095. ASSERT_TRUE(svr.is_valid());
  2096. ASSERT_TRUE(port > 0);
  2097. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2098. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2099. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2100. ASSERT_TRUE(cert != nullptr);
  2101. ASSERT_TRUE(ca_cert != nullptr);
  2102. ASSERT_TRUE(key != nullptr);
  2103. X509_STORE *cert_store = X509_STORE_new();
  2104. X509_STORE_add_cert(cert_store, ca_cert);
  2105. svr.update_certs(cert, key, cert_store);
  2106. ASSERT_TRUE(svr.is_valid());
  2107. svr.stop();
  2108. X509_free(cert);
  2109. X509_free(ca_cert);
  2110. EVP_PKEY_free(key);
  2111. }
  2112. #endif
  2113. TEST(ErrorHandlerTest, ContentLength) {
  2114. Server svr;
  2115. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2116. res.status = StatusCode::OK_200;
  2117. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2118. "text/html"); // <= Content-Length still 13
  2119. });
  2120. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2121. res.set_content("Hello World!\n", "text/plain");
  2122. res.status = 524;
  2123. });
  2124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2125. auto se = detail::scope_exit([&] {
  2126. svr.stop();
  2127. thread.join();
  2128. ASSERT_FALSE(svr.is_running());
  2129. });
  2130. svr.wait_until_ready();
  2131. {
  2132. Client cli(HOST, PORT);
  2133. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2134. ASSERT_TRUE(res);
  2135. EXPECT_EQ(StatusCode::OK_200, res->status);
  2136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2138. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2139. }
  2140. }
  2141. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2142. TEST(ExceptionTest, WithoutExceptionHandler) {
  2143. Server svr;
  2144. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2145. throw std::runtime_error("exception...");
  2146. });
  2147. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2148. throw std::runtime_error("exception\r\n...");
  2149. });
  2150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2151. auto se = detail::scope_exit([&] {
  2152. svr.stop();
  2153. listen_thread.join();
  2154. ASSERT_FALSE(svr.is_running());
  2155. });
  2156. svr.wait_until_ready();
  2157. Client cli("localhost", PORT);
  2158. {
  2159. auto res = cli.Get("/exception");
  2160. ASSERT_TRUE(res);
  2161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2162. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2163. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2164. }
  2165. {
  2166. auto res = cli.Get("/unknown");
  2167. ASSERT_TRUE(res);
  2168. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2169. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2170. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2171. }
  2172. }
  2173. TEST(ExceptionTest, WithExceptionHandler) {
  2174. Server svr;
  2175. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2176. std::exception_ptr ep) {
  2177. EXPECT_FALSE(ep == nullptr);
  2178. try {
  2179. std::rethrow_exception(ep);
  2180. } catch (std::exception &e) {
  2181. EXPECT_EQ("abc", std::string(e.what()));
  2182. } catch (...) {}
  2183. res.status = StatusCode::InternalServerError_500;
  2184. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2185. "text/html"); // <= Content-Length still 13 at this point
  2186. });
  2187. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2188. res.set_content("Hello World!\n", "text/plain");
  2189. throw std::runtime_error("abc");
  2190. });
  2191. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2192. auto se = detail::scope_exit([&] {
  2193. svr.stop();
  2194. thread.join();
  2195. ASSERT_FALSE(svr.is_running());
  2196. });
  2197. svr.wait_until_ready();
  2198. for (size_t i = 0; i < 10; i++) {
  2199. Client cli(HOST, PORT);
  2200. for (size_t j = 0; j < 100; j++) {
  2201. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2202. ASSERT_TRUE(res);
  2203. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2205. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2206. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2207. }
  2208. cli.set_keep_alive(true);
  2209. for (size_t j = 0; j < 100; j++) {
  2210. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2211. ASSERT_TRUE(res);
  2212. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2213. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2214. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2215. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2216. }
  2217. }
  2218. }
  2219. TEST(ExceptionTest, AndErrorHandler) {
  2220. Server svr;
  2221. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2222. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2223. });
  2224. svr.set_exception_handler(
  2225. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2226. EXPECT_FALSE(ep == nullptr);
  2227. try {
  2228. std::rethrow_exception(ep);
  2229. } catch (std::exception &e) {
  2230. res.set_content(e.what(), "text/html");
  2231. } catch (...) {}
  2232. res.status = StatusCode::InternalServerError_500;
  2233. });
  2234. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2235. throw std::runtime_error("EXCEPTION");
  2236. });
  2237. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2238. res.set_content("ERROR", "text/html");
  2239. res.status = StatusCode::InternalServerError_500;
  2240. });
  2241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2242. auto se = detail::scope_exit([&] {
  2243. svr.stop();
  2244. thread.join();
  2245. ASSERT_FALSE(svr.is_running());
  2246. });
  2247. svr.wait_until_ready();
  2248. Client cli(HOST, PORT);
  2249. {
  2250. auto res = cli.Get("/exception");
  2251. ASSERT_TRUE(res);
  2252. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2253. EXPECT_EQ("EXCEPTION", res->body);
  2254. }
  2255. {
  2256. auto res = cli.Get("/error");
  2257. ASSERT_TRUE(res);
  2258. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2259. EXPECT_EQ("ERROR", res->body);
  2260. }
  2261. {
  2262. auto res = cli.Get("/invalid");
  2263. ASSERT_TRUE(res);
  2264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2265. EXPECT_EQ("NOT_FOUND", res->body);
  2266. }
  2267. }
  2268. #endif
  2269. TEST(NoContentTest, ContentLength) {
  2270. Server svr;
  2271. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2272. res.status = StatusCode::NoContent_204;
  2273. });
  2274. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2275. auto se = detail::scope_exit([&] {
  2276. svr.stop();
  2277. thread.join();
  2278. ASSERT_FALSE(svr.is_running());
  2279. });
  2280. svr.wait_until_ready();
  2281. {
  2282. Client cli(HOST, PORT);
  2283. auto res = cli.Get("/hi");
  2284. ASSERT_TRUE(res);
  2285. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2286. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2287. }
  2288. }
  2289. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2290. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2292. ASSERT_TRUE(svr.is_valid());
  2293. #else
  2294. Server svr;
  2295. #endif
  2296. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2297. if (req.path == "/routing_handler") {
  2298. res.set_header("PRE_ROUTING", "on");
  2299. res.set_content("Routing Handler", "text/plain");
  2300. return httplib::Server::HandlerResponse::Handled;
  2301. }
  2302. return httplib::Server::HandlerResponse::Unhandled;
  2303. });
  2304. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2305. res.set_content("Error", "text/html");
  2306. });
  2307. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2308. if (req.path == "/routing_handler") {
  2309. res.set_header("POST_ROUTING", "on");
  2310. }
  2311. });
  2312. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2313. res.set_content("Hello World!\n", "text/plain");
  2314. });
  2315. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2316. auto se = detail::scope_exit([&] {
  2317. svr.stop();
  2318. thread.join();
  2319. ASSERT_FALSE(svr.is_running());
  2320. });
  2321. svr.wait_until_ready();
  2322. {
  2323. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2324. SSLClient cli(HOST, PORT);
  2325. cli.enable_server_certificate_verification(false);
  2326. #else
  2327. Client cli(HOST, PORT);
  2328. #endif
  2329. auto res = cli.Get("/routing_handler");
  2330. ASSERT_TRUE(res);
  2331. EXPECT_EQ(StatusCode::OK_200, res->status);
  2332. EXPECT_EQ("Routing Handler", res->body);
  2333. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2334. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2335. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2336. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2337. }
  2338. {
  2339. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2340. SSLClient cli(HOST, PORT);
  2341. cli.enable_server_certificate_verification(false);
  2342. #else
  2343. Client cli(HOST, PORT);
  2344. #endif
  2345. auto res = cli.Get("/hi");
  2346. ASSERT_TRUE(res);
  2347. EXPECT_EQ(StatusCode::OK_200, res->status);
  2348. EXPECT_EQ("Hello World!\n", res->body);
  2349. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2350. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2351. }
  2352. {
  2353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2354. SSLClient cli(HOST, PORT);
  2355. cli.enable_server_certificate_verification(false);
  2356. #else
  2357. Client cli(HOST, PORT);
  2358. #endif
  2359. auto res = cli.Get("/aaa");
  2360. ASSERT_TRUE(res);
  2361. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2362. EXPECT_EQ("Error", res->body);
  2363. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2364. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2365. }
  2366. }
  2367. TEST(RequestHandlerTest, PreRequestHandler) {
  2368. auto route_path = "/user/:user";
  2369. Server svr;
  2370. svr.Get("/hi", [](const Request &, Response &res) {
  2371. res.set_content("hi", "text/plain");
  2372. });
  2373. svr.Get(route_path, [](const Request &req, Response &res) {
  2374. res.set_content(req.path_params.at("user"), "text/plain");
  2375. });
  2376. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2377. if (req.matched_route == route_path) {
  2378. auto user = req.path_params.at("user");
  2379. if (user != "john") {
  2380. res.status = StatusCode::Forbidden_403;
  2381. res.set_content("error", "text/html");
  2382. return Server::HandlerResponse::Handled;
  2383. }
  2384. }
  2385. return Server::HandlerResponse::Unhandled;
  2386. });
  2387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2388. auto se = detail::scope_exit([&] {
  2389. svr.stop();
  2390. thread.join();
  2391. ASSERT_FALSE(svr.is_running());
  2392. });
  2393. svr.wait_until_ready();
  2394. Client cli(HOST, PORT);
  2395. {
  2396. auto res = cli.Get("/hi");
  2397. ASSERT_TRUE(res);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ("hi", res->body);
  2400. }
  2401. {
  2402. auto res = cli.Get("/user/john");
  2403. ASSERT_TRUE(res);
  2404. EXPECT_EQ(StatusCode::OK_200, res->status);
  2405. EXPECT_EQ("john", res->body);
  2406. }
  2407. {
  2408. auto res = cli.Get("/user/invalid-user");
  2409. ASSERT_TRUE(res);
  2410. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2411. EXPECT_EQ("error", res->body);
  2412. }
  2413. }
  2414. TEST(InvalidFormatTest, StatusCode) {
  2415. Server svr;
  2416. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2417. res.set_content("Hello World!\n", "text/plain");
  2418. res.status = 9999; // Status should be a three-digit code...
  2419. });
  2420. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2421. auto se = detail::scope_exit([&] {
  2422. svr.stop();
  2423. thread.join();
  2424. ASSERT_FALSE(svr.is_running());
  2425. });
  2426. svr.wait_until_ready();
  2427. {
  2428. Client cli(HOST, PORT);
  2429. auto res = cli.Get("/hi");
  2430. ASSERT_FALSE(res);
  2431. }
  2432. }
  2433. TEST(URLFragmentTest, WithFragment) {
  2434. Server svr;
  2435. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2436. EXPECT_TRUE(req.target == "/hi");
  2437. });
  2438. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. thread.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. {
  2446. Client cli(HOST, PORT);
  2447. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2448. EXPECT_TRUE(res);
  2449. EXPECT_EQ(StatusCode::OK_200, res->status);
  2450. res = cli.Get("/hi%23key1=val1=key2=val2");
  2451. EXPECT_TRUE(res);
  2452. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2453. }
  2454. }
  2455. TEST(HeaderWriter, SetHeaderWriter) {
  2456. Server svr;
  2457. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2458. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2459. return detail::write_headers(strm, hdrs);
  2460. });
  2461. svr.Get("/hi", [](const Request &req, Response &res) {
  2462. auto it = req.headers.find("CustomClientHeader");
  2463. EXPECT_TRUE(it != req.headers.end());
  2464. EXPECT_EQ(it->second, "CustomClientValue");
  2465. res.set_content("Hello World!\n", "text/plain");
  2466. });
  2467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2468. auto se = detail::scope_exit([&] {
  2469. svr.stop();
  2470. thread.join();
  2471. ASSERT_FALSE(svr.is_running());
  2472. });
  2473. svr.wait_until_ready();
  2474. {
  2475. Client cli(HOST, PORT);
  2476. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2477. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2478. return detail::write_headers(strm, hdrs);
  2479. });
  2480. auto res = cli.Get("/hi");
  2481. EXPECT_TRUE(res);
  2482. EXPECT_EQ(StatusCode::OK_200, res->status);
  2483. auto it = res->headers.find("CustomServerHeader");
  2484. EXPECT_TRUE(it != res->headers.end());
  2485. EXPECT_EQ(it->second, "CustomServerValue");
  2486. }
  2487. }
  2488. class ServerTest : public ::testing::Test {
  2489. protected:
  2490. ServerTest()
  2491. : cli_(HOST, PORT)
  2492. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2493. ,
  2494. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2495. #endif
  2496. {
  2497. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2498. cli_.enable_server_certificate_verification(false);
  2499. #endif
  2500. }
  2501. virtual void SetUp() {
  2502. svr_.set_mount_point("/", "./www");
  2503. svr_.set_mount_point("/mount", "./www2");
  2504. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2505. svr_.Get("/hi",
  2506. [&](const Request & /*req*/, Response &res) {
  2507. res.set_content("Hello World!", "text/plain");
  2508. })
  2509. .Get("/file_content",
  2510. [&](const Request & /*req*/, Response &res) {
  2511. res.set_file_content("./www/dir/test.html");
  2512. })
  2513. .Get("/file_content_with_content_type",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_file_content("./www/file", "text/plain");
  2516. })
  2517. .Get("/invalid_file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/invalid_file_path");
  2520. })
  2521. .Get("/http_response_splitting",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2524. EXPECT_EQ(0U, res.headers.size());
  2525. EXPECT_FALSE(res.has_header("a"));
  2526. res.set_header("a", "1\nSet-Cookie: a=1");
  2527. EXPECT_EQ(0U, res.headers.size());
  2528. EXPECT_FALSE(res.has_header("a"));
  2529. res.set_header("a", "1\rSet-Cookie: a=1");
  2530. EXPECT_EQ(0U, res.headers.size());
  2531. EXPECT_FALSE(res.has_header("a"));
  2532. res.set_header("a\r\nb", "0");
  2533. EXPECT_EQ(0U, res.headers.size());
  2534. EXPECT_FALSE(res.has_header("a"));
  2535. res.set_header("a\rb", "0");
  2536. EXPECT_EQ(0U, res.headers.size());
  2537. EXPECT_FALSE(res.has_header("a"));
  2538. res.set_header("a\nb", "0");
  2539. EXPECT_EQ(0U, res.headers.size());
  2540. EXPECT_FALSE(res.has_header("a"));
  2541. res.set_redirect("1\r\nSet-Cookie: a=1");
  2542. EXPECT_EQ(0U, res.headers.size());
  2543. EXPECT_FALSE(res.has_header("Location"));
  2544. })
  2545. .Get("/slow",
  2546. [&](const Request & /*req*/, Response &res) {
  2547. std::this_thread::sleep_for(std::chrono::seconds(2));
  2548. res.set_content("slow", "text/plain");
  2549. })
  2550. #if 0
  2551. .Post("/slowpost",
  2552. [&](const Request & /*req*/, Response &res) {
  2553. std::this_thread::sleep_for(std::chrono::seconds(2));
  2554. res.set_content("slow", "text/plain");
  2555. })
  2556. #endif
  2557. .Get("/remote_addr",
  2558. [&](const Request &req, Response &res) {
  2559. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2560. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2561. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2562. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2563. res.set_content(req.remote_addr, "text/plain");
  2564. })
  2565. .Get("/local_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2568. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2571. auto local_addr = req.local_addr;
  2572. auto local_port = std::to_string(req.local_port);
  2573. res.set_content(local_addr.append(":").append(local_port),
  2574. "text/plain");
  2575. })
  2576. .Get("/endwith%",
  2577. [&](const Request & /*req*/, Response &res) {
  2578. res.set_content("Hello World!", "text/plain");
  2579. })
  2580. .Get("/a\\+\\+b",
  2581. [&](const Request &req, Response &res) {
  2582. ASSERT_TRUE(req.has_param("a +b"));
  2583. auto val = req.get_param_value("a +b");
  2584. res.set_content(val, "text/plain");
  2585. })
  2586. .Get("/", [&](const Request & /*req*/,
  2587. Response &res) { res.set_redirect("/hi"); })
  2588. .Post("/1",
  2589. [](const Request & /*req*/, Response &res) {
  2590. res.set_redirect("/2", StatusCode::SeeOther_303);
  2591. })
  2592. .Get("/2",
  2593. [](const Request & /*req*/, Response &res) {
  2594. res.set_content("redirected.", "text/plain");
  2595. res.status = StatusCode::OK_200;
  2596. })
  2597. .Post("/person",
  2598. [&](const Request &req, Response &res) {
  2599. if (req.has_param("name") && req.has_param("note")) {
  2600. persons_[req.get_param_value("name")] =
  2601. req.get_param_value("note");
  2602. } else {
  2603. res.status = StatusCode::BadRequest_400;
  2604. }
  2605. })
  2606. .Put("/person",
  2607. [&](const Request &req, Response &res) {
  2608. if (req.has_param("name") && req.has_param("note")) {
  2609. persons_[req.get_param_value("name")] =
  2610. req.get_param_value("note");
  2611. } else {
  2612. res.status = StatusCode::BadRequest_400;
  2613. }
  2614. })
  2615. .Get("/person/(.*)",
  2616. [&](const Request &req, Response &res) {
  2617. string name = req.matches[1];
  2618. if (persons_.find(name) != persons_.end()) {
  2619. auto note = persons_[name];
  2620. res.set_content(note, "text/plain");
  2621. } else {
  2622. res.status = StatusCode::NotFound_404;
  2623. }
  2624. })
  2625. .Delete("/person",
  2626. [&](const Request &req, Response &res) {
  2627. if (req.has_param("name")) {
  2628. string name = req.get_param_value("name");
  2629. if (persons_.find(name) != persons_.end()) {
  2630. persons_.erase(name);
  2631. res.set_content("DELETED", "text/plain");
  2632. } else {
  2633. res.status = StatusCode::NotFound_404;
  2634. }
  2635. } else {
  2636. res.status = StatusCode::BadRequest_400;
  2637. }
  2638. })
  2639. .Post("/x-www-form-urlencoded-json",
  2640. [&](const Request &req, Response &res) {
  2641. auto json = req.get_param_value("json");
  2642. ASSERT_EQ(JSON_DATA, json);
  2643. res.set_content(json, "appliation/json");
  2644. res.status = StatusCode::OK_200;
  2645. })
  2646. .Get("/streamed-chunked",
  2647. [&](const Request & /*req*/, Response &res) {
  2648. res.set_chunked_content_provider(
  2649. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2650. sink.os << "123";
  2651. sink.os << "456";
  2652. sink.os << "789";
  2653. sink.done();
  2654. return true;
  2655. });
  2656. })
  2657. .Get("/streamed-chunked-with-prohibited-trailer",
  2658. [&](const Request & /*req*/, Response &res) {
  2659. auto i = new int(0);
  2660. // Declare both a prohibited trailer (Content-Length) and an
  2661. // allowed one
  2662. res.set_header("Trailer", "Content-Length, X-Allowed");
  2663. res.set_chunked_content_provider(
  2664. "text/plain",
  2665. [i](size_t /*offset*/, DataSink &sink) {
  2666. switch (*i) {
  2667. case 0: sink.os << "123"; break;
  2668. case 1: sink.os << "456"; break;
  2669. case 2: sink.os << "789"; break;
  2670. case 3: {
  2671. sink.done_with_trailer(
  2672. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2673. } break;
  2674. }
  2675. (*i)++;
  2676. return true;
  2677. },
  2678. [i](bool success) {
  2679. EXPECT_TRUE(success);
  2680. delete i;
  2681. });
  2682. })
  2683. .Get("/streamed-chunked2",
  2684. [&](const Request & /*req*/, Response &res) {
  2685. auto i = new int(0);
  2686. res.set_chunked_content_provider(
  2687. "text/plain",
  2688. [i](size_t /*offset*/, DataSink &sink) {
  2689. switch (*i) {
  2690. case 0: sink.os << "123"; break;
  2691. case 1: sink.os << "456"; break;
  2692. case 2: sink.os << "789"; break;
  2693. case 3: sink.done(); break;
  2694. }
  2695. (*i)++;
  2696. return true;
  2697. },
  2698. [i](bool success) {
  2699. EXPECT_TRUE(success);
  2700. delete i;
  2701. });
  2702. })
  2703. .Get("/streamed-chunked-with-trailer",
  2704. [&](const Request & /*req*/, Response &res) {
  2705. auto i = new int(0);
  2706. res.set_header("Trailer", "Dummy1, Dummy2");
  2707. res.set_chunked_content_provider(
  2708. "text/plain",
  2709. [i](size_t /*offset*/, DataSink &sink) {
  2710. switch (*i) {
  2711. case 0: sink.os << "123"; break;
  2712. case 1: sink.os << "456"; break;
  2713. case 2: sink.os << "789"; break;
  2714. case 3: {
  2715. sink.done_with_trailer(
  2716. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2717. } break;
  2718. }
  2719. (*i)++;
  2720. return true;
  2721. },
  2722. [i](bool success) {
  2723. EXPECT_TRUE(success);
  2724. delete i;
  2725. });
  2726. })
  2727. .Get("/streamed",
  2728. [&](const Request & /*req*/, Response &res) {
  2729. res.set_content_provider(
  2730. 6, "text/plain",
  2731. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2732. sink.os << (offset < 3 ? "a" : "b");
  2733. return true;
  2734. });
  2735. })
  2736. .Get("/streamed-with-range",
  2737. [&](const Request &req, Response &res) {
  2738. auto data = new std::string("abcdefg");
  2739. res.set_content_provider(
  2740. data->size(), "text/plain",
  2741. [data](size_t offset, size_t length, DataSink &sink) {
  2742. size_t DATA_CHUNK_SIZE = 4;
  2743. const auto &d = *data;
  2744. auto out_len =
  2745. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2746. auto ret =
  2747. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2748. EXPECT_TRUE(ret);
  2749. return true;
  2750. },
  2751. [data, &req](bool success) {
  2752. EXPECT_EQ(success, !req.has_param("error"));
  2753. delete data;
  2754. });
  2755. })
  2756. .Get("/streamed-cancel",
  2757. [&](const Request & /*req*/, Response &res) {
  2758. res.set_content_provider(
  2759. size_t(-1), "text/plain",
  2760. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2761. sink.os << "data_chunk";
  2762. return true;
  2763. });
  2764. })
  2765. .Get("/regex-with-delimiter",
  2766. [&](const Request &req, Response & /*res*/) {
  2767. ASSERT_TRUE(req.has_param("key"));
  2768. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2769. })
  2770. .Get("/with-range",
  2771. [&](const Request & /*req*/, Response &res) {
  2772. res.set_content("abcdefg", "text/plain");
  2773. })
  2774. .Get("/test-start-time",
  2775. [&](const Request &req, Response & /*res*/) {
  2776. EXPECT_NE(req.start_time_,
  2777. std::chrono::steady_clock::time_point::min());
  2778. })
  2779. .Get("/with-range-customized-response",
  2780. [&](const Request & /*req*/, Response &res) {
  2781. res.status = StatusCode::BadRequest_400;
  2782. res.set_content(JSON_DATA, "application/json");
  2783. })
  2784. .Post("/chunked",
  2785. [&](const Request &req, Response & /*res*/) {
  2786. EXPECT_EQ(req.body, "dechunked post body");
  2787. })
  2788. .Post("/large-chunked",
  2789. [&](const Request &req, Response & /*res*/) {
  2790. std::string expected(6 * 30 * 1024u, 'a');
  2791. EXPECT_EQ(req.body, expected);
  2792. })
  2793. .Post("/multipart",
  2794. [&](const Request &req, Response & /*res*/) {
  2795. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2796. req.form.get_field_count("text2") +
  2797. req.form.get_field_count("file3") +
  2798. req.form.get_field_count("file4"));
  2799. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2800. req.form.get_file_count("file2"));
  2801. ASSERT_TRUE(!req.form.has_file("???"));
  2802. ASSERT_TRUE(!req.form.has_field("???"));
  2803. ASSERT_TRUE(req.body.empty());
  2804. {
  2805. const auto &text = req.form.get_field("text1");
  2806. EXPECT_EQ("text default", text);
  2807. }
  2808. {
  2809. const auto &text = req.form.get_field("text2");
  2810. EXPECT_EQ("aωb", text);
  2811. }
  2812. {
  2813. const auto &file = req.form.get_file("file1");
  2814. EXPECT_EQ("hello.txt", file.filename);
  2815. EXPECT_EQ("text/plain", file.content_type);
  2816. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2817. }
  2818. {
  2819. const auto &file = req.form.get_file("file2");
  2820. EXPECT_EQ("world.json", file.filename);
  2821. EXPECT_EQ("application/json", file.content_type);
  2822. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2823. }
  2824. {
  2825. const auto &text = req.form.get_field("file3");
  2826. EXPECT_EQ(0u, text.size());
  2827. }
  2828. {
  2829. const auto &text = req.form.get_field("file4");
  2830. EXPECT_EQ(0u, text.size());
  2831. }
  2832. })
  2833. .Post("/multipart/multi_file_values",
  2834. [&](const Request &req, Response & /*res*/) {
  2835. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2836. req.form.get_field_count("multi_text1"));
  2837. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2838. ASSERT_TRUE(!req.form.has_file("???"));
  2839. ASSERT_TRUE(!req.form.has_field("???"));
  2840. ASSERT_TRUE(req.body.empty());
  2841. {
  2842. const auto &text = req.form.get_field("text");
  2843. EXPECT_EQ("default text", text);
  2844. }
  2845. {
  2846. const auto &text1_values = req.form.get_fields("multi_text1");
  2847. EXPECT_EQ(2u, text1_values.size());
  2848. EXPECT_EQ("aaaaa", text1_values[0]);
  2849. EXPECT_EQ("bbbbb", text1_values[1]);
  2850. }
  2851. {
  2852. const auto &file1_values = req.form.get_files("multi_file1");
  2853. EXPECT_EQ(2u, file1_values.size());
  2854. auto file1 = file1_values[0];
  2855. EXPECT_EQ(file1.filename, "hello.txt");
  2856. EXPECT_EQ(file1.content_type, "text/plain");
  2857. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2858. auto file2 = file1_values[1];
  2859. EXPECT_EQ(file2.filename, "world.json");
  2860. EXPECT_EQ(file2.content_type, "application/json");
  2861. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2862. }
  2863. })
  2864. .Post("/empty",
  2865. [&](const Request &req, Response &res) {
  2866. EXPECT_EQ(req.body, "");
  2867. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2869. res.set_content("empty", "text/plain");
  2870. })
  2871. .Post("/empty-no-content-type",
  2872. [&](const Request &req, Response &res) {
  2873. EXPECT_EQ(req.body, "");
  2874. EXPECT_FALSE(req.has_header("Content-Type"));
  2875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2876. res.set_content("empty-no-content-type", "text/plain");
  2877. })
  2878. .Post("/path-only",
  2879. [&](const Request &req, Response &res) {
  2880. EXPECT_EQ(req.body, "");
  2881. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2882. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2883. res.set_content("path-only", "text/plain");
  2884. })
  2885. .Post("/path-headers-only",
  2886. [&](const Request &req, Response &res) {
  2887. EXPECT_EQ(req.body, "");
  2888. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2889. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2890. EXPECT_EQ("world", req.get_header_value("hello"));
  2891. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2892. res.set_content("path-headers-only", "text/plain");
  2893. })
  2894. .Post("/post-large",
  2895. [&](const Request &req, Response &res) {
  2896. EXPECT_EQ(req.body, LARGE_DATA);
  2897. res.set_content(req.body, "text/plain");
  2898. })
  2899. .Post("/post-loopback",
  2900. [&](const Request &, Response &res,
  2901. ContentReader const &content_reader) {
  2902. std::string body;
  2903. content_reader([&](const char *data, size_t data_length) {
  2904. body.append(data, data_length);
  2905. return true;
  2906. });
  2907. res.set_content(body, "text/plain");
  2908. })
  2909. .Put("/put-loopback",
  2910. [&](const Request &, Response &res,
  2911. ContentReader const &content_reader) {
  2912. std::string body;
  2913. content_reader([&](const char *data, size_t data_length) {
  2914. body.append(data, data_length);
  2915. return true;
  2916. });
  2917. res.set_content(body, "text/plain");
  2918. })
  2919. .Patch("/patch-loopback",
  2920. [&](const Request &, Response &res,
  2921. ContentReader const &content_reader) {
  2922. std::string body;
  2923. content_reader([&](const char *data, size_t data_length) {
  2924. body.append(data, data_length);
  2925. return true;
  2926. });
  2927. res.set_content(body, "text/plain");
  2928. })
  2929. .Put("/empty-no-content-type",
  2930. [&](const Request &req, Response &res) {
  2931. EXPECT_EQ(req.body, "");
  2932. EXPECT_FALSE(req.has_header("Content-Type"));
  2933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2934. res.set_content("empty-no-content-type", "text/plain");
  2935. })
  2936. .Put("/put",
  2937. [&](const Request &req, Response &res) {
  2938. EXPECT_EQ(req.body, "PUT");
  2939. res.set_content(req.body, "text/plain");
  2940. })
  2941. .Put("/put-large",
  2942. [&](const Request &req, Response &res) {
  2943. EXPECT_EQ(req.body, LARGE_DATA);
  2944. res.set_content(req.body, "text/plain");
  2945. })
  2946. .Patch("/patch",
  2947. [&](const Request &req, Response &res) {
  2948. EXPECT_EQ(req.body, "PATCH");
  2949. res.set_content(req.body, "text/plain");
  2950. })
  2951. .Delete("/delete",
  2952. [&](const Request & /*req*/, Response &res) {
  2953. res.set_content("DELETE", "text/plain");
  2954. })
  2955. .Delete("/delete-body",
  2956. [&](const Request &req, Response &res) {
  2957. EXPECT_EQ(req.body, "content");
  2958. res.set_content(req.body, "text/plain");
  2959. })
  2960. .Options(R"(\*)",
  2961. [&](const Request & /*req*/, Response &res) {
  2962. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2963. })
  2964. .Get("/request-target",
  2965. [&](const Request &req, Response & /*res*/) {
  2966. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2967. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2968. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2969. })
  2970. .Get("/long-query-value",
  2971. [&](const Request &req, Response & /*res*/) {
  2972. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2973. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2974. })
  2975. .Get("/too-long-query-value",
  2976. [&](const Request &req, Response & /*res*/) {
  2977. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2978. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2979. })
  2980. .Get("/array-param",
  2981. [&](const Request &req, Response & /*res*/) {
  2982. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2983. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2984. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2985. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2986. })
  2987. .Post("/validate-no-multiple-headers",
  2988. [&](const Request &req, Response & /*res*/) {
  2989. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2990. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2991. })
  2992. .Post("/content_receiver",
  2993. [&](const Request &req, Response &res,
  2994. const ContentReader &content_reader) {
  2995. if (req.is_multipart_form_data()) {
  2996. std::vector<FormData> items;
  2997. content_reader(
  2998. [&](const FormData &file) {
  2999. items.push_back(file);
  3000. return true;
  3001. },
  3002. [&](const char *data, size_t data_length) {
  3003. items.back().content.append(data, data_length);
  3004. return true;
  3005. });
  3006. EXPECT_EQ(5u, items.size());
  3007. {
  3008. const auto &file = get_file_value(items, "text1");
  3009. EXPECT_TRUE(file.filename.empty());
  3010. EXPECT_EQ("text default", file.content);
  3011. }
  3012. {
  3013. const auto &file = get_file_value(items, "text2");
  3014. EXPECT_TRUE(file.filename.empty());
  3015. EXPECT_EQ("aωb", file.content);
  3016. }
  3017. {
  3018. const auto &file = get_file_value(items, "file1");
  3019. EXPECT_EQ("hello.txt", file.filename);
  3020. EXPECT_EQ("text/plain", file.content_type);
  3021. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3022. }
  3023. {
  3024. const auto &file = get_file_value(items, "file2");
  3025. EXPECT_EQ("world.json", file.filename);
  3026. EXPECT_EQ("application/json", file.content_type);
  3027. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3028. }
  3029. {
  3030. const auto &file = get_file_value(items, "file3");
  3031. EXPECT_TRUE(file.filename.empty());
  3032. EXPECT_EQ("application/octet-stream", file.content_type);
  3033. EXPECT_EQ(0u, file.content.size());
  3034. }
  3035. } else {
  3036. std::string body;
  3037. content_reader([&](const char *data, size_t data_length) {
  3038. EXPECT_EQ(7U, data_length);
  3039. body.append(data, data_length);
  3040. return true;
  3041. });
  3042. EXPECT_EQ(body, "content");
  3043. res.set_content(body, "text/plain");
  3044. }
  3045. })
  3046. .Put("/content_receiver",
  3047. [&](const Request & /*req*/, Response &res,
  3048. const ContentReader &content_reader) {
  3049. std::string body;
  3050. content_reader([&](const char *data, size_t data_length) {
  3051. body.append(data, data_length);
  3052. return true;
  3053. });
  3054. EXPECT_EQ(body, "content");
  3055. res.set_content(body, "text/plain");
  3056. })
  3057. .Patch("/content_receiver",
  3058. [&](const Request & /*req*/, Response &res,
  3059. const ContentReader &content_reader) {
  3060. std::string body;
  3061. content_reader([&](const char *data, size_t data_length) {
  3062. body.append(data, data_length);
  3063. return true;
  3064. });
  3065. EXPECT_EQ(body, "content");
  3066. res.set_content(body, "text/plain");
  3067. })
  3068. .Post("/query-string-and-body",
  3069. [&](const Request &req, Response & /*res*/) {
  3070. ASSERT_TRUE(req.has_param("key"));
  3071. EXPECT_EQ(req.get_param_value("key"), "value");
  3072. EXPECT_EQ(req.body, "content");
  3073. })
  3074. .Get("/last-request",
  3075. [&](const Request &req, Response & /*res*/) {
  3076. EXPECT_EQ("close", req.get_header_value("Connection"));
  3077. })
  3078. .Get(R"(/redirect/(\d+))",
  3079. [&](const Request &req, Response &res) {
  3080. auto num = std::stoi(req.matches[1]) + 1;
  3081. std::string url = "/redirect/" + std::to_string(num);
  3082. res.set_redirect(url);
  3083. })
  3084. .Post("/binary",
  3085. [&](const Request &req, Response &res) {
  3086. EXPECT_EQ(4U, req.body.size());
  3087. EXPECT_EQ("application/octet-stream",
  3088. req.get_header_value("Content-Type"));
  3089. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3090. res.set_content(req.body, "application/octet-stream");
  3091. })
  3092. .Put("/binary",
  3093. [&](const Request &req, Response &res) {
  3094. EXPECT_EQ(4U, req.body.size());
  3095. EXPECT_EQ("application/octet-stream",
  3096. req.get_header_value("Content-Type"));
  3097. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3098. res.set_content(req.body, "application/octet-stream");
  3099. })
  3100. .Patch("/binary",
  3101. [&](const Request &req, Response &res) {
  3102. EXPECT_EQ(4U, req.body.size());
  3103. EXPECT_EQ("application/octet-stream",
  3104. req.get_header_value("Content-Type"));
  3105. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3106. res.set_content(req.body, "application/octet-stream");
  3107. })
  3108. .Delete("/binary",
  3109. [&](const Request &req, Response &res) {
  3110. EXPECT_EQ(4U, req.body.size());
  3111. EXPECT_EQ("application/octet-stream",
  3112. req.get_header_value("Content-Type"));
  3113. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3114. res.set_content(req.body, "application/octet-stream");
  3115. })
  3116. .Get("/issue1772",
  3117. [&](const Request & /*req*/, Response &res) {
  3118. res.status = 401;
  3119. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3120. })
  3121. .Delete("/issue609",
  3122. [](const httplib::Request &, httplib::Response &res,
  3123. const httplib::ContentReader &) {
  3124. res.set_content("ok", "text/plain");
  3125. })
  3126. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3127. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3128. .Get("/compress",
  3129. [&](const Request & /*req*/, Response &res) {
  3130. res.set_content(
  3131. "12345678901234567890123456789012345678901234567890123456789"
  3132. "01234567890123456789012345678901234567890",
  3133. "text/plain");
  3134. })
  3135. .Get("/nocompress",
  3136. [&](const Request & /*req*/, Response &res) {
  3137. res.set_content(
  3138. "12345678901234567890123456789012345678901234567890123456789"
  3139. "01234567890123456789012345678901234567890",
  3140. "application/octet-stream");
  3141. })
  3142. .Post("/compress-multipart",
  3143. [&](const Request &req, Response & /*res*/) {
  3144. EXPECT_EQ(2u, req.form.fields.size());
  3145. ASSERT_TRUE(!req.form.has_field("???"));
  3146. {
  3147. const auto &text = req.form.get_field("key1");
  3148. EXPECT_EQ("test", text);
  3149. }
  3150. {
  3151. const auto &text = req.form.get_field("key2");
  3152. EXPECT_EQ("--abcdefg123", text);
  3153. }
  3154. })
  3155. #endif
  3156. ;
  3157. persons_["john"] = "programmer";
  3158. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3159. svr_.wait_until_ready();
  3160. }
  3161. virtual void TearDown() {
  3162. svr_.stop();
  3163. if (!request_threads_.empty()) {
  3164. std::this_thread::sleep_for(std::chrono::seconds(1));
  3165. for (auto &t : request_threads_) {
  3166. t.join();
  3167. }
  3168. }
  3169. t_.join();
  3170. }
  3171. map<string, string> persons_;
  3172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3173. SSLClient cli_;
  3174. SSLServer svr_;
  3175. #else
  3176. Client cli_;
  3177. Server svr_;
  3178. #endif
  3179. thread t_;
  3180. std::vector<thread> request_threads_;
  3181. };
  3182. TEST_F(ServerTest, GetMethod200) {
  3183. auto res = cli_.Get("/hi");
  3184. ASSERT_TRUE(res);
  3185. EXPECT_EQ("HTTP/1.1", res->version);
  3186. EXPECT_EQ(StatusCode::OK_200, res->status);
  3187. EXPECT_EQ("OK", res->reason);
  3188. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3189. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3190. EXPECT_EQ("Hello World!", res->body);
  3191. }
  3192. TEST_F(ServerTest, GetEmptyFile) {
  3193. auto res = cli_.Get("/empty_file");
  3194. ASSERT_TRUE(res);
  3195. EXPECT_EQ(StatusCode::OK_200, res->status);
  3196. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3198. EXPECT_EQ("", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetFileContent) {
  3201. auto res = cli_.Get("/file_content");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("test.html", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContentWithRange) {
  3209. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3214. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3215. EXPECT_EQ("est", res->body);
  3216. }
  3217. TEST_F(ServerTest, GetFileContentWithContentType) {
  3218. auto res = cli_.Get("/file_content_with_content_type");
  3219. ASSERT_TRUE(res);
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3222. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("file\n", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetInvalidFileContent) {
  3226. auto res = cli_.Get("/invalid_file_content");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3229. }
  3230. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3231. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3232. ASSERT_TRUE(res);
  3233. EXPECT_EQ("HTTP/1.1", res->version);
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3236. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3237. EXPECT_EQ("Hello World!", res->body);
  3238. }
  3239. TEST_F(ServerTest, GetMethod302) {
  3240. auto res = cli_.Get("/");
  3241. ASSERT_TRUE(res);
  3242. EXPECT_EQ(StatusCode::Found_302, res->status);
  3243. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3244. }
  3245. TEST_F(ServerTest, GetMethod302Redirect) {
  3246. cli_.set_follow_location(true);
  3247. auto res = cli_.Get("/");
  3248. ASSERT_TRUE(res);
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. EXPECT_EQ("Hello World!", res->body);
  3251. EXPECT_EQ("/hi", res->location);
  3252. }
  3253. TEST_F(ServerTest, GetMethod404) {
  3254. auto res = cli_.Get("/invalid");
  3255. ASSERT_TRUE(res);
  3256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3257. }
  3258. TEST_F(ServerTest, HeadMethod200) {
  3259. auto res = cli_.Head("/hi");
  3260. ASSERT_TRUE(res);
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3263. EXPECT_TRUE(res->body.empty());
  3264. }
  3265. TEST_F(ServerTest, HeadMethod200Static) {
  3266. auto res = cli_.Head("/mount/dir/index.html");
  3267. ASSERT_TRUE(res);
  3268. EXPECT_EQ(StatusCode::OK_200, res->status);
  3269. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3270. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod404) {
  3274. auto res = cli_.Head("/invalid");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3277. EXPECT_TRUE(res->body.empty());
  3278. }
  3279. TEST_F(ServerTest, GetMethodPersonJohn) {
  3280. auto res = cli_.Get("/person/john");
  3281. ASSERT_TRUE(res);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3284. EXPECT_EQ("programmer", res->body);
  3285. }
  3286. TEST_F(ServerTest, PostMethod1) {
  3287. auto res = cli_.Get("/person/john1");
  3288. ASSERT_TRUE(res);
  3289. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3290. res = cli_.Post("/person", "name=john1&note=coder",
  3291. "application/x-www-form-urlencoded");
  3292. ASSERT_TRUE(res);
  3293. ASSERT_EQ(StatusCode::OK_200, res->status);
  3294. res = cli_.Get("/person/john1");
  3295. ASSERT_TRUE(res);
  3296. ASSERT_EQ(StatusCode::OK_200, res->status);
  3297. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3298. ASSERT_EQ("coder", res->body);
  3299. }
  3300. TEST_F(ServerTest, PostMethod2) {
  3301. auto res = cli_.Get("/person/john2");
  3302. ASSERT_TRUE(res);
  3303. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3304. Params params;
  3305. params.emplace("name", "john2");
  3306. params.emplace("note", "coder");
  3307. res = cli_.Post("/person", params);
  3308. ASSERT_TRUE(res);
  3309. ASSERT_EQ(StatusCode::OK_200, res->status);
  3310. res = cli_.Get("/person/john2");
  3311. ASSERT_TRUE(res);
  3312. ASSERT_EQ(StatusCode::OK_200, res->status);
  3313. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3314. ASSERT_EQ("coder", res->body);
  3315. }
  3316. TEST_F(ServerTest, PutMethod3) {
  3317. auto res = cli_.Get("/person/john3");
  3318. ASSERT_TRUE(res);
  3319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3320. Params params;
  3321. params.emplace("name", "john3");
  3322. params.emplace("note", "coder");
  3323. res = cli_.Put("/person", params);
  3324. ASSERT_TRUE(res);
  3325. ASSERT_EQ(StatusCode::OK_200, res->status);
  3326. res = cli_.Get("/person/john3");
  3327. ASSERT_TRUE(res);
  3328. ASSERT_EQ(StatusCode::OK_200, res->status);
  3329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3330. ASSERT_EQ("coder", res->body);
  3331. }
  3332. TEST_F(ServerTest, DeleteMethod1) {
  3333. auto res = cli_.Get("/person/john4");
  3334. ASSERT_TRUE(res);
  3335. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3336. Params params;
  3337. params.emplace("name", "john4");
  3338. params.emplace("note", "coder");
  3339. res = cli_.Post("/person", params);
  3340. ASSERT_TRUE(res);
  3341. ASSERT_EQ(StatusCode::OK_200, res->status);
  3342. res = cli_.Get("/person/john4");
  3343. ASSERT_TRUE(res);
  3344. ASSERT_EQ(StatusCode::OK_200, res->status);
  3345. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3346. ASSERT_EQ("coder", res->body);
  3347. Params delete_params;
  3348. delete_params.emplace("name", "john4");
  3349. res = cli_.Delete("/person", delete_params);
  3350. ASSERT_TRUE(res);
  3351. ASSERT_EQ(StatusCode::OK_200, res->status);
  3352. ASSERT_EQ("DELETED", res->body);
  3353. res = cli_.Get("/person/john4");
  3354. ASSERT_TRUE(res);
  3355. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3356. }
  3357. TEST_F(ServerTest, DeleteMethod2) {
  3358. auto res = cli_.Get("/person/john5");
  3359. ASSERT_TRUE(res);
  3360. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3361. Params params;
  3362. params.emplace("name", "john5");
  3363. params.emplace("note", "developer");
  3364. res = cli_.Post("/person", params);
  3365. ASSERT_TRUE(res);
  3366. ASSERT_EQ(StatusCode::OK_200, res->status);
  3367. res = cli_.Get("/person/john5");
  3368. ASSERT_TRUE(res);
  3369. ASSERT_EQ(StatusCode::OK_200, res->status);
  3370. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3371. ASSERT_EQ("developer", res->body);
  3372. Params delete_params;
  3373. delete_params.emplace("name", "john5");
  3374. Headers headers;
  3375. headers.emplace("Custom-Header", "test-value");
  3376. res = cli_.Delete("/person", headers, delete_params);
  3377. ASSERT_TRUE(res);
  3378. ASSERT_EQ(StatusCode::OK_200, res->status);
  3379. ASSERT_EQ("DELETED", res->body);
  3380. res = cli_.Get("/person/john5");
  3381. ASSERT_TRUE(res);
  3382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3383. }
  3384. TEST_F(ServerTest, DeleteMethod3) {
  3385. auto res = cli_.Get("/person/john6");
  3386. ASSERT_TRUE(res);
  3387. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3388. Params params;
  3389. params.emplace("name", "john6");
  3390. params.emplace("note", "tester");
  3391. res = cli_.Post("/person", params);
  3392. ASSERT_TRUE(res);
  3393. ASSERT_EQ(StatusCode::OK_200, res->status);
  3394. res = cli_.Get("/person/john6");
  3395. ASSERT_TRUE(res);
  3396. ASSERT_EQ(StatusCode::OK_200, res->status);
  3397. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3398. ASSERT_EQ("tester", res->body);
  3399. Params delete_params;
  3400. delete_params.emplace("name", "john6");
  3401. Headers headers;
  3402. headers.emplace("Custom-Header", "test-value");
  3403. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3404. ASSERT_TRUE(res);
  3405. ASSERT_EQ(StatusCode::OK_200, res->status);
  3406. ASSERT_EQ("DELETED", res->body);
  3407. res = cli_.Get("/person/john6");
  3408. ASSERT_TRUE(res);
  3409. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3410. }
  3411. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3412. Params params;
  3413. params.emplace("json", JSON_DATA);
  3414. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3415. ASSERT_TRUE(res);
  3416. ASSERT_EQ(StatusCode::OK_200, res->status);
  3417. ASSERT_EQ(JSON_DATA, res->body);
  3418. }
  3419. TEST_F(ServerTest, PostEmptyContent) {
  3420. auto res = cli_.Post("/empty", "", "text/plain");
  3421. ASSERT_TRUE(res);
  3422. ASSERT_EQ(StatusCode::OK_200, res->status);
  3423. ASSERT_EQ("empty", res->body);
  3424. }
  3425. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3426. auto res = cli_.Post("/empty-no-content-type");
  3427. ASSERT_TRUE(res);
  3428. ASSERT_EQ(StatusCode::OK_200, res->status);
  3429. ASSERT_EQ("empty-no-content-type", res->body);
  3430. }
  3431. TEST_F(ServerTest, PostPathOnly) {
  3432. auto res = cli_.Post("/path-only");
  3433. ASSERT_TRUE(res);
  3434. ASSERT_EQ(StatusCode::OK_200, res->status);
  3435. ASSERT_EQ("path-only", res->body);
  3436. }
  3437. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3438. auto res = cli_.Post("/path-headers-only",
  3439. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3440. ASSERT_TRUE(res);
  3441. ASSERT_EQ(StatusCode::OK_200, res->status);
  3442. ASSERT_EQ("path-headers-only", res->body);
  3443. }
  3444. TEST_F(ServerTest, PostLarge) {
  3445. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3446. ASSERT_TRUE(res);
  3447. ASSERT_EQ(StatusCode::OK_200, res->status);
  3448. EXPECT_EQ(LARGE_DATA, res->body);
  3449. }
  3450. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3451. auto res = cli_.Put("/empty-no-content-type");
  3452. ASSERT_TRUE(res);
  3453. ASSERT_EQ(StatusCode::OK_200, res->status);
  3454. ASSERT_EQ("empty-no-content-type", res->body);
  3455. }
  3456. TEST_F(ServerTest, GetMethodDir) {
  3457. auto res = cli_.Get("/dir/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(StatusCode::OK_200, res->status);
  3460. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3461. auto body = R"(<html>
  3462. <head>
  3463. </head>
  3464. <body>
  3465. <a href="/dir/test.html">Test</a>
  3466. <a href="/hi">hi</a>
  3467. </body>
  3468. </html>
  3469. )";
  3470. EXPECT_EQ(body, res->body);
  3471. }
  3472. TEST_F(ServerTest, GetMethodDirTest) {
  3473. auto res = cli_.Get("/dir/test.html");
  3474. ASSERT_TRUE(res);
  3475. EXPECT_EQ(StatusCode::OK_200, res->status);
  3476. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3477. EXPECT_EQ("test.html", res->body);
  3478. }
  3479. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3480. auto res = cli_.Get("/dir/../dir/test.html");
  3481. ASSERT_TRUE(res);
  3482. EXPECT_EQ(StatusCode::OK_200, res->status);
  3483. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3484. EXPECT_EQ("test.html", res->body);
  3485. }
  3486. TEST_F(ServerTest, GetMethodInvalidPath) {
  3487. auto res = cli_.Get("/dir/../test.html");
  3488. ASSERT_TRUE(res);
  3489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3490. }
  3491. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3492. auto res = cli_.Get("/../www/dir/test.html");
  3493. ASSERT_TRUE(res);
  3494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3495. }
  3496. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3497. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3498. ASSERT_TRUE(res);
  3499. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3500. }
  3501. TEST_F(ServerTest, GetMethodDirMountTest) {
  3502. auto res = cli_.Get("/mount/dir/test.html");
  3503. ASSERT_TRUE(res);
  3504. EXPECT_EQ(StatusCode::OK_200, res->status);
  3505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3506. EXPECT_EQ("test.html", res->body);
  3507. }
  3508. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3509. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3510. ASSERT_TRUE(res);
  3511. EXPECT_EQ(StatusCode::OK_200, res->status);
  3512. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3513. EXPECT_EQ("test.html", res->body);
  3514. }
  3515. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3516. auto res = cli_.Get("/mount/dir/../test.html");
  3517. ASSERT_TRUE(res);
  3518. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3519. }
  3520. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3521. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3522. ASSERT_TRUE(res);
  3523. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3524. }
  3525. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3526. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3527. ASSERT_TRUE(res);
  3528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3529. }
  3530. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3531. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3532. ASSERT_TRUE(res);
  3533. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3534. }
  3535. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3536. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3537. ASSERT_TRUE(res);
  3538. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3539. }
  3540. TEST_F(ServerTest, PostMethod303) {
  3541. auto res = cli_.Post("/1", "body", "text/plain");
  3542. ASSERT_TRUE(res);
  3543. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3544. EXPECT_EQ("/2", res->get_header_value("Location"));
  3545. }
  3546. TEST_F(ServerTest, PostMethod303Redirect) {
  3547. cli_.set_follow_location(true);
  3548. auto res = cli_.Post("/1", "body", "text/plain");
  3549. ASSERT_TRUE(res);
  3550. EXPECT_EQ(StatusCode::OK_200, res->status);
  3551. EXPECT_EQ("redirected.", res->body);
  3552. EXPECT_EQ("/2", res->location);
  3553. }
  3554. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3555. auto res = cli_.Get("/dir/test.abcde");
  3556. ASSERT_TRUE(res);
  3557. EXPECT_EQ(StatusCode::OK_200, res->status);
  3558. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3559. EXPECT_EQ("abcde", res->body);
  3560. }
  3561. TEST_F(ServerTest, StaticFileRange) {
  3562. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3563. ASSERT_TRUE(res);
  3564. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3565. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3566. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3567. EXPECT_EQ(true, res->has_header("Content-Range"));
  3568. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3569. EXPECT_EQ(std::string("cd"), res->body);
  3570. }
  3571. TEST_F(ServerTest, StaticFileRanges) {
  3572. auto res =
  3573. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3574. ASSERT_TRUE(res);
  3575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3576. EXPECT_TRUE(
  3577. res->get_header_value("Content-Type")
  3578. .find(
  3579. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3580. 0);
  3581. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3582. }
  3583. TEST_F(ServerTest, StaticFileRangeHead) {
  3584. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3585. ASSERT_TRUE(res);
  3586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3587. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3588. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3589. EXPECT_EQ(true, res->has_header("Content-Range"));
  3590. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3591. }
  3592. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3593. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3594. ASSERT_TRUE(res);
  3595. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3597. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3598. EXPECT_EQ(true, res->has_header("Content-Range"));
  3599. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3600. res->get_header_value("Content-Range"));
  3601. EXPECT_EQ("LAST\n", res->body);
  3602. }
  3603. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3604. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3605. ASSERT_TRUE(res);
  3606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3607. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3608. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3609. EXPECT_EQ(true, res->has_header("Content-Range"));
  3610. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3611. }
  3612. TEST_F(ServerTest, StaticFileBigFile) {
  3613. auto res = cli_.Get("/dir/1MB.txt");
  3614. ASSERT_TRUE(res);
  3615. EXPECT_EQ(StatusCode::OK_200, res->status);
  3616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3617. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3618. }
  3619. TEST_F(ServerTest, InvalidBaseDirMount) {
  3620. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3621. }
  3622. TEST_F(ServerTest, Binary) {
  3623. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3624. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3625. "application/octet-stream");
  3626. ASSERT_TRUE(res);
  3627. ASSERT_EQ(StatusCode::OK_200, res->status);
  3628. ASSERT_EQ(4U, res->body.size());
  3629. res = cli_.Put("/binary", binary.data(), binary.size(),
  3630. "application/octet-stream");
  3631. ASSERT_TRUE(res);
  3632. ASSERT_EQ(StatusCode::OK_200, res->status);
  3633. ASSERT_EQ(4U, res->body.size());
  3634. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3635. "application/octet-stream");
  3636. ASSERT_TRUE(res);
  3637. ASSERT_EQ(StatusCode::OK_200, res->status);
  3638. ASSERT_EQ(4U, res->body.size());
  3639. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3640. "application/octet-stream");
  3641. ASSERT_TRUE(res);
  3642. ASSERT_EQ(StatusCode::OK_200, res->status);
  3643. ASSERT_EQ(4U, res->body.size());
  3644. }
  3645. TEST_F(ServerTest, BinaryString) {
  3646. auto binary = std::string("\x00\x01\x02\x03", 4);
  3647. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  3648. ASSERT_TRUE(res);
  3649. ASSERT_EQ(StatusCode::OK_200, res->status);
  3650. ASSERT_EQ(4U, res->body.size());
  3651. res = cli_.Put("/binary", binary, "application/octet-stream");
  3652. ASSERT_TRUE(res);
  3653. ASSERT_EQ(StatusCode::OK_200, res->status);
  3654. ASSERT_EQ(4U, res->body.size());
  3655. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3656. ASSERT_TRUE(res);
  3657. ASSERT_EQ(StatusCode::OK_200, res->status);
  3658. ASSERT_EQ(4U, res->body.size());
  3659. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3660. ASSERT_TRUE(res);
  3661. ASSERT_EQ(StatusCode::OK_200, res->status);
  3662. ASSERT_EQ(4U, res->body.size());
  3663. }
  3664. TEST_F(ServerTest, EmptyRequest) {
  3665. auto res = cli_.Get("");
  3666. ASSERT_TRUE(!res);
  3667. EXPECT_EQ(Error::Connection, res.error());
  3668. }
  3669. TEST_F(ServerTest, LongRequest) {
  3670. std::string request;
  3671. for (size_t i = 0; i < 545; i++) {
  3672. request += "/TooLongRequest";
  3673. }
  3674. request += "OK";
  3675. auto res = cli_.Get(request.c_str());
  3676. ASSERT_TRUE(res);
  3677. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3678. }
  3679. TEST_F(ServerTest, TooLongRequest) {
  3680. std::string request;
  3681. for (size_t i = 0; i < 546; i++) {
  3682. request += "/TooLongRequest";
  3683. }
  3684. request += "_NG";
  3685. auto start = std::chrono::high_resolution_clock::now();
  3686. cli_.set_keep_alive(true);
  3687. auto res = cli_.Get(request.c_str());
  3688. auto end = std::chrono::high_resolution_clock::now();
  3689. auto elapsed =
  3690. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3691. .count();
  3692. ASSERT_TRUE(res);
  3693. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3694. EXPECT_LE(elapsed, 100);
  3695. EXPECT_EQ("close", res->get_header_value("Connection"));
  3696. EXPECT_FALSE(cli_.is_socket_open());
  3697. }
  3698. TEST_F(ServerTest, AlmostTooLongRequest) {
  3699. // test for #2046 - URI length check shouldn't include other content on req
  3700. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3701. // leading /, space, HTTP/1.1)
  3702. std::string request =
  3703. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3704. auto res = cli_.Get(request.c_str());
  3705. ASSERT_TRUE(res);
  3706. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3707. }
  3708. TEST_F(ServerTest, LongHeader) {
  3709. Request req;
  3710. req.method = "GET";
  3711. req.path = "/hi";
  3712. std::string host_and_port;
  3713. host_and_port += HOST;
  3714. host_and_port += ":";
  3715. host_and_port += std::to_string(PORT);
  3716. req.headers.emplace("Host", host_and_port.c_str());
  3717. req.headers.emplace("Accept", "*/*");
  3718. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3719. req.headers.emplace(
  3720. "Header-Name",
  3721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@");
  3750. auto res = std::make_shared<Response>();
  3751. auto error = Error::Success;
  3752. auto ret = cli_.send(req, *res, error);
  3753. ASSERT_TRUE(ret);
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST_F(ServerTest, LongQueryValue) {
  3757. auto start = std::chrono::high_resolution_clock::now();
  3758. cli_.set_keep_alive(true);
  3759. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3760. auto end = std::chrono::high_resolution_clock::now();
  3761. auto elapsed =
  3762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3763. .count();
  3764. ASSERT_TRUE(res);
  3765. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3766. EXPECT_LE(elapsed, 100);
  3767. EXPECT_EQ("close", res->get_header_value("Connection"));
  3768. EXPECT_FALSE(cli_.is_socket_open());
  3769. }
  3770. TEST_F(ServerTest, TooLongQueryValue) {
  3771. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3772. ASSERT_FALSE(res);
  3773. EXPECT_EQ(Error::Read, res.error());
  3774. }
  3775. TEST_F(ServerTest, TooLongHeader) {
  3776. Request req;
  3777. req.method = "GET";
  3778. req.path = "/hi";
  3779. std::string host_and_port;
  3780. host_and_port += HOST;
  3781. host_and_port += ":";
  3782. host_and_port += std::to_string(PORT);
  3783. req.headers.emplace("Host", host_and_port.c_str());
  3784. req.headers.emplace("Accept", "*/*");
  3785. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3786. req.headers.emplace(
  3787. "Header-Name",
  3788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@");
  3817. auto res = std::make_shared<Response>();
  3818. auto error = Error::Success;
  3819. auto ret = cli_.send(req, *res, error);
  3820. ASSERT_TRUE(ret);
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. }
  3823. TEST_F(ServerTest, HeaderCountAtLimit) {
  3824. // Test with headers just under the 100 limit
  3825. httplib::Headers headers;
  3826. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3827. // This should keep us just under the 100 header limit
  3828. for (int i = 0; i < 95; i++) {
  3829. std::string name = "X-Test-Header-" + std::to_string(i);
  3830. std::string value = "value" + std::to_string(i);
  3831. headers.emplace(name, value);
  3832. }
  3833. // This should work fine as we're under the limit
  3834. auto res = cli_.Get("/hi", headers);
  3835. EXPECT_TRUE(res);
  3836. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3837. }
  3838. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3839. // Test with many headers to exceed the 100 limit
  3840. httplib::Headers headers;
  3841. // Add 150 headers to definitely exceed the 100 limit
  3842. for (int i = 0; i < 150; i++) {
  3843. std::string name = "X-Test-Header-" + std::to_string(i);
  3844. std::string value = "value" + std::to_string(i);
  3845. headers.emplace(name, value);
  3846. }
  3847. // This should fail due to exceeding header count limit
  3848. cli_.set_keep_alive(true);
  3849. auto res = cli_.Get("/hi", headers);
  3850. // The request should either fail or return 400 Bad Request
  3851. if (res) {
  3852. // If we get a response, it should be 400 Bad Request
  3853. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3854. } else {
  3855. // Or the request should fail entirely
  3856. EXPECT_FALSE(res);
  3857. }
  3858. EXPECT_EQ("close", res->get_header_value("Connection"));
  3859. EXPECT_FALSE(cli_.is_socket_open());
  3860. }
  3861. TEST_F(ServerTest, PercentEncoding) {
  3862. auto res = cli_.Get("/e%6edwith%");
  3863. ASSERT_TRUE(res);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, PercentEncodingUnicode) {
  3867. auto res = cli_.Get("/e%u006edwith%");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_EQ(StatusCode::OK_200, res->status);
  3870. }
  3871. TEST_F(ServerTest, InvalidPercentEncoding) {
  3872. auto res = cli_.Get("/%endwith%");
  3873. ASSERT_TRUE(res);
  3874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3875. }
  3876. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3877. auto res = cli_.Get("/%uendwith%");
  3878. ASSERT_TRUE(res);
  3879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3880. }
  3881. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3882. auto res = cli_.Get("/hello?aaa=bbb%");
  3883. ASSERT_TRUE(res);
  3884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3885. }
  3886. TEST_F(ServerTest, PlusSignEncoding) {
  3887. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3888. ASSERT_TRUE(res);
  3889. EXPECT_EQ(StatusCode::OK_200, res->status);
  3890. EXPECT_EQ("a +b", res->body);
  3891. }
  3892. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3893. // This test simulates a potential DoS attack using many headers
  3894. // to verify our security fix prevents memory exhaustion
  3895. httplib::Headers attack_headers;
  3896. // Attempt to add many headers like an attacker would (200 headers to far
  3897. // exceed limit)
  3898. for (int i = 0; i < 200; i++) {
  3899. std::string name = "X-Attack-Header-" + std::to_string(i);
  3900. std::string value = "attack_payload_" + std::to_string(i);
  3901. attack_headers.emplace(name, value);
  3902. }
  3903. // Try to POST with excessive headers
  3904. cli_.set_keep_alive(true);
  3905. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3906. // Should either fail or return 400 Bad Request due to security limit
  3907. if (res) {
  3908. // If we get a response, it should be 400 Bad Request
  3909. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3910. } else {
  3911. // Request failed, which is the expected behavior for DoS protection
  3912. EXPECT_FALSE(res);
  3913. }
  3914. EXPECT_EQ("close", res->get_header_value("Connection"));
  3915. EXPECT_FALSE(cli_.is_socket_open());
  3916. }
  3917. TEST_F(ServerTest, MultipartFormData) {
  3918. UploadFormDataItems items = {
  3919. {"text1", "text default", "", ""},
  3920. {"text2", "aωb", "", ""},
  3921. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3922. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3923. {"file3", "", "", "application/octet-stream"},
  3924. {"file4", "", "", " application/json tmp-string "}};
  3925. auto res = cli_.Post("/multipart", items);
  3926. ASSERT_TRUE(res);
  3927. EXPECT_EQ(StatusCode::OK_200, res->status);
  3928. }
  3929. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3930. UploadFormDataItems items = {
  3931. {"text", "default text", "", ""},
  3932. {"multi_text1", "aaaaa", "", ""},
  3933. {"multi_text1", "bbbbb", "", ""},
  3934. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3935. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3936. "application/json"},
  3937. };
  3938. auto res = cli_.Post("/multipart/multi_file_values", items);
  3939. ASSERT_TRUE(res);
  3940. EXPECT_EQ(StatusCode::OK_200, res->status);
  3941. }
  3942. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3943. auto res = cli_.Get("/hi");
  3944. ASSERT_TRUE(res);
  3945. EXPECT_EQ(StatusCode::OK_200, res->status);
  3946. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3947. EXPECT_EQ("Hello World!", res->body);
  3948. }
  3949. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3950. Request req;
  3951. req.method = "POST";
  3952. req.path = "/chunked";
  3953. std::string host_and_port;
  3954. host_and_port += HOST;
  3955. host_and_port += ":";
  3956. host_and_port += std::to_string(PORT);
  3957. req.headers.emplace("Host", host_and_port.c_str());
  3958. req.headers.emplace("Accept", "*/*");
  3959. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3960. req.headers.emplace("Content-Type", "text/plain");
  3961. req.headers.emplace("Content-Length", "0");
  3962. req.headers.emplace(
  3963. "Transfer-Encoding",
  3964. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3965. // Client does not chunk, so make a chunked body manually.
  3966. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3967. auto res = std::make_shared<Response>();
  3968. auto error = Error::Success;
  3969. auto ret = cli_.send(req, *res, error);
  3970. ASSERT_TRUE(ret);
  3971. EXPECT_EQ(StatusCode::OK_200, res->status);
  3972. }
  3973. TEST_F(ServerTest, GetStreamed2) {
  3974. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3975. ASSERT_TRUE(res);
  3976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3978. EXPECT_EQ(true, res->has_header("Content-Range"));
  3979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3980. EXPECT_EQ(std::string("ab"), res->body);
  3981. }
  3982. TEST_F(ServerTest, GetStreamed) {
  3983. auto res = cli_.Get("/streamed");
  3984. ASSERT_TRUE(res);
  3985. EXPECT_EQ(StatusCode::OK_200, res->status);
  3986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3987. EXPECT_EQ(std::string("aaabbb"), res->body);
  3988. }
  3989. TEST_F(ServerTest, GetStreamedWithRange1) {
  3990. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3991. ASSERT_TRUE(res);
  3992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3993. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3994. EXPECT_EQ(true, res->has_header("Content-Range"));
  3995. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3996. EXPECT_EQ(std::string("def"), res->body);
  3997. }
  3998. TEST_F(ServerTest, GetStreamedWithRange2) {
  3999. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4000. ASSERT_TRUE(res);
  4001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4002. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4003. EXPECT_EQ(true, res->has_header("Content-Range"));
  4004. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4005. EXPECT_EQ(std::string("bcdefg"), res->body);
  4006. }
  4007. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4008. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4009. ASSERT_TRUE(res);
  4010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4011. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4012. EXPECT_EQ(true, res->has_header("Content-Range"));
  4013. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4014. EXPECT_EQ(std::string("efg"), res->body);
  4015. }
  4016. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4017. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4018. ASSERT_TRUE(res);
  4019. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4020. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4021. EXPECT_EQ(false, res->has_header("Content-Range"));
  4022. EXPECT_EQ(0U, res->body.size());
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4025. auto res = cli_.Get("/streamed-with-range",
  4026. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4027. "92233720368547758079223372036854775807"}});
  4028. ASSERT_TRUE(res);
  4029. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4030. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4031. EXPECT_EQ(false, res->has_header("Content-Range"));
  4032. EXPECT_EQ(0U, res->body.size());
  4033. }
  4034. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4035. auto res = cli_.Get(
  4036. "/with-range",
  4037. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4038. {"Accept-Encoding", ""}});
  4039. ASSERT_TRUE(res);
  4040. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4041. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4042. EXPECT_EQ(true, res->has_header("Content-Range"));
  4043. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4044. EXPECT_EQ(std::string("abcdefg"), res->body);
  4045. }
  4046. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4047. auto res = cli_.Get("/with-range", {
  4048. {"Range", "bytes=0-"},
  4049. {"Accept-Encoding", ""},
  4050. });
  4051. ASSERT_TRUE(res);
  4052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4053. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4054. EXPECT_EQ(true, res->has_header("Content-Range"));
  4055. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4056. EXPECT_EQ(std::string("abcdefg"), res->body);
  4057. }
  4058. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4059. auto res =
  4060. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4061. ASSERT_TRUE(res);
  4062. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4063. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4064. EXPECT_EQ(false, res->has_header("Content-Range"));
  4065. EXPECT_EQ(267U, res->body.size());
  4066. // Check that both range contents are present
  4067. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4068. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4069. // Check that Content-Range headers are present for both ranges
  4070. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4071. std::string::npos);
  4072. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4073. std::string::npos);
  4074. }
  4075. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4076. Ranges ranges;
  4077. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4078. ranges.emplace_back(0, -1);
  4079. }
  4080. auto res =
  4081. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4082. ASSERT_TRUE(res);
  4083. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4084. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4085. EXPECT_EQ(false, res->has_header("Content-Range"));
  4086. EXPECT_EQ(0U, res->body.size());
  4087. }
  4088. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4089. auto res =
  4090. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4091. ASSERT_TRUE(res);
  4092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4093. EXPECT_EQ(5U, res->body.size());
  4094. // Check that overlapping ranges are coalesced into a single range
  4095. EXPECT_EQ("bcdef", res->body);
  4096. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4097. // Should be single range, not multipart
  4098. EXPECT_TRUE(res->has_header("Content-Range"));
  4099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4100. }
  4101. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4102. auto res =
  4103. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4104. ASSERT_TRUE(res);
  4105. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4106. EXPECT_EQ(268U, res->body.size());
  4107. // Check that both range contents are present
  4108. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4109. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4110. // Check that Content-Range headers are present for both ranges
  4111. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4112. std::string::npos);
  4113. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4114. std::string::npos);
  4115. }
  4116. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4117. auto res =
  4118. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4119. ASSERT_TRUE(res);
  4120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4121. EXPECT_EQ(269U, res->body.size());
  4122. // Check that both duplicate range contents are present
  4123. size_t first_abc = res->body.find("abc\r\n");
  4124. EXPECT_TRUE(first_abc != std::string::npos);
  4125. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4126. EXPECT_TRUE(second_abc != std::string::npos);
  4127. // Check that Content-Range headers are present for both ranges
  4128. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4129. EXPECT_TRUE(first_range != std::string::npos);
  4130. size_t second_range =
  4131. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4132. EXPECT_TRUE(second_range != std::string::npos);
  4133. }
  4134. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4135. auto res = cli_.Get("/streamed-with-range?error",
  4136. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4137. ASSERT_TRUE(res);
  4138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4140. EXPECT_EQ(false, res->has_header("Content-Range"));
  4141. EXPECT_EQ(0U, res->body.size());
  4142. }
  4143. TEST_F(ServerTest, GetStreamedEndless) {
  4144. uint64_t offset = 0;
  4145. auto res = cli_.Get("/streamed-cancel",
  4146. [&](const char * /*data*/, uint64_t data_length) {
  4147. if (offset < 100) {
  4148. offset += data_length;
  4149. return true;
  4150. }
  4151. return false;
  4152. });
  4153. ASSERT_TRUE(!res);
  4154. EXPECT_EQ(Error::Canceled, res.error());
  4155. }
  4156. TEST_F(ServerTest, ClientStop) {
  4157. std::atomic_size_t count{4};
  4158. std::vector<std::thread> threads;
  4159. for (auto i = count.load(); i != 0; --i) {
  4160. threads.emplace_back([&]() {
  4161. auto res = cli_.Get("/streamed-cancel",
  4162. [&](const char *, uint64_t) { return true; });
  4163. --count;
  4164. ASSERT_TRUE(!res);
  4165. EXPECT_TRUE(res.error() == Error::Canceled ||
  4166. res.error() == Error::Read || res.error() == Error::Write);
  4167. });
  4168. }
  4169. std::this_thread::sleep_for(std::chrono::seconds(2));
  4170. while (count != 0) {
  4171. cli_.stop();
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4173. }
  4174. for (auto &t : threads) {
  4175. t.join();
  4176. }
  4177. }
  4178. TEST_F(ServerTest, GetWithRange1) {
  4179. auto res = cli_.Get("/with-range", {
  4180. make_range_header({{3, 5}}),
  4181. {"Accept-Encoding", ""},
  4182. });
  4183. ASSERT_TRUE(res);
  4184. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4185. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4186. EXPECT_EQ(true, res->has_header("Content-Range"));
  4187. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4188. EXPECT_EQ(std::string("def"), res->body);
  4189. }
  4190. TEST_F(ServerTest, GetWithRange2) {
  4191. auto res = cli_.Get("/with-range", {
  4192. make_range_header({{1, -1}}),
  4193. {"Accept-Encoding", ""},
  4194. });
  4195. ASSERT_TRUE(res);
  4196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4197. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4198. EXPECT_EQ(true, res->has_header("Content-Range"));
  4199. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4200. EXPECT_EQ(std::string("bcdefg"), res->body);
  4201. }
  4202. TEST_F(ServerTest, GetWithRange3) {
  4203. auto res = cli_.Get("/with-range", {
  4204. make_range_header({{0, 0}}),
  4205. {"Accept-Encoding", ""},
  4206. });
  4207. ASSERT_TRUE(res);
  4208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4209. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4210. EXPECT_EQ(true, res->has_header("Content-Range"));
  4211. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4212. EXPECT_EQ(std::string("a"), res->body);
  4213. }
  4214. TEST_F(ServerTest, GetWithRange4) {
  4215. auto res = cli_.Get("/with-range", {
  4216. make_range_header({{-1, 2}}),
  4217. {"Accept-Encoding", ""},
  4218. });
  4219. ASSERT_TRUE(res);
  4220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4221. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4222. EXPECT_EQ(true, res->has_header("Content-Range"));
  4223. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4224. EXPECT_EQ(std::string("fg"), res->body);
  4225. }
  4226. TEST_F(ServerTest, GetWithRange5) {
  4227. auto res = cli_.Get("/with-range", {
  4228. make_range_header({{0, 5}}),
  4229. {"Accept-Encoding", ""},
  4230. });
  4231. ASSERT_TRUE(res);
  4232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4233. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4234. EXPECT_EQ(true, res->has_header("Content-Range"));
  4235. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4236. EXPECT_EQ(std::string("abcdef"), res->body);
  4237. }
  4238. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4239. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4240. ASSERT_TRUE(res);
  4241. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4242. }
  4243. TEST_F(ServerTest, GetWithRangeMultipart) {
  4244. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4245. ASSERT_TRUE(res);
  4246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4247. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4248. EXPECT_EQ(false, res->has_header("Content-Range"));
  4249. EXPECT_EQ(267U, res->body.size());
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4252. auto res =
  4253. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4254. ASSERT_TRUE(res);
  4255. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4256. }
  4257. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4258. auto res = cli_.Get("/with-range-customized-response",
  4259. {{make_range_header({{1, 2}})}});
  4260. ASSERT_TRUE(res);
  4261. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4262. EXPECT_EQ(true, res->has_header("Content-Length"));
  4263. EXPECT_EQ(false, res->has_header("Content-Range"));
  4264. EXPECT_EQ(JSON_DATA, res->body);
  4265. }
  4266. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4267. auto res = cli_.Get("/with-range-customized-response",
  4268. {{make_range_header({{1, 2}, {4, 5}})}});
  4269. ASSERT_TRUE(res);
  4270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4271. EXPECT_EQ(true, res->has_header("Content-Length"));
  4272. EXPECT_EQ(false, res->has_header("Content-Range"));
  4273. EXPECT_EQ(JSON_DATA, res->body);
  4274. }
  4275. TEST_F(ServerTest, Issue1772) {
  4276. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4279. }
  4280. TEST_F(ServerTest, Issue609) {
  4281. auto res = cli_.Delete("/issue609");
  4282. ASSERT_TRUE(res);
  4283. EXPECT_EQ(StatusCode::OK_200, res->status);
  4284. EXPECT_EQ(std::string("ok"), res->body);
  4285. }
  4286. TEST_F(ServerTest, GetStreamedChunked) {
  4287. auto res = cli_.Get("/streamed-chunked");
  4288. ASSERT_TRUE(res);
  4289. EXPECT_EQ(StatusCode::OK_200, res->status);
  4290. EXPECT_EQ(std::string("123456789"), res->body);
  4291. }
  4292. TEST_F(ServerTest, GetStreamedChunked2) {
  4293. auto res = cli_.Get("/streamed-chunked2");
  4294. ASSERT_TRUE(res);
  4295. EXPECT_EQ(StatusCode::OK_200, res->status);
  4296. EXPECT_EQ(std::string("123456789"), res->body);
  4297. }
  4298. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4299. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4300. ASSERT_TRUE(res);
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ(std::string("123456789"), res->body);
  4303. EXPECT_TRUE(res->has_header("Trailer"));
  4304. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4305. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4306. // Trailers are now stored separately from headers (security fix)
  4307. EXPECT_EQ(2U, res->trailers.size());
  4308. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4309. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4310. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4311. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4312. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4313. // Verify trailers are NOT in headers (security verification)
  4314. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4315. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4316. }
  4317. TEST_F(ServerTest, LargeChunkedPost) {
  4318. Request req;
  4319. req.method = "POST";
  4320. req.path = "/large-chunked";
  4321. std::string host_and_port;
  4322. host_and_port += HOST;
  4323. host_and_port += ":";
  4324. host_and_port += std::to_string(PORT);
  4325. req.headers.emplace("Host", host_and_port.c_str());
  4326. req.headers.emplace("Accept", "*/*");
  4327. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4328. req.headers.emplace("Content-Type", "text/plain");
  4329. req.headers.emplace("Content-Length", "0");
  4330. req.headers.emplace("Transfer-Encoding", "chunked");
  4331. std::string long_string(30 * 1024u, 'a');
  4332. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4333. // Attempt to make a large enough post to exceed OS buffers, to test that
  4334. // the server handles short reads if the full chunk data isn't available.
  4335. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4336. auto res = std::make_shared<Response>();
  4337. auto error = Error::Success;
  4338. auto ret = cli_.send(req, *res, error);
  4339. ASSERT_TRUE(ret);
  4340. EXPECT_EQ(StatusCode::OK_200, res->status);
  4341. }
  4342. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4343. auto res = cli_.Get("/remote_addr");
  4344. ASSERT_TRUE(res);
  4345. EXPECT_EQ(StatusCode::OK_200, res->status);
  4346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4347. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4348. }
  4349. TEST_F(ServerTest, GetMethodLocalAddr) {
  4350. auto res = cli_.Get("/local_addr");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::OK_200, res->status);
  4353. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4354. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4355. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4356. }
  4357. TEST_F(ServerTest, HTTPResponseSplitting) {
  4358. auto res = cli_.Get("/http_response_splitting");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. }
  4362. TEST_F(ServerTest, SlowRequest) {
  4363. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4364. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4365. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4366. }
  4367. #if 0
  4368. TEST_F(ServerTest, SlowPost) {
  4369. char buffer[64 * 1024];
  4370. memset(buffer, 0x42, sizeof(buffer));
  4371. auto res = cli_.Post(
  4372. "/slowpost", 64 * 1024 * 1024,
  4373. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4374. auto ret = sink.write(buffer, sizeof(buffer));
  4375. EXPECT_TRUE(ret);
  4376. return true;
  4377. },
  4378. "text/plain");
  4379. ASSERT_TRUE(res);
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. TEST_F(ServerTest, SlowPostFail) {
  4383. char buffer[64 * 1024];
  4384. memset(buffer, 0x42, sizeof(buffer));
  4385. cli_.set_write_timeout(std::chrono::seconds(0));
  4386. auto res = cli_.Post(
  4387. "/slowpost", 64 * 1024 * 1024,
  4388. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4389. sink.write(buffer, sizeof(buffer));
  4390. return true;
  4391. },
  4392. "text/plain");
  4393. ASSERT_TRUE(!res);
  4394. EXPECT_EQ(Error::Write, res.error());
  4395. }
  4396. #endif
  4397. TEST_F(ServerTest, Put) {
  4398. auto res = cli_.Put("/put", "PUT", "text/plain");
  4399. ASSERT_TRUE(res);
  4400. EXPECT_EQ(StatusCode::OK_200, res->status);
  4401. EXPECT_EQ("PUT", res->body);
  4402. }
  4403. TEST_F(ServerTest, PutWithContentProvider) {
  4404. auto res = cli_.Put(
  4405. "/put", 3,
  4406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4407. sink.os << "PUT";
  4408. return true;
  4409. },
  4410. "text/plain");
  4411. ASSERT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::OK_200, res->status);
  4413. EXPECT_EQ("PUT", res->body);
  4414. }
  4415. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4416. auto res = cli_.Post(
  4417. "/post", 42,
  4418. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4419. return false;
  4420. },
  4421. "text/plain");
  4422. ASSERT_TRUE(!res);
  4423. EXPECT_EQ(Error::Canceled, res.error());
  4424. }
  4425. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4426. auto res = cli_.Put(
  4427. "/put",
  4428. [](size_t /*offset*/, DataSink &sink) {
  4429. sink.os << "PUT";
  4430. sink.done();
  4431. return true;
  4432. },
  4433. "text/plain");
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(StatusCode::OK_200, res->status);
  4436. EXPECT_EQ("PUT", res->body);
  4437. }
  4438. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4439. auto res = cli_.Post(
  4440. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4441. "text/plain");
  4442. ASSERT_TRUE(!res);
  4443. EXPECT_EQ(Error::Canceled, res.error());
  4444. }
  4445. TEST_F(ServerTest, PostLoopBack) {
  4446. std::string body;
  4447. auto res = cli_.Post(
  4448. "/post-loopback", 9,
  4449. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4450. EXPECT_EQ(9u, length);
  4451. sink.write("123", 3);
  4452. sink.write("456", 3);
  4453. sink.write("789", 3);
  4454. return true;
  4455. },
  4456. "text/plain",
  4457. [&body](const char *data, size_t data_length) {
  4458. body.append(data, data_length);
  4459. return true;
  4460. });
  4461. ASSERT_TRUE(res);
  4462. EXPECT_EQ(StatusCode::OK_200, res->status);
  4463. EXPECT_EQ("123456789", body);
  4464. }
  4465. TEST_F(ServerTest, PutLoopBack) {
  4466. std::string body;
  4467. auto res = cli_.Put(
  4468. "/put-loopback", 9,
  4469. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4470. EXPECT_EQ(9u, length);
  4471. sink.write("123", 3);
  4472. sink.write("456", 3);
  4473. sink.write("789", 3);
  4474. return true;
  4475. },
  4476. "text/plain",
  4477. [&body](const char *data, size_t data_length) {
  4478. body.append(data, data_length);
  4479. return true;
  4480. });
  4481. ASSERT_TRUE(res);
  4482. EXPECT_EQ(StatusCode::OK_200, res->status);
  4483. EXPECT_EQ("123456789", body);
  4484. }
  4485. TEST_F(ServerTest, PatchLoopBack) {
  4486. std::string body;
  4487. auto res = cli_.Patch(
  4488. "/patch-loopback", 9,
  4489. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4490. EXPECT_EQ(9u, length);
  4491. sink.write("123", 3);
  4492. sink.write("456", 3);
  4493. sink.write("789", 3);
  4494. return true;
  4495. },
  4496. "text/plain",
  4497. [&body](const char *data, size_t data_length) {
  4498. body.append(data, data_length);
  4499. return true;
  4500. });
  4501. ASSERT_TRUE(res);
  4502. EXPECT_EQ(StatusCode::OK_200, res->status);
  4503. EXPECT_EQ("123456789", body);
  4504. }
  4505. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4506. std::string body;
  4507. auto res = cli_.Post(
  4508. "/post-loopback",
  4509. [](size_t /*offset*/, DataSink &sink) {
  4510. sink.write("123", 3);
  4511. sink.write("456", 3);
  4512. sink.write("789", 3);
  4513. sink.done();
  4514. return true;
  4515. },
  4516. "text/plain",
  4517. [&body](const char *data, size_t data_length) {
  4518. body.append(data, data_length);
  4519. return true;
  4520. });
  4521. ASSERT_TRUE(res);
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("123456789", body);
  4524. }
  4525. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4526. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4527. cli_.set_compress(true);
  4528. auto res = cli_.Put(
  4529. "/put", 3,
  4530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4531. sink.os << "PUT";
  4532. return true;
  4533. },
  4534. "text/plain");
  4535. ASSERT_TRUE(res);
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("PUT", res->body);
  4538. }
  4539. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4540. cli_.set_compress(true);
  4541. auto res = cli_.Post(
  4542. "/post", 42,
  4543. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4544. return false;
  4545. },
  4546. "text/plain");
  4547. ASSERT_TRUE(!res);
  4548. EXPECT_EQ(Error::Canceled, res.error());
  4549. }
  4550. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4551. cli_.set_compress(true);
  4552. auto res = cli_.Put(
  4553. "/put",
  4554. [](size_t /*offset*/, DataSink &sink) {
  4555. sink.os << "PUT";
  4556. sink.done();
  4557. return true;
  4558. },
  4559. "text/plain");
  4560. ASSERT_TRUE(res);
  4561. EXPECT_EQ(StatusCode::OK_200, res->status);
  4562. EXPECT_EQ("PUT", res->body);
  4563. }
  4564. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4565. cli_.set_compress(true);
  4566. auto res = cli_.Post(
  4567. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4568. "text/plain");
  4569. ASSERT_TRUE(!res);
  4570. EXPECT_EQ(Error::Canceled, res.error());
  4571. }
  4572. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4575. ASSERT_TRUE(res);
  4576. EXPECT_EQ(StatusCode::OK_200, res->status);
  4577. EXPECT_EQ(LARGE_DATA, res->body);
  4578. }
  4579. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4580. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4581. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4582. Client cli(s.c_str());
  4583. cli.enable_server_certificate_verification(false);
  4584. #else
  4585. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4586. Client cli(s.c_str());
  4587. #endif
  4588. cli.set_compress(true);
  4589. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4590. ASSERT_TRUE(res);
  4591. EXPECT_EQ(StatusCode::OK_200, res->status);
  4592. EXPECT_EQ(LARGE_DATA, res->body);
  4593. // The compressed size should be less than a 10th of the original. May vary
  4594. // depending on the zlib library.
  4595. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4596. static_cast<uint64_t>(10 * 1024 * 1024));
  4597. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4598. }
  4599. TEST_F(ServerTest, PutContentWithDeflate) {
  4600. cli_.set_compress(false);
  4601. Headers headers;
  4602. headers.emplace("Content-Encoding", "deflate");
  4603. // PUT in deflate format:
  4604. auto res = cli_.Put("/put", headers,
  4605. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4606. ASSERT_TRUE(res);
  4607. EXPECT_EQ(StatusCode::OK_200, res->status);
  4608. EXPECT_EQ("PUT", res->body);
  4609. }
  4610. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4611. Headers headers;
  4612. headers.emplace("Accept-Encoding", "gzip, deflate");
  4613. auto res = cli_.Get("/streamed-chunked", headers);
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ(std::string("123456789"), res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked2", headers);
  4622. ASSERT_TRUE(res);
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ(std::string("123456789"), res->body);
  4625. }
  4626. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4627. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4628. ASSERT_TRUE(res);
  4629. EXPECT_EQ(StatusCode::OK_200, res->status);
  4630. }
  4631. TEST(GzipDecompressor, ChunkedDecompression) {
  4632. std::string data;
  4633. for (size_t i = 0; i < 32 * 1024; ++i) {
  4634. data.push_back(static_cast<char>('a' + i % 26));
  4635. }
  4636. std::string compressed_data;
  4637. {
  4638. httplib::detail::gzip_compressor compressor;
  4639. bool result = compressor.compress(
  4640. data.data(), data.size(),
  4641. /*last=*/true,
  4642. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4643. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4644. compressed_data_size);
  4645. return true;
  4646. });
  4647. ASSERT_TRUE(result);
  4648. }
  4649. std::string decompressed_data;
  4650. {
  4651. httplib::detail::gzip_decompressor decompressor;
  4652. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4653. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4654. size_t chunk_size = 130;
  4655. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4656. chunk_begin += chunk_size) {
  4657. size_t current_chunk_size =
  4658. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4659. bool result = decompressor.decompress(
  4660. compressed_data.data() + chunk_begin, current_chunk_size,
  4661. [&](const char *decompressed_data_chunk,
  4662. size_t decompressed_data_chunk_size) {
  4663. decompressed_data.insert(decompressed_data.size(),
  4664. decompressed_data_chunk,
  4665. decompressed_data_chunk_size);
  4666. return true;
  4667. });
  4668. ASSERT_TRUE(result);
  4669. }
  4670. }
  4671. ASSERT_EQ(data, decompressed_data);
  4672. }
  4673. TEST(GzipDecompressor, DeflateDecompression) {
  4674. std::string original_text = "Raw deflate without gzip";
  4675. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4676. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4677. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4678. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4679. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4680. std::string decompressed_data;
  4681. {
  4682. httplib::detail::gzip_decompressor decompressor;
  4683. bool result = decompressor.decompress(
  4684. compressed_data.data(), compressed_data.size(),
  4685. [&](const char *decompressed_data_chunk,
  4686. size_t decompressed_data_chunk_size) {
  4687. decompressed_data.insert(decompressed_data.size(),
  4688. decompressed_data_chunk,
  4689. decompressed_data_chunk_size);
  4690. return true;
  4691. });
  4692. ASSERT_TRUE(result);
  4693. }
  4694. ASSERT_EQ(original_text, decompressed_data);
  4695. }
  4696. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4697. std::string original_text = "Raw deflate without gzip";
  4698. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4699. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4700. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4701. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4702. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4703. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4704. std::string decompressed_data;
  4705. {
  4706. httplib::detail::gzip_decompressor decompressor;
  4707. bool result = decompressor.decompress(
  4708. compressed_data.data(), compressed_data.size(),
  4709. [&](const char *decompressed_data_chunk,
  4710. size_t decompressed_data_chunk_size) {
  4711. decompressed_data.insert(decompressed_data.size(),
  4712. decompressed_data_chunk,
  4713. decompressed_data_chunk_size);
  4714. return true;
  4715. });
  4716. ASSERT_TRUE(result);
  4717. }
  4718. ASSERT_EQ(original_text, decompressed_data);
  4719. }
  4720. #ifdef _WIN32
  4721. TEST(GzipDecompressor, LargeRandomData) {
  4722. // prepare large random data that is difficult to be compressed and is
  4723. // expected to have large size even when compressed
  4724. std::random_device seed_gen;
  4725. std::mt19937 random(seed_gen());
  4726. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4727. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4728. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4729. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4730. // compress data over 4GiB
  4731. std::string compressed_data;
  4732. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4733. httplib::detail::gzip_compressor compressor;
  4734. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4735. data.size() * sizeof(std::uint32_t), true,
  4736. [&](const char *data, size_t size) {
  4737. compressed_data.insert(
  4738. compressed_data.size(), data, size);
  4739. return true;
  4740. });
  4741. ASSERT_TRUE(result);
  4742. // FIXME: compressed data size is expected to be greater than 4GiB,
  4743. // but there is no guarantee
  4744. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4745. // decompress data over 4GiB
  4746. std::string decompressed_data;
  4747. decompressed_data.reserve(data_size);
  4748. httplib::detail::gzip_decompressor decompressor;
  4749. result = decompressor.decompress(
  4750. compressed_data.data(), compressed_data.size(),
  4751. [&](const char *data, size_t size) {
  4752. decompressed_data.insert(decompressed_data.size(), data, size);
  4753. return true;
  4754. });
  4755. ASSERT_TRUE(result);
  4756. // compare
  4757. ASSERT_EQ(data_size, decompressed_data.size());
  4758. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4759. 0);
  4760. }
  4761. #endif
  4762. #endif
  4763. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4764. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4765. Headers headers;
  4766. headers.emplace("Accept-Encoding", "br");
  4767. auto res = cli_.Get("/streamed-chunked", headers);
  4768. ASSERT_TRUE(res);
  4769. EXPECT_EQ(StatusCode::OK_200, res->status);
  4770. EXPECT_EQ(std::string("123456789"), res->body);
  4771. }
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked2", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. #endif
  4781. TEST_F(ServerTest, Patch) {
  4782. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4783. ASSERT_TRUE(res);
  4784. EXPECT_EQ(StatusCode::OK_200, res->status);
  4785. EXPECT_EQ("PATCH", res->body);
  4786. }
  4787. TEST_F(ServerTest, Delete) {
  4788. auto res = cli_.Delete("/delete");
  4789. ASSERT_TRUE(res);
  4790. EXPECT_EQ(StatusCode::OK_200, res->status);
  4791. EXPECT_EQ("DELETE", res->body);
  4792. }
  4793. TEST_F(ServerTest, DeleteContentReceiver) {
  4794. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4795. ASSERT_TRUE(res);
  4796. EXPECT_EQ(StatusCode::OK_200, res->status);
  4797. EXPECT_EQ("content", res->body);
  4798. }
  4799. TEST_F(ServerTest, Options) {
  4800. auto res = cli_.Options("*");
  4801. ASSERT_TRUE(res);
  4802. EXPECT_EQ(StatusCode::OK_200, res->status);
  4803. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4804. EXPECT_TRUE(res->body.empty());
  4805. }
  4806. TEST_F(ServerTest, URL) {
  4807. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4808. ASSERT_TRUE(res);
  4809. EXPECT_EQ(StatusCode::OK_200, res->status);
  4810. }
  4811. TEST_F(ServerTest, ArrayParam) {
  4812. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4813. ASSERT_TRUE(res);
  4814. EXPECT_EQ(StatusCode::OK_200, res->status);
  4815. }
  4816. TEST_F(ServerTest, NoMultipleHeaders) {
  4817. Headers headers = {{"Content-Length", "5"}};
  4818. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4819. "text/plain");
  4820. ASSERT_TRUE(res);
  4821. EXPECT_EQ(StatusCode::OK_200, res->status);
  4822. }
  4823. TEST_F(ServerTest, PostContentReceiver) {
  4824. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4825. ASSERT_TRUE(res);
  4826. ASSERT_EQ(StatusCode::OK_200, res->status);
  4827. ASSERT_EQ("content", res->body);
  4828. }
  4829. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4830. UploadFormDataItems items = {
  4831. {"text1", "text default", "", ""},
  4832. {"text2", "aωb", "", ""},
  4833. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4834. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4835. {"file3", "", "", "application/octet-stream"},
  4836. };
  4837. auto res = cli_.Post("/content_receiver", items);
  4838. ASSERT_TRUE(res);
  4839. EXPECT_EQ(StatusCode::OK_200, res->status);
  4840. }
  4841. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4842. UploadFormDataItems items = {
  4843. {"text1", "text default", "", ""},
  4844. {"text2", "aωb", "", ""},
  4845. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4846. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4847. {"file3", "", "", "application/octet-stream"},
  4848. };
  4849. auto boundary = std::string("+++++");
  4850. std::string body;
  4851. for (const auto &item : items) {
  4852. body += "--" + boundary + "\r\n";
  4853. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4854. if (!item.filename.empty()) {
  4855. body += "; filename=\"" + item.filename + "\"";
  4856. }
  4857. body += "\r\n";
  4858. if (!item.content_type.empty()) {
  4859. body += "Content-Type: " + item.content_type + "\r\n";
  4860. }
  4861. body += "\r\n";
  4862. body += item.content + "\r\n";
  4863. }
  4864. body += "--" + boundary + "--\r\n";
  4865. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4866. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4867. ASSERT_TRUE(res);
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. }
  4870. TEST_F(ServerTest, PostContentReceiverGzip) {
  4871. cli_.set_compress(true);
  4872. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4873. ASSERT_TRUE(res);
  4874. ASSERT_EQ(StatusCode::OK_200, res->status);
  4875. ASSERT_EQ("content", res->body);
  4876. }
  4877. TEST_F(ServerTest, PutContentReceiver) {
  4878. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4879. ASSERT_TRUE(res);
  4880. ASSERT_EQ(StatusCode::OK_200, res->status);
  4881. ASSERT_EQ("content", res->body);
  4882. }
  4883. TEST_F(ServerTest, PatchContentReceiver) {
  4884. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4885. ASSERT_TRUE(res);
  4886. ASSERT_EQ(StatusCode::OK_200, res->status);
  4887. ASSERT_EQ("content", res->body);
  4888. }
  4889. template <typename ClientType>
  4890. void TestWithHeadersAndContentReceiver(
  4891. ClientType &cli,
  4892. std::function<Result(ClientType &, const std::string &, const Headers &,
  4893. const std::string &, const std::string &,
  4894. ContentReceiver, DownloadProgress)>
  4895. request_func) {
  4896. Headers headers;
  4897. headers.emplace("X-Custom-Header", "test-value");
  4898. std::string received_body;
  4899. auto res = request_func(
  4900. cli, "/content_receiver", headers, "content", "application/json",
  4901. [&](const char *data, size_t data_length) {
  4902. received_body.append(data, data_length);
  4903. return true;
  4904. },
  4905. nullptr);
  4906. ASSERT_TRUE(res);
  4907. EXPECT_EQ(StatusCode::OK_200, res->status);
  4908. EXPECT_EQ("content", received_body);
  4909. }
  4910. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4912. using ClientT = SSLClient;
  4913. #else
  4914. using ClientT = Client;
  4915. #endif
  4916. TestWithHeadersAndContentReceiver<ClientT>(
  4917. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4918. const std::string &body, const std::string &content_type,
  4919. ContentReceiver receiver, DownloadProgress progress) {
  4920. return cli.Post(path, headers, body, content_type, receiver, progress);
  4921. });
  4922. }
  4923. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4925. using ClientT = SSLClient;
  4926. #else
  4927. using ClientT = Client;
  4928. #endif
  4929. TestWithHeadersAndContentReceiver<ClientT>(
  4930. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4931. const std::string &body, const std::string &content_type,
  4932. ContentReceiver receiver, DownloadProgress progress) {
  4933. return cli.Put(path, headers, body, content_type, receiver, progress);
  4934. });
  4935. }
  4936. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4937. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4938. using ClientT = SSLClient;
  4939. #else
  4940. using ClientT = Client;
  4941. #endif
  4942. TestWithHeadersAndContentReceiver<ClientT>(
  4943. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4944. const std::string &body, const std::string &content_type,
  4945. ContentReceiver receiver, DownloadProgress progress) {
  4946. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4947. });
  4948. }
  4949. template <typename ClientType>
  4950. void TestWithHeadersAndContentReceiverWithProgress(
  4951. ClientType &cli,
  4952. std::function<Result(ClientType &, const std::string &, const Headers &,
  4953. const std::string &, const std::string &,
  4954. ContentReceiver, DownloadProgress)>
  4955. request_func) {
  4956. Headers headers;
  4957. headers.emplace("X-Test-Header", "progress-test");
  4958. std::string received_body;
  4959. auto progress_called = false;
  4960. auto res = request_func(
  4961. cli, "/content_receiver", headers, "content", "text/plain",
  4962. [&](const char *data, size_t data_length) {
  4963. received_body.append(data, data_length);
  4964. return true;
  4965. },
  4966. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4967. progress_called = true;
  4968. return true;
  4969. });
  4970. ASSERT_TRUE(res);
  4971. EXPECT_EQ(StatusCode::OK_200, res->status);
  4972. EXPECT_EQ("content", received_body);
  4973. EXPECT_TRUE(progress_called);
  4974. }
  4975. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4976. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4977. using ClientT = SSLClient;
  4978. #else
  4979. using ClientT = Client;
  4980. #endif
  4981. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4982. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4983. const std::string &body, const std::string &content_type,
  4984. ContentReceiver receiver, DownloadProgress progress) {
  4985. return cli.Post(path, headers, body, content_type, receiver, progress);
  4986. });
  4987. }
  4988. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4990. using ClientT = SSLClient;
  4991. #else
  4992. using ClientT = Client;
  4993. #endif
  4994. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4995. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4996. const std::string &body, const std::string &content_type,
  4997. ContentReceiver receiver, DownloadProgress progress) {
  4998. return cli.Put(path, headers, body, content_type, receiver, progress);
  4999. });
  5000. }
  5001. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5002. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5003. using ClientT = SSLClient;
  5004. #else
  5005. using ClientT = Client;
  5006. #endif
  5007. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5008. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5009. const std::string &body, const std::string &content_type,
  5010. ContentReceiver receiver, DownloadProgress progress) {
  5011. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5012. });
  5013. }
  5014. template <typename ClientType>
  5015. void TestWithHeadersAndContentReceiverError(
  5016. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5017. const Headers &, const std::string &,
  5018. const std::string &, ContentReceiver)>
  5019. request_func) {
  5020. Headers headers;
  5021. headers.emplace("X-Error-Test", "true");
  5022. std::string received_body;
  5023. auto receiver_failed = false;
  5024. auto res =
  5025. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5026. [&](const char *data, size_t data_length) {
  5027. received_body.append(data, data_length);
  5028. receiver_failed = true;
  5029. return false;
  5030. });
  5031. ASSERT_FALSE(res);
  5032. EXPECT_TRUE(receiver_failed);
  5033. }
  5034. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5036. using ClientT = SSLClient;
  5037. #else
  5038. using ClientT = Client;
  5039. #endif
  5040. TestWithHeadersAndContentReceiverError<ClientT>(
  5041. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5042. const std::string &body, const std::string &content_type,
  5043. ContentReceiver receiver) {
  5044. return cli.Post(path, headers, body, content_type, receiver);
  5045. });
  5046. }
  5047. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5048. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5049. using ClientT = SSLClient;
  5050. #else
  5051. using ClientT = Client;
  5052. #endif
  5053. TestWithHeadersAndContentReceiverError<ClientT>(
  5054. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5055. const std::string &body, const std::string &content_type,
  5056. ContentReceiver receiver) {
  5057. return cli.Put(path, headers, body, content_type, receiver);
  5058. });
  5059. }
  5060. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5062. using ClientT = SSLClient;
  5063. #else
  5064. using ClientT = Client;
  5065. #endif
  5066. TestWithHeadersAndContentReceiverError<ClientT>(
  5067. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5068. const std::string &body, const std::string &content_type,
  5069. ContentReceiver receiver) {
  5070. return cli.Patch(path, headers, body, content_type, receiver);
  5071. });
  5072. }
  5073. TEST_F(ServerTest, PostQueryStringAndBody) {
  5074. auto res =
  5075. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5076. ASSERT_TRUE(res);
  5077. ASSERT_EQ(StatusCode::OK_200, res->status);
  5078. }
  5079. TEST_F(ServerTest, HTTP2Magic) {
  5080. Request req;
  5081. req.method = "PRI";
  5082. req.path = "*";
  5083. req.body = "SM";
  5084. auto res = std::make_shared<Response>();
  5085. auto error = Error::Success;
  5086. auto ret = cli_.send(req, *res, error);
  5087. ASSERT_TRUE(ret);
  5088. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5089. }
  5090. TEST_F(ServerTest, KeepAlive) {
  5091. auto res = cli_.Get("/hi");
  5092. ASSERT_TRUE(res);
  5093. EXPECT_EQ(StatusCode::OK_200, res->status);
  5094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5095. EXPECT_EQ("Hello World!", res->body);
  5096. res = cli_.Get("/hi");
  5097. ASSERT_TRUE(res);
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5100. EXPECT_EQ("Hello World!", res->body);
  5101. res = cli_.Get("/hi");
  5102. ASSERT_TRUE(res);
  5103. EXPECT_EQ(StatusCode::OK_200, res->status);
  5104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5105. EXPECT_EQ("Hello World!", res->body);
  5106. res = cli_.Get("/not-exist");
  5107. ASSERT_TRUE(res);
  5108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5109. res = cli_.Post("/empty", "", "text/plain");
  5110. ASSERT_TRUE(res);
  5111. EXPECT_EQ(StatusCode::OK_200, res->status);
  5112. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5113. EXPECT_EQ("empty", res->body);
  5114. EXPECT_EQ("close", res->get_header_value("Connection"));
  5115. res = cli_.Post(
  5116. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5117. "text/plain");
  5118. ASSERT_TRUE(res);
  5119. EXPECT_EQ(StatusCode::OK_200, res->status);
  5120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5121. EXPECT_EQ("empty", res->body);
  5122. cli_.set_keep_alive(false);
  5123. res = cli_.Get("/last-request");
  5124. ASSERT_TRUE(res);
  5125. EXPECT_EQ(StatusCode::OK_200, res->status);
  5126. EXPECT_EQ("close", res->get_header_value("Connection"));
  5127. }
  5128. TEST_F(ServerTest, TooManyRedirect) {
  5129. cli_.set_follow_location(true);
  5130. auto res = cli_.Get("/redirect/0");
  5131. ASSERT_TRUE(!res);
  5132. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5133. }
  5134. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5135. Request req;
  5136. req.method = "FOOBAR";
  5137. req.path = "/hi";
  5138. cli_.set_keep_alive(true);
  5139. auto res = cli_.send(req);
  5140. ASSERT_TRUE(res);
  5141. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5142. EXPECT_EQ("close", res->get_header_value("Connection"));
  5143. EXPECT_FALSE(cli_.is_socket_open());
  5144. }
  5145. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5146. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5147. TEST_F(ServerTest, Gzip) {
  5148. Headers headers;
  5149. headers.emplace("Accept-Encoding", "gzip, deflate");
  5150. auto res = cli_.Get("/compress", headers);
  5151. ASSERT_TRUE(res);
  5152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5156. "7890123456789012345678901234567890",
  5157. res->body);
  5158. EXPECT_EQ(StatusCode::OK_200, res->status);
  5159. }
  5160. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5161. Headers headers;
  5162. headers.emplace("Accept-Encoding", "");
  5163. auto res = cli_.Get("/compress", headers);
  5164. ASSERT_TRUE(res);
  5165. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5169. "7890123456789012345678901234567890",
  5170. res->body);
  5171. EXPECT_EQ(StatusCode::OK_200, res->status);
  5172. }
  5173. TEST_F(ServerTest, GzipWithContentReceiver) {
  5174. Headers headers;
  5175. headers.emplace("Accept-Encoding", "gzip, deflate");
  5176. std::string body;
  5177. auto res = cli_.Get("/compress", headers,
  5178. [&](const char *data, uint64_t data_length) {
  5179. EXPECT_EQ(100U, data_length);
  5180. body.append(data, data_length);
  5181. return true;
  5182. });
  5183. ASSERT_TRUE(res);
  5184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5186. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5187. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5188. "7890123456789012345678901234567890",
  5189. body);
  5190. EXPECT_EQ(StatusCode::OK_200, res->status);
  5191. }
  5192. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5193. Headers headers;
  5194. headers.emplace("Accept-Encoding", "gzip, deflate");
  5195. cli_.set_decompress(false);
  5196. auto res = cli_.Get("/compress", headers);
  5197. ASSERT_TRUE(res);
  5198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5199. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5200. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5201. EXPECT_EQ(33U, res->body.size());
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. }
  5204. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5205. Headers headers;
  5206. headers.emplace("Accept-Encoding", "");
  5207. std::string body;
  5208. auto res = cli_.Get("/compress", headers,
  5209. [&](const char *data, uint64_t data_length) {
  5210. EXPECT_EQ(100U, data_length);
  5211. body.append(data, data_length);
  5212. return true;
  5213. });
  5214. ASSERT_TRUE(res);
  5215. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5217. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5218. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5219. "7890123456789012345678901234567890",
  5220. body);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. }
  5223. TEST_F(ServerTest, NoGzip) {
  5224. Headers headers;
  5225. headers.emplace("Accept-Encoding", "gzip, deflate");
  5226. auto res = cli_.Get("/nocompress", headers);
  5227. ASSERT_TRUE(res);
  5228. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5229. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5230. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5231. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5232. "7890123456789012345678901234567890",
  5233. res->body);
  5234. EXPECT_EQ(StatusCode::OK_200, res->status);
  5235. }
  5236. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5237. Headers headers;
  5238. headers.emplace("Accept-Encoding", "gzip, deflate");
  5239. std::string body;
  5240. auto res = cli_.Get("/nocompress", headers,
  5241. [&](const char *data, uint64_t data_length) {
  5242. EXPECT_EQ(100U, data_length);
  5243. body.append(data, data_length);
  5244. return true;
  5245. });
  5246. ASSERT_TRUE(res);
  5247. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5248. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5249. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5250. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5251. "7890123456789012345678901234567890",
  5252. body);
  5253. EXPECT_EQ(StatusCode::OK_200, res->status);
  5254. }
  5255. TEST_F(ServerTest, MultipartFormDataGzip) {
  5256. UploadFormDataItems items = {
  5257. {"key1", "test", "", ""},
  5258. {"key2", "--abcdefg123", "", ""},
  5259. };
  5260. cli_.set_compress(true);
  5261. auto res = cli_.Post("/compress-multipart", items);
  5262. ASSERT_TRUE(res);
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. }
  5265. #endif
  5266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5267. TEST_F(ServerTest, Brotli) {
  5268. Headers headers;
  5269. headers.emplace("Accept-Encoding", "br");
  5270. auto res = cli_.Get("/compress", headers);
  5271. ASSERT_TRUE(res);
  5272. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5273. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5274. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5275. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5276. "7890123456789012345678901234567890",
  5277. res->body);
  5278. EXPECT_EQ(StatusCode::OK_200, res->status);
  5279. }
  5280. #endif
  5281. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5282. TEST_F(ServerTest, Zstd) {
  5283. Headers headers;
  5284. headers.emplace("Accept-Encoding", "zstd");
  5285. auto res = cli_.Get("/compress", headers);
  5286. ASSERT_TRUE(res);
  5287. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5288. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5289. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5290. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5291. "7890123456789012345678901234567890",
  5292. res->body);
  5293. EXPECT_EQ(StatusCode::OK_200, res->status);
  5294. }
  5295. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5296. Headers headers;
  5297. headers.emplace("Accept-Encoding", "");
  5298. auto res = cli_.Get("/compress", headers);
  5299. ASSERT_TRUE(res);
  5300. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5301. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5302. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5303. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5304. "7890123456789012345678901234567890",
  5305. res->body);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. }
  5308. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5309. Headers headers;
  5310. headers.emplace("Accept-Encoding", "zstd");
  5311. std::string body;
  5312. auto res = cli_.Get("/compress", headers,
  5313. [&](const char *data, uint64_t data_length) {
  5314. EXPECT_EQ(100U, data_length);
  5315. body.append(data, data_length);
  5316. return true;
  5317. });
  5318. ASSERT_TRUE(res);
  5319. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5321. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5322. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5323. "7890123456789012345678901234567890",
  5324. body);
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. }
  5327. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5328. Headers headers;
  5329. headers.emplace("Accept-Encoding", "zstd");
  5330. cli_.set_decompress(false);
  5331. auto res = cli_.Get("/compress", headers);
  5332. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5333. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5334. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5335. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5336. ASSERT_TRUE(res);
  5337. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5339. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5340. EXPECT_EQ(StatusCode::OK_200, res->status);
  5341. ASSERT_EQ(26U, res->body.size());
  5342. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5343. 0);
  5344. }
  5345. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5346. Headers headers;
  5347. headers.emplace("Accept-Encoding", "");
  5348. std::string body;
  5349. auto res = cli_.Get("/compress", headers,
  5350. [&](const char *data, uint64_t data_length) {
  5351. EXPECT_EQ(100U, data_length);
  5352. body.append(data, data_length);
  5353. return true;
  5354. });
  5355. ASSERT_TRUE(res);
  5356. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5359. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5360. "7890123456789012345678901234567890",
  5361. body);
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. }
  5364. TEST_F(ServerTest, NoZstd) {
  5365. Headers headers;
  5366. headers.emplace("Accept-Encoding", "zstd");
  5367. auto res = cli_.Get("/nocompress", headers);
  5368. ASSERT_TRUE(res);
  5369. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5370. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5371. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5372. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5373. "7890123456789012345678901234567890",
  5374. res->body);
  5375. EXPECT_EQ(StatusCode::OK_200, res->status);
  5376. }
  5377. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5378. Headers headers;
  5379. headers.emplace("Accept-Encoding", "zstd");
  5380. std::string body;
  5381. auto res = cli_.Get("/nocompress", headers,
  5382. [&](const char *data, uint64_t data_length) {
  5383. EXPECT_EQ(100U, data_length);
  5384. body.append(data, data_length);
  5385. return true;
  5386. });
  5387. ASSERT_TRUE(res);
  5388. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5389. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5390. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5391. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5392. "7890123456789012345678901234567890",
  5393. body);
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. }
  5396. // TODO: How to enable zstd ??
  5397. TEST_F(ServerTest, MultipartFormDataZstd) {
  5398. UploadFormDataItems items = {
  5399. {"key1", "test", "", ""},
  5400. {"key2", "--abcdefg123", "", ""},
  5401. };
  5402. Headers headers;
  5403. headers.emplace("Accept-Encoding", "zstd");
  5404. cli_.set_compress(true);
  5405. auto res = cli_.Post("/compress-multipart", headers, items);
  5406. ASSERT_TRUE(res);
  5407. EXPECT_EQ(StatusCode::OK_200, res->status);
  5408. }
  5409. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Put(
  5414. "/put", headers, 3,
  5415. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5416. sink.os << "PUT";
  5417. return true;
  5418. },
  5419. "text/plain");
  5420. ASSERT_TRUE(res);
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("PUT", res->body);
  5423. }
  5424. // Pre-compression logging tests
  5425. TEST_F(ServerTest, PreCompressionLogging) {
  5426. // Test data for compression (matches the actual /compress endpoint content)
  5427. const std::string test_content =
  5428. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5429. "3456789012345678901234567890";
  5430. // Variables to capture logging data
  5431. std::string pre_compression_body;
  5432. std::string pre_compression_content_type;
  5433. std::string pre_compression_content_encoding;
  5434. std::string post_compression_body;
  5435. std::string post_compression_content_type;
  5436. std::string post_compression_content_encoding;
  5437. // Set up pre-compression logger
  5438. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5439. const Response &res) {
  5440. pre_compression_body = res.body;
  5441. pre_compression_content_type = res.get_header_value("Content-Type");
  5442. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5443. });
  5444. // Set up post-compression logger
  5445. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5446. post_compression_body = res.body;
  5447. post_compression_content_type = res.get_header_value("Content-Type");
  5448. post_compression_content_encoding =
  5449. res.get_header_value("Content-Encoding");
  5450. });
  5451. // Test with gzip compression
  5452. Headers headers;
  5453. headers.emplace("Accept-Encoding", "gzip");
  5454. auto res = cli_.Get("/compress", headers);
  5455. // Verify response was compressed
  5456. ASSERT_TRUE(res);
  5457. EXPECT_EQ(StatusCode::OK_200, res->status);
  5458. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5459. // Verify pre-compression logger captured uncompressed content
  5460. EXPECT_EQ(test_content, pre_compression_body);
  5461. EXPECT_EQ("text/plain", pre_compression_content_type);
  5462. EXPECT_TRUE(pre_compression_content_encoding
  5463. .empty()); // No encoding header before compression
  5464. // Verify post-compression logger captured compressed content
  5465. EXPECT_NE(test_content,
  5466. post_compression_body); // Should be different after compression
  5467. EXPECT_EQ("text/plain", post_compression_content_type);
  5468. EXPECT_EQ("gzip", post_compression_content_encoding);
  5469. // Verify compressed content is smaller
  5470. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5471. }
  5472. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5473. const std::string test_content =
  5474. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5475. "3456789012345678901234567890";
  5476. std::string pre_compression_body;
  5477. std::string post_compression_body;
  5478. svr_.set_pre_compression_logger(
  5479. [&](const Request & /*req*/, const Response &res) {
  5480. pre_compression_body = res.body;
  5481. });
  5482. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5483. post_compression_body = res.body;
  5484. });
  5485. Headers headers;
  5486. headers.emplace("Accept-Encoding", "br");
  5487. auto res = cli_.Get("/compress", headers);
  5488. ASSERT_TRUE(res);
  5489. EXPECT_EQ(StatusCode::OK_200, res->status);
  5490. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5491. // Verify pre-compression content is uncompressed
  5492. EXPECT_EQ(test_content, pre_compression_body);
  5493. // Verify post-compression content is compressed
  5494. EXPECT_NE(test_content, post_compression_body);
  5495. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5496. }
  5497. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5498. const std::string test_content =
  5499. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5500. "3456789012345678901234567890";
  5501. std::string pre_compression_body;
  5502. std::string post_compression_body;
  5503. svr_.set_pre_compression_logger(
  5504. [&](const Request & /*req*/, const Response &res) {
  5505. pre_compression_body = res.body;
  5506. });
  5507. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5508. post_compression_body = res.body;
  5509. });
  5510. // Request without compression (use /nocompress endpoint)
  5511. Headers headers;
  5512. auto res = cli_.Get("/nocompress", headers);
  5513. ASSERT_TRUE(res);
  5514. EXPECT_EQ(StatusCode::OK_200, res->status);
  5515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5516. // Pre-compression logger should not be called when no compression is applied
  5517. EXPECT_TRUE(
  5518. pre_compression_body.empty()); // Pre-compression logger not called
  5519. EXPECT_EQ(
  5520. test_content,
  5521. post_compression_body); // Post-compression logger captures final content
  5522. }
  5523. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5524. const std::string test_content =
  5525. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5526. "3456789012345678901234567890";
  5527. std::string pre_compression_body;
  5528. bool pre_logger_called = false;
  5529. // Set only pre-compression logger
  5530. svr_.set_pre_compression_logger(
  5531. [&](const Request & /*req*/, const Response &res) {
  5532. pre_compression_body = res.body;
  5533. pre_logger_called = true;
  5534. });
  5535. Headers headers;
  5536. headers.emplace("Accept-Encoding", "gzip");
  5537. auto res = cli_.Get("/compress", headers);
  5538. ASSERT_TRUE(res);
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5541. // Verify pre-compression logger was called
  5542. EXPECT_TRUE(pre_logger_called);
  5543. EXPECT_EQ(test_content, pre_compression_body);
  5544. }
  5545. TEST(ZstdDecompressor, ChunkedDecompression) {
  5546. std::string data;
  5547. for (size_t i = 0; i < 32 * 1024; ++i) {
  5548. data.push_back(static_cast<char>('a' + i % 26));
  5549. }
  5550. std::string compressed_data;
  5551. {
  5552. httplib::detail::zstd_compressor compressor;
  5553. bool result = compressor.compress(
  5554. data.data(), data.size(),
  5555. /*last=*/true,
  5556. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5557. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5558. compressed_data_size);
  5559. return true;
  5560. });
  5561. ASSERT_TRUE(result);
  5562. }
  5563. std::string decompressed_data;
  5564. {
  5565. httplib::detail::zstd_decompressor decompressor;
  5566. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5567. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5568. size_t chunk_size = 130;
  5569. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5570. chunk_begin += chunk_size) {
  5571. size_t current_chunk_size =
  5572. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5573. bool result = decompressor.decompress(
  5574. compressed_data.data() + chunk_begin, current_chunk_size,
  5575. [&](const char *decompressed_data_chunk,
  5576. size_t decompressed_data_chunk_size) {
  5577. decompressed_data.insert(decompressed_data.size(),
  5578. decompressed_data_chunk,
  5579. decompressed_data_chunk_size);
  5580. return true;
  5581. });
  5582. ASSERT_TRUE(result);
  5583. }
  5584. }
  5585. ASSERT_EQ(data, decompressed_data);
  5586. }
  5587. TEST(ZstdDecompressor, Decompress) {
  5588. std::string original_text = "Compressed with ZSTD";
  5589. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5590. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5591. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5592. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5593. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5594. std::string decompressed_data;
  5595. {
  5596. httplib::detail::zstd_decompressor decompressor;
  5597. bool result = decompressor.decompress(
  5598. compressed_data.data(), compressed_data.size(),
  5599. [&](const char *decompressed_data_chunk,
  5600. size_t decompressed_data_chunk_size) {
  5601. decompressed_data.insert(decompressed_data.size(),
  5602. decompressed_data_chunk,
  5603. decompressed_data_chunk_size);
  5604. return true;
  5605. });
  5606. ASSERT_TRUE(result);
  5607. }
  5608. ASSERT_EQ(original_text, decompressed_data);
  5609. }
  5610. #endif
  5611. // Sends a raw request to a server listening at HOST:PORT.
  5612. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5613. std::string *resp = nullptr) {
  5614. auto error = Error::Success;
  5615. auto client_sock = detail::create_client_socket(
  5616. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5617. /*connection_timeout_sec=*/5, 0,
  5618. /*read_timeout_sec=*/5, 0,
  5619. /*write_timeout_sec=*/5, 0, std::string(), error);
  5620. if (client_sock == INVALID_SOCKET) { return false; }
  5621. auto ret = detail::process_client_socket(
  5622. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5623. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5624. if (req.size() !=
  5625. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5626. return false;
  5627. }
  5628. char buf[512];
  5629. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5630. while (line_reader.getline()) {
  5631. if (resp) { *resp += line_reader.ptr(); }
  5632. }
  5633. return true;
  5634. });
  5635. detail::close_socket(client_sock);
  5636. return ret;
  5637. }
  5638. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5639. Server svr;
  5640. std::string header_value;
  5641. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5642. header_value = req.get_header_value("foo");
  5643. res.set_content("ok", "text/plain");
  5644. });
  5645. thread t = thread([&] { svr.listen(HOST, PORT); });
  5646. auto se = detail::scope_exit([&] {
  5647. svr.stop();
  5648. t.join();
  5649. ASSERT_FALSE(svr.is_running());
  5650. });
  5651. svr.wait_until_ready();
  5652. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5653. // like characters are not treated the same - use vertical tab and escape.
  5654. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5655. "foo: \t \v bar \x1B\t \r\n"
  5656. "Connection: close\r\n"
  5657. "\r\n";
  5658. std::string res;
  5659. ASSERT_TRUE(send_request(5, req, &res));
  5660. EXPECT_EQ(header_value, "");
  5661. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5662. }
  5663. // Sends a raw request and verifies that there isn't a crash or exception.
  5664. static void test_raw_request(const std::string &req,
  5665. std::string *out = nullptr) {
  5666. Server svr;
  5667. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5668. res.set_content("ok", "text/plain");
  5669. });
  5670. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5671. res.set_content("ok", "text/plain");
  5672. });
  5673. svr.Get("/header_field_value_check",
  5674. [&](const Request & /*req*/, Response &res) {
  5675. res.set_content("ok", "text/plain");
  5676. });
  5677. // Server read timeout must be longer than the client read timeout for the
  5678. // bug to reproduce, probably to force the server to process a request
  5679. // without a trailing blank line.
  5680. const time_t client_read_timeout_sec = 1;
  5681. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5682. bool listen_thread_ok = false;
  5683. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5684. auto se = detail::scope_exit([&] {
  5685. svr.stop();
  5686. t.join();
  5687. ASSERT_FALSE(svr.is_running());
  5688. EXPECT_TRUE(listen_thread_ok);
  5689. });
  5690. svr.wait_until_ready();
  5691. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5692. }
  5693. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5694. // A certain header line causes an exception if the header property is parsed
  5695. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5696. test_raw_request(
  5697. "GET /hi HTTP/1.1\r\n"
  5698. " : "
  5699. " "
  5700. " ");
  5701. }
  5702. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5703. // A certain header line causes an exception if the header property *name* is
  5704. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5705. // greedy matcher and requires backtracking when there are a lot of ":"
  5706. // characters.
  5707. // This occurs with libc++ but not libstdc++.
  5708. test_raw_request(
  5709. "GET /hi HTTP/1.1\r\n"
  5710. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5711. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5712. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5713. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5714. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5715. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5716. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5717. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5718. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5719. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5720. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5722. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5723. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5724. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5725. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5726. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5727. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5728. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5729. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5730. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5731. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5732. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5733. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5734. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5735. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5736. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5737. "&&&%%%");
  5738. }
  5739. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5740. // Make sure this doesn't crash the server.
  5741. // In a previous version of the header line regex, the "\r" rendered the line
  5742. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5743. // a new position where the leading white space ended and the field value
  5744. // began.
  5745. // The crash occurs with libc++ but not libstdc++.
  5746. test_raw_request("GET /hi HTTP/1.1\r\n"
  5747. "a:" +
  5748. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5749. "\r\n"
  5750. "\r\n");
  5751. }
  5752. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5753. std::string out;
  5754. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5755. "Content-Type: text/plain\r\n"
  5756. "Transfer-Encoding: chunked\r\n"
  5757. "\r\n"
  5758. "nothex\r\n",
  5759. &out);
  5760. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5761. }
  5762. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5763. std::string out;
  5764. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5765. "Content-Type: text/plain\r\n"
  5766. "Transfer-Encoding: chunked\r\n"
  5767. "\r\n"
  5768. "3\r\n"
  5769. "xyz\r\n"
  5770. "NaN\r\n",
  5771. &out);
  5772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5773. }
  5774. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5775. std::string out;
  5776. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5777. "Content-Type: text/plain\r\n"
  5778. "Transfer-Encoding: chunked\r\n"
  5779. "\r\n"
  5780. // Length is too large for 64 bits.
  5781. "1ffffffffffffffff\r\n"
  5782. "xyz\r\n",
  5783. &out);
  5784. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5785. }
  5786. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5787. test_raw_request("GET /hi HTTP/1.1\r\n"
  5788. "Content-Type: text/plain\r\n\r");
  5789. }
  5790. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5791. std::string out;
  5792. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5793. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5794. }
  5795. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5796. Server svr;
  5797. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5798. EXPECT_TRUE(!req.remote_addr.empty());
  5799. });
  5800. thread t = thread([&] { svr.listen(HOST, PORT); });
  5801. auto se = detail::scope_exit([&] {
  5802. svr.stop();
  5803. t.join();
  5804. ASSERT_FALSE(svr.is_running());
  5805. });
  5806. svr.wait_until_ready();
  5807. // Send an invalid request line to trigger Bad Request
  5808. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5809. std::string out;
  5810. ASSERT_TRUE(send_request(5, bad_req, &out));
  5811. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5812. }
  5813. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5814. std::string out;
  5815. std::string request(
  5816. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5817. test_raw_request(request, &out);
  5818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5819. }
  5820. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5821. std::string out;
  5822. std::string request(
  5823. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5824. test_raw_request(request, &out);
  5825. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5826. }
  5827. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5828. std::string out;
  5829. std::string request(
  5830. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5831. test_raw_request(request, &out);
  5832. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5833. }
  5834. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5835. std::string out;
  5836. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5837. "Test: \r\n\r\n",
  5838. &out);
  5839. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5840. }
  5841. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5842. Server svr;
  5843. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5844. res.set_header("Cache-Control", "no-cache");
  5845. res.set_chunked_content_provider(
  5846. "text/event-stream", [](size_t offset, DataSink &sink) {
  5847. std::string s = "data:";
  5848. s += std::to_string(offset);
  5849. s += "\n\n";
  5850. auto ret = sink.write(s.data(), s.size());
  5851. EXPECT_TRUE(ret);
  5852. std::this_thread::sleep_for(std::chrono::seconds(1));
  5853. return true;
  5854. });
  5855. });
  5856. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5857. svr.wait_until_ready();
  5858. Client client(HOST, PORT);
  5859. const Headers headers = {{"Accept", "text/event-stream"}};
  5860. auto get_thread = std::thread([&client, &headers]() {
  5861. auto res = client.Get(
  5862. "/events", headers,
  5863. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5864. });
  5865. auto se = detail::scope_exit([&] {
  5866. svr.stop();
  5867. get_thread.join();
  5868. listen_thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. // Give GET time to get a few messages.
  5872. std::this_thread::sleep_for(std::chrono::seconds(2));
  5873. }
  5874. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5875. httplib::Server svr;
  5876. svr.Post("/hi",
  5877. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5878. res.status = StatusCode::OK_200;
  5879. });
  5880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5881. svr.wait_until_ready();
  5882. Client cli(HOST, PORT);
  5883. auto res = cli.Post("/hi", "data", "text/plain");
  5884. ASSERT_TRUE(res);
  5885. EXPECT_EQ(StatusCode::OK_200, res->status);
  5886. svr.stop();
  5887. thread.join();
  5888. ASSERT_FALSE(svr.is_running());
  5889. res = cli.Post("/hi", "data", "text/plain");
  5890. ASSERT_FALSE(res);
  5891. }
  5892. TEST(ServerStopTest, ListenFailure) {
  5893. Server svr;
  5894. auto t = thread([&]() {
  5895. auto ret = svr.listen("????", PORT);
  5896. EXPECT_FALSE(ret);
  5897. });
  5898. svr.wait_until_ready();
  5899. svr.stop();
  5900. t.join();
  5901. }
  5902. TEST(ServerStopTest, Decommision) {
  5903. Server svr;
  5904. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5905. for (int i = 0; i < 4; i++) {
  5906. auto is_even = !(i % 2);
  5907. std::thread t{[&] {
  5908. try {
  5909. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5910. if (is_even) {
  5911. throw std::runtime_error("Some thing that happens to go wrong.");
  5912. }
  5913. svr.listen(HOST, PORT);
  5914. } catch (...) { svr.decommission(); }
  5915. }};
  5916. svr.wait_until_ready();
  5917. // Server is up
  5918. {
  5919. Client cli(HOST, PORT);
  5920. auto res = cli.Get("/hi");
  5921. if (is_even) {
  5922. EXPECT_FALSE(res);
  5923. } else {
  5924. EXPECT_TRUE(res);
  5925. EXPECT_EQ("hi...", res->body);
  5926. }
  5927. }
  5928. svr.stop();
  5929. t.join();
  5930. // Server is down...
  5931. {
  5932. Client cli(HOST, PORT);
  5933. auto res = cli.Get("/hi");
  5934. EXPECT_FALSE(res);
  5935. }
  5936. }
  5937. }
  5938. // Helper function for string body upload progress tests
  5939. template <typename SetupHandler, typename ClientCall>
  5940. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5941. ClientCall &&client_call,
  5942. const string &body) {
  5943. Server svr;
  5944. setup_handler(svr);
  5945. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5946. auto se = detail::scope_exit([&] {
  5947. svr.stop();
  5948. t.join();
  5949. });
  5950. svr.wait_until_ready();
  5951. Client cli(HOST, PORT);
  5952. vector<uint64_t> progress_values;
  5953. bool progress_called = false;
  5954. auto res =
  5955. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  5956. progress_values.push_back(current);
  5957. progress_called = true;
  5958. return true;
  5959. });
  5960. ASSERT_TRUE(res);
  5961. EXPECT_EQ(200, res->status);
  5962. EXPECT_TRUE(progress_called);
  5963. }
  5964. TEST(UploadProgressTest, PostStringBodyBasic) {
  5965. TestStringBodyUploadProgress(
  5966. [](Server &svr) {
  5967. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  5968. res.set_content("received", "text/plain");
  5969. });
  5970. },
  5971. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5972. return cli.Post("/test", body, "text/plain", progress_callback);
  5973. },
  5974. "test data for upload progress");
  5975. }
  5976. TEST(UploadProgressTest, PutStringBodyBasic) {
  5977. TestStringBodyUploadProgress(
  5978. [](Server &svr) {
  5979. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  5980. res.set_content("put received", "text/plain");
  5981. });
  5982. },
  5983. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5984. return cli.Put("/test", body, "text/plain", progress_callback);
  5985. },
  5986. "put test data for upload progress");
  5987. }
  5988. TEST(UploadProgressTest, PatchStringBodyBasic) {
  5989. TestStringBodyUploadProgress(
  5990. [](Server &svr) {
  5991. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  5992. res.set_content("patch received", "text/plain");
  5993. });
  5994. },
  5995. [](Client &cli, const string &body, UploadProgress progress_callback) {
  5996. return cli.Patch("/test", body, "text/plain", progress_callback);
  5997. },
  5998. "patch test data for upload progress");
  5999. }
  6000. // Helper function for content provider upload progress tests
  6001. template <typename SetupHandler, typename ClientCall>
  6002. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6003. ClientCall &&client_call) {
  6004. Server svr;
  6005. setup_handler(svr);
  6006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6007. auto se = detail::scope_exit([&] {
  6008. svr.stop();
  6009. t.join();
  6010. });
  6011. svr.wait_until_ready();
  6012. Client cli(HOST, PORT);
  6013. vector<uint64_t> progress_values;
  6014. auto res =
  6015. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6016. progress_values.push_back(current);
  6017. return true;
  6018. });
  6019. ASSERT_TRUE(res);
  6020. EXPECT_EQ(200, res->status);
  6021. EXPECT_FALSE(progress_values.empty());
  6022. }
  6023. TEST(UploadProgressTest, PostContentProviderProgress) {
  6024. TestContentProviderUploadProgress(
  6025. [](Server &svr) {
  6026. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6027. res.set_content("provider received", "text/plain");
  6028. });
  6029. },
  6030. [](Client &cli, UploadProgress progress_callback) {
  6031. return cli.Post(
  6032. "/test", 10,
  6033. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6034. sink.os << "test data";
  6035. return true;
  6036. },
  6037. "text/plain", progress_callback);
  6038. });
  6039. }
  6040. // Helper function for multipart upload progress tests
  6041. template <typename SetupHandler, typename ClientCall>
  6042. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6043. ClientCall &&client_call,
  6044. const string &endpoint) {
  6045. Server svr;
  6046. setup_handler(svr);
  6047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6048. auto se = detail::scope_exit([&] {
  6049. svr.stop();
  6050. t.join();
  6051. });
  6052. svr.wait_until_ready();
  6053. Client cli(HOST, PORT);
  6054. vector<uint64_t> progress_values;
  6055. UploadFormDataItems items = {
  6056. {"field1", "value1", "", ""},
  6057. {"field2", "longer value for progress tracking test", "", ""},
  6058. {"file1", "file content data for upload progress", "test.txt",
  6059. "text/plain"}};
  6060. auto res = client_call(cli, endpoint, items,
  6061. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6062. progress_values.push_back(current);
  6063. return true;
  6064. });
  6065. ASSERT_TRUE(res);
  6066. EXPECT_EQ(200, res->status);
  6067. EXPECT_FALSE(progress_values.empty());
  6068. }
  6069. TEST(UploadProgressTest, PostMultipartProgress) {
  6070. TestMultipartUploadProgress(
  6071. [](Server &svr) {
  6072. svr.Post("/multipart", [](const Request &req, Response &res) {
  6073. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6074. res.set_content("multipart received", "text/plain");
  6075. });
  6076. },
  6077. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6078. UploadProgress progress_callback) {
  6079. return cli.Post(endpoint, items, progress_callback);
  6080. },
  6081. "/multipart");
  6082. }
  6083. // Helper function for basic download progress tests
  6084. template <typename SetupHandler, typename ClientCall>
  6085. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6086. ClientCall &&client_call, const string &endpoint,
  6087. size_t expected_content_size) {
  6088. Server svr;
  6089. setup_handler(svr);
  6090. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6091. auto se = detail::scope_exit([&] {
  6092. svr.stop();
  6093. t.join();
  6094. });
  6095. svr.wait_until_ready();
  6096. Client cli(HOST, PORT);
  6097. vector<uint64_t> progress_values;
  6098. auto res = client_call(cli, endpoint,
  6099. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6100. progress_values.push_back(current);
  6101. return true;
  6102. });
  6103. ASSERT_TRUE(res);
  6104. EXPECT_EQ(200, res->status);
  6105. EXPECT_FALSE(progress_values.empty());
  6106. EXPECT_EQ(expected_content_size, res->body.size());
  6107. }
  6108. TEST(DownloadProgressTest, GetBasic) {
  6109. TestBasicDownloadProgress(
  6110. [](Server &svr) {
  6111. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6112. string content(1000, 'D');
  6113. res.set_content(content, "text/plain");
  6114. });
  6115. },
  6116. [](Client &cli, const string &endpoint,
  6117. DownloadProgress progress_callback) {
  6118. return cli.Get(endpoint, progress_callback);
  6119. },
  6120. "/download", 1000u);
  6121. }
  6122. // Helper function for content receiver download progress tests
  6123. template <typename SetupHandler, typename ClientCall>
  6124. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6125. ClientCall &&client_call,
  6126. const string &endpoint,
  6127. size_t expected_content_size) {
  6128. Server svr;
  6129. setup_handler(svr);
  6130. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6131. auto se = detail::scope_exit([&] {
  6132. svr.stop();
  6133. t.join();
  6134. });
  6135. svr.wait_until_ready();
  6136. Client cli(HOST, PORT);
  6137. vector<uint64_t> progress_values;
  6138. string received_body;
  6139. auto res = client_call(
  6140. cli, endpoint,
  6141. [&](const char *data, size_t data_length) -> bool {
  6142. received_body.append(data, data_length);
  6143. return true;
  6144. },
  6145. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6146. progress_values.push_back(current);
  6147. return true;
  6148. });
  6149. ASSERT_TRUE(res);
  6150. EXPECT_EQ(200, res->status);
  6151. EXPECT_FALSE(progress_values.empty());
  6152. EXPECT_EQ(expected_content_size, received_body.size());
  6153. EXPECT_TRUE(res->body.empty());
  6154. }
  6155. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6156. TestContentReceiverDownloadProgress(
  6157. [](Server &svr) {
  6158. svr.Get("/download-receiver",
  6159. [](const Request & /*req*/, Response &res) {
  6160. string content(2000, 'R');
  6161. res.set_content(content, "text/plain");
  6162. });
  6163. },
  6164. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6165. DownloadProgress progress_callback) {
  6166. return cli.Get(endpoint, content_receiver, progress_callback);
  6167. },
  6168. "/download-receiver", 2000u);
  6169. }
  6170. TEST(StreamingTest, NoContentLengthStreaming) {
  6171. Server svr;
  6172. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6173. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6174. if (offset < 6) {
  6175. sink.os << (offset < 3 ? "a" : "b");
  6176. } else {
  6177. sink.done();
  6178. }
  6179. return true;
  6180. });
  6181. });
  6182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6183. auto listen_se = detail::scope_exit([&] {
  6184. svr.stop();
  6185. listen_thread.join();
  6186. ASSERT_FALSE(svr.is_running());
  6187. });
  6188. svr.wait_until_ready();
  6189. Client client(HOST, PORT);
  6190. auto get_thread = std::thread([&client]() {
  6191. std::string s;
  6192. auto res =
  6193. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6194. s += std::string(data, len);
  6195. return true;
  6196. });
  6197. ASSERT_TRUE(res);
  6198. EXPECT_EQ(StatusCode::OK_200, res->status);
  6199. EXPECT_EQ("aaabbb", s);
  6200. });
  6201. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6202. // Give GET time to get a few messages.
  6203. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6204. }
  6205. TEST(MountTest, Unmount) {
  6206. Server svr;
  6207. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6208. auto se = detail::scope_exit([&] {
  6209. svr.stop();
  6210. listen_thread.join();
  6211. ASSERT_FALSE(svr.is_running());
  6212. });
  6213. svr.wait_until_ready();
  6214. Client cli("localhost", PORT);
  6215. svr.set_mount_point("/mount2", "./www2");
  6216. auto res = cli.Get("/");
  6217. ASSERT_TRUE(res);
  6218. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6219. res = cli.Get("/mount2/dir/test.html");
  6220. ASSERT_TRUE(res);
  6221. EXPECT_EQ(StatusCode::OK_200, res->status);
  6222. svr.set_mount_point("/", "./www");
  6223. res = cli.Get("/dir/");
  6224. ASSERT_TRUE(res);
  6225. EXPECT_EQ(StatusCode::OK_200, res->status);
  6226. svr.remove_mount_point("/");
  6227. res = cli.Get("/dir/");
  6228. ASSERT_TRUE(res);
  6229. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6230. svr.remove_mount_point("/mount2");
  6231. res = cli.Get("/mount2/dir/test.html");
  6232. ASSERT_TRUE(res);
  6233. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6234. }
  6235. TEST(MountTest, Redicect) {
  6236. Server svr;
  6237. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6238. auto se = detail::scope_exit([&] {
  6239. svr.stop();
  6240. listen_thread.join();
  6241. ASSERT_FALSE(svr.is_running());
  6242. });
  6243. svr.set_mount_point("/", "./www");
  6244. svr.wait_until_ready();
  6245. Client cli("localhost", PORT);
  6246. auto res = cli.Get("/dir/");
  6247. ASSERT_TRUE(res);
  6248. EXPECT_EQ(StatusCode::OK_200, res->status);
  6249. res = cli.Get("/dir");
  6250. ASSERT_TRUE(res);
  6251. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6252. res = cli.Get("/file");
  6253. ASSERT_TRUE(res);
  6254. EXPECT_EQ(StatusCode::OK_200, res->status);
  6255. res = cli.Get("/file/");
  6256. ASSERT_TRUE(res);
  6257. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6258. cli.set_follow_location(true);
  6259. res = cli.Get("/dir");
  6260. ASSERT_TRUE(res);
  6261. EXPECT_EQ(StatusCode::OK_200, res->status);
  6262. }
  6263. TEST(MountTest, MultibytesPathName) {
  6264. Server svr;
  6265. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6266. auto se = detail::scope_exit([&] {
  6267. svr.stop();
  6268. listen_thread.join();
  6269. ASSERT_FALSE(svr.is_running());
  6270. });
  6271. svr.set_mount_point("/", "./www");
  6272. svr.wait_until_ready();
  6273. Client cli("localhost", PORT);
  6274. auto res = cli.Get(u8"/日本語Dir/日本語File.txt");
  6275. ASSERT_TRUE(res);
  6276. EXPECT_EQ(StatusCode::OK_200, res->status);
  6277. EXPECT_EQ(u8"日本語コンテンツ", res->body);
  6278. }
  6279. TEST(KeepAliveTest, ReadTimeout) {
  6280. Server svr;
  6281. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6282. std::this_thread::sleep_for(std::chrono::seconds(2));
  6283. res.set_content("a", "text/plain");
  6284. });
  6285. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6286. res.set_content("b", "text/plain");
  6287. });
  6288. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6289. auto se = detail::scope_exit([&] {
  6290. svr.stop();
  6291. listen_thread.join();
  6292. ASSERT_FALSE(svr.is_running());
  6293. });
  6294. svr.wait_until_ready();
  6295. Client cli("localhost", PORT);
  6296. cli.set_keep_alive(true);
  6297. cli.set_read_timeout(std::chrono::seconds(1));
  6298. auto resa = cli.Get("/a");
  6299. ASSERT_FALSE(resa);
  6300. EXPECT_EQ(Error::Read, resa.error());
  6301. auto resb = cli.Get("/b");
  6302. ASSERT_TRUE(resb);
  6303. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6304. EXPECT_EQ("b", resb->body);
  6305. }
  6306. TEST(KeepAliveTest, MaxCount) {
  6307. size_t keep_alive_max_count = 3;
  6308. Server svr;
  6309. svr.set_keep_alive_max_count(keep_alive_max_count);
  6310. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6311. res.set_content("Hello World!", "text/plain");
  6312. });
  6313. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6314. auto se = detail::scope_exit([&] {
  6315. svr.stop();
  6316. listen_thread.join();
  6317. ASSERT_FALSE(svr.is_running());
  6318. });
  6319. svr.wait_until_ready();
  6320. Client cli(HOST, PORT);
  6321. cli.set_keep_alive(true);
  6322. for (size_t i = 0; i < 5; i++) {
  6323. auto result = cli.Get("/hi");
  6324. ASSERT_TRUE(result);
  6325. EXPECT_EQ(StatusCode::OK_200, result->status);
  6326. if (i == keep_alive_max_count - 1) {
  6327. EXPECT_EQ("close", result->get_header_value("Connection"));
  6328. } else {
  6329. EXPECT_FALSE(result->has_header("Connection"));
  6330. }
  6331. }
  6332. }
  6333. TEST(KeepAliveTest, Issue1041) {
  6334. Server svr;
  6335. svr.set_keep_alive_timeout(3);
  6336. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6337. res.set_content("Hello World!", "text/plain");
  6338. });
  6339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6340. auto se = detail::scope_exit([&] {
  6341. svr.stop();
  6342. listen_thread.join();
  6343. ASSERT_FALSE(svr.is_running());
  6344. });
  6345. svr.wait_until_ready();
  6346. Client cli(HOST, PORT);
  6347. cli.set_keep_alive(true);
  6348. auto result = cli.Get("/hi");
  6349. ASSERT_TRUE(result);
  6350. EXPECT_EQ(StatusCode::OK_200, result->status);
  6351. std::this_thread::sleep_for(std::chrono::seconds(5));
  6352. result = cli.Get("/hi");
  6353. ASSERT_TRUE(result);
  6354. EXPECT_EQ(StatusCode::OK_200, result->status);
  6355. }
  6356. TEST(KeepAliveTest, Issue1959) {
  6357. Server svr;
  6358. svr.set_keep_alive_timeout(5);
  6359. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6360. res.set_content("a", "text/plain");
  6361. });
  6362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6363. auto se = detail::scope_exit([&] {
  6364. if (!svr.is_running()) return;
  6365. svr.stop();
  6366. listen_thread.join();
  6367. ASSERT_FALSE(svr.is_running());
  6368. });
  6369. svr.wait_until_ready();
  6370. Client cli("localhost", PORT);
  6371. cli.set_keep_alive(true);
  6372. using namespace std::chrono;
  6373. auto start = steady_clock::now();
  6374. cli.Get("/a");
  6375. svr.stop();
  6376. listen_thread.join();
  6377. auto end = steady_clock::now();
  6378. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6379. EXPECT_LT(elapsed, 5000);
  6380. }
  6381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6382. TEST(KeepAliveTest, SSLClientReconnection) {
  6383. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6384. ASSERT_TRUE(svr.is_valid());
  6385. svr.set_keep_alive_timeout(1);
  6386. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6387. res.set_content("Hello World!", "text/plain");
  6388. });
  6389. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6390. auto se = detail::scope_exit([&] {
  6391. svr.stop();
  6392. listen_thread.join();
  6393. ASSERT_FALSE(svr.is_running());
  6394. });
  6395. svr.wait_until_ready();
  6396. SSLClient cli(HOST, PORT);
  6397. cli.enable_server_certificate_verification(false);
  6398. cli.set_keep_alive(true);
  6399. auto result = cli.Get("/hi");
  6400. ASSERT_TRUE(result);
  6401. EXPECT_EQ(StatusCode::OK_200, result->status);
  6402. result = cli.Get("/hi");
  6403. ASSERT_TRUE(result);
  6404. EXPECT_EQ(StatusCode::OK_200, result->status);
  6405. std::this_thread::sleep_for(std::chrono::seconds(2));
  6406. // Recoonect
  6407. result = cli.Get("/hi");
  6408. ASSERT_TRUE(result);
  6409. EXPECT_EQ(StatusCode::OK_200, result->status);
  6410. result = cli.Get("/hi");
  6411. ASSERT_TRUE(result);
  6412. EXPECT_EQ(StatusCode::OK_200, result->status);
  6413. }
  6414. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6416. ASSERT_TRUE(svr.is_valid());
  6417. svr.set_keep_alive_timeout(1);
  6418. std::string content = "reconnect";
  6419. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6420. res.set_content("Hello World!", "text/plain");
  6421. });
  6422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6423. auto se = detail::scope_exit([&] {
  6424. svr.stop();
  6425. listen_thread.join();
  6426. ASSERT_FALSE(svr.is_running());
  6427. });
  6428. svr.wait_until_ready();
  6429. SSLClient cli(HOST, PORT);
  6430. cli.enable_server_certificate_verification(false);
  6431. cli.set_keep_alive(true);
  6432. auto result = cli.Post(
  6433. "/hi", content.size(),
  6434. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6435. sink.write(content.c_str(), content.size());
  6436. return true;
  6437. },
  6438. "text/plain");
  6439. ASSERT_TRUE(result);
  6440. EXPECT_EQ(200, result->status);
  6441. std::this_thread::sleep_for(std::chrono::seconds(2));
  6442. // Recoonect
  6443. result = cli.Post(
  6444. "/hi", content.size(),
  6445. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6446. sink.write(content.c_str(), content.size());
  6447. return true;
  6448. },
  6449. "text/plain");
  6450. ASSERT_TRUE(result);
  6451. EXPECT_EQ(200, result->status);
  6452. result = cli.Post(
  6453. "/hi", content.size(),
  6454. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6455. sink.write(content.c_str(), content.size());
  6456. return true;
  6457. },
  6458. "text/plain");
  6459. ASSERT_TRUE(result);
  6460. EXPECT_EQ(200, result->status);
  6461. }
  6462. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6463. {
  6464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6465. ASSERT_TRUE(svr.is_valid());
  6466. svr.Get("/sni", [&](const Request &req, Response &res) {
  6467. std::string expected;
  6468. if (req.ssl) {
  6469. if (const char *sni =
  6470. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6471. expected = sni;
  6472. }
  6473. }
  6474. EXPECT_EQ(expected, req.get_param_value("expected"));
  6475. res.set_content("ok", "text/plain");
  6476. });
  6477. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6478. auto se = detail::scope_exit([&] {
  6479. svr.stop();
  6480. listen_thread.join();
  6481. ASSERT_FALSE(svr.is_running());
  6482. });
  6483. svr.wait_until_ready();
  6484. {
  6485. SSLClient cli("localhost", PORT);
  6486. cli.enable_server_certificate_verification(false);
  6487. auto res = cli.Get("/sni?expected=localhost");
  6488. ASSERT_TRUE(res);
  6489. }
  6490. {
  6491. SSLClient cli("::1", PORT);
  6492. cli.enable_server_certificate_verification(false);
  6493. auto res = cli.Get("/sni?expected=");
  6494. // NOTE: This may fail if the server is listening on IPv4 only
  6495. // (e.g., when localhost resolves to 127.0.0.1 only)
  6496. if (res) {
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. } else {
  6499. EXPECT_EQ(Error::Connection, res.error());
  6500. }
  6501. }
  6502. }
  6503. }
  6504. #endif
  6505. TEST(ClientProblemDetectionTest, ContentProvider) {
  6506. Server svr;
  6507. size_t content_length = 1024 * 1024;
  6508. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6509. res.set_content_provider(
  6510. content_length, "text/plain",
  6511. [&](size_t offset, size_t length, DataSink &sink) {
  6512. auto out_len = std::min(length, static_cast<size_t>(1024));
  6513. std::string out(out_len, '@');
  6514. sink.write(out.data(), out_len);
  6515. return offset < 4096;
  6516. },
  6517. [](bool success) { ASSERT_FALSE(success); });
  6518. });
  6519. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6520. res.set_content_provider(
  6521. 0, "text/plain",
  6522. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6523. EXPECT_TRUE(false);
  6524. return true;
  6525. },
  6526. [](bool success) { ASSERT_FALSE(success); });
  6527. });
  6528. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6529. auto se = detail::scope_exit([&] {
  6530. svr.stop();
  6531. listen_thread.join();
  6532. ASSERT_FALSE(svr.is_running());
  6533. });
  6534. svr.wait_until_ready();
  6535. Client cli("localhost", PORT);
  6536. {
  6537. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6538. size_t /*data_length*/) { return false; });
  6539. ASSERT_FALSE(res);
  6540. }
  6541. {
  6542. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6543. size_t /*data_length*/) { return false; });
  6544. ASSERT_TRUE(res);
  6545. }
  6546. }
  6547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6548. Server svr;
  6549. svr.set_error_handler([](Request const &, Response &res) -> void {
  6550. res.set_chunked_content_provider(
  6551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6552. sink.os << "hello";
  6553. sink.os << "world";
  6554. sink.done();
  6555. return true;
  6556. });
  6557. });
  6558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6559. auto se = detail::scope_exit([&] {
  6560. svr.stop();
  6561. listen_thread.join();
  6562. ASSERT_FALSE(svr.is_running());
  6563. });
  6564. svr.wait_until_ready();
  6565. Client cli("localhost", PORT);
  6566. auto res = cli.Get("/");
  6567. ASSERT_TRUE(res);
  6568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6569. EXPECT_EQ("helloworld", res->body);
  6570. }
  6571. TEST(LongPollingTest, ClientCloseDetection) {
  6572. Server svr;
  6573. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6574. res.set_chunked_content_provider(
  6575. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6576. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6577. sink.os << "hello";
  6578. auto count = 10;
  6579. while (count > 0 && sink.is_writable()) {
  6580. this_thread::sleep_for(chrono::milliseconds(10));
  6581. count--;
  6582. }
  6583. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6584. return true;
  6585. });
  6586. });
  6587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6588. auto se = detail::scope_exit([&] {
  6589. svr.stop();
  6590. listen_thread.join();
  6591. ASSERT_FALSE(svr.is_running());
  6592. });
  6593. svr.wait_until_ready();
  6594. Client cli("localhost", PORT);
  6595. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6596. EXPECT_EQ("hello", string(data, data_length));
  6597. return false; // close the socket immediately.
  6598. });
  6599. ASSERT_FALSE(res);
  6600. }
  6601. TEST(GetWithParametersTest, GetWithParameters) {
  6602. Server svr;
  6603. svr.Get("/", [&](const Request &req, Response &) {
  6604. EXPECT_EQ("world", req.get_param_value("hello"));
  6605. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6606. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6607. });
  6608. svr.Get("/params", [&](const Request &req, Response &) {
  6609. EXPECT_EQ("world", req.get_param_value("hello"));
  6610. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6611. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6612. });
  6613. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6614. EXPECT_EQ("resource-id", req.matches[1]);
  6615. EXPECT_EQ("foo", req.get_param_value("param1"));
  6616. EXPECT_EQ("bar", req.get_param_value("param2"));
  6617. });
  6618. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6619. EXPECT_EQ("user-id", req.path_params.at("id"));
  6620. EXPECT_EQ("foo", req.get_param_value("param1"));
  6621. EXPECT_EQ("bar", req.get_param_value("param2"));
  6622. });
  6623. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6624. auto se = detail::scope_exit([&] {
  6625. svr.stop();
  6626. listen_thread.join();
  6627. ASSERT_FALSE(svr.is_running());
  6628. });
  6629. svr.wait_until_ready();
  6630. {
  6631. Client cli(HOST, PORT);
  6632. Params params;
  6633. params.emplace("hello", "world");
  6634. params.emplace("hello2", "world2");
  6635. params.emplace("hello3", "world3");
  6636. auto res = cli.Get("/", params, Headers{});
  6637. ASSERT_TRUE(res);
  6638. EXPECT_EQ(StatusCode::OK_200, res->status);
  6639. }
  6640. {
  6641. Client cli(HOST, PORT);
  6642. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6643. ASSERT_TRUE(res);
  6644. EXPECT_EQ(StatusCode::OK_200, res->status);
  6645. }
  6646. {
  6647. Client cli(HOST, PORT);
  6648. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6649. ASSERT_TRUE(res);
  6650. EXPECT_EQ(StatusCode::OK_200, res->status);
  6651. }
  6652. {
  6653. Client cli(HOST, PORT);
  6654. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6655. ASSERT_TRUE(res);
  6656. EXPECT_EQ(StatusCode::OK_200, res->status);
  6657. }
  6658. }
  6659. TEST(GetWithParametersTest, GetWithParameters2) {
  6660. Server svr;
  6661. svr.Get("/", [&](const Request &req, Response &res) {
  6662. auto text = req.get_param_value("hello");
  6663. res.set_content(text, "text/plain");
  6664. });
  6665. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6666. auto se = detail::scope_exit([&] {
  6667. svr.stop();
  6668. listen_thread.join();
  6669. ASSERT_FALSE(svr.is_running());
  6670. });
  6671. svr.wait_until_ready();
  6672. Client cli("localhost", PORT);
  6673. Params params;
  6674. params.emplace("hello", "world");
  6675. std::string body;
  6676. auto res = cli.Get("/", params, Headers{},
  6677. [&](const char *data, size_t data_length) {
  6678. body.append(data, data_length);
  6679. return true;
  6680. });
  6681. ASSERT_TRUE(res);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("world", body);
  6684. }
  6685. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6686. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6687. auto host = "httpcan.org";
  6688. auto path = std::string{"/range/32"};
  6689. #else
  6690. auto host = "nghttp2.org";
  6691. auto path = std::string{"/httpbin/range/32"};
  6692. #endif
  6693. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6694. SSLClient cli(host);
  6695. #else
  6696. Client cli(host);
  6697. #endif
  6698. cli.set_default_headers({make_range_header({{1, 10}})});
  6699. cli.set_connection_timeout(5);
  6700. {
  6701. auto res = cli.Get(path);
  6702. ASSERT_TRUE(res);
  6703. EXPECT_EQ("bcdefghijk", res->body);
  6704. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6705. }
  6706. {
  6707. auto res = cli.Get(path);
  6708. ASSERT_TRUE(res);
  6709. EXPECT_EQ("bcdefghijk", res->body);
  6710. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6711. }
  6712. }
  6713. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6714. Server svr;
  6715. svr.set_default_headers({{"Hello", "World"}});
  6716. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6717. res.set_content("ok", "text/plain");
  6718. });
  6719. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6720. auto se = detail::scope_exit([&] {
  6721. svr.stop();
  6722. listen_thread.join();
  6723. ASSERT_FALSE(svr.is_running());
  6724. });
  6725. svr.wait_until_ready();
  6726. Client cli("localhost", PORT);
  6727. auto res = cli.Get("/");
  6728. ASSERT_TRUE(res);
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("ok", res->body);
  6731. EXPECT_EQ("World", res->get_header_value("Hello"));
  6732. }
  6733. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6734. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6736. ASSERT_TRUE(svr.is_valid());
  6737. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6738. std::this_thread::sleep_for(std::chrono::seconds(2));
  6739. res.set_content("a", "text/plain");
  6740. });
  6741. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6742. res.set_content("b", "text/plain");
  6743. });
  6744. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6745. auto se = detail::scope_exit([&] {
  6746. svr.stop();
  6747. listen_thread.join();
  6748. ASSERT_FALSE(svr.is_running());
  6749. });
  6750. svr.wait_until_ready();
  6751. SSLClient cli("localhost", PORT);
  6752. cli.enable_server_certificate_verification(false);
  6753. cli.set_keep_alive(true);
  6754. cli.set_read_timeout(std::chrono::seconds(1));
  6755. auto resa = cli.Get("/a");
  6756. ASSERT_TRUE(!resa);
  6757. EXPECT_EQ(Error::Read, resa.error());
  6758. auto resb = cli.Get("/b");
  6759. ASSERT_TRUE(resb);
  6760. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6761. EXPECT_EQ("b", resb->body);
  6762. }
  6763. #endif
  6764. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6765. protected:
  6766. ServerTestWithAI_PASSIVE()
  6767. : cli_(HOST, PORT)
  6768. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6769. ,
  6770. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6771. #endif
  6772. {
  6773. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6774. cli_.enable_server_certificate_verification(false);
  6775. #endif
  6776. }
  6777. virtual void SetUp() {
  6778. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6779. res.set_content("Hello World!", "text/plain");
  6780. });
  6781. t_ = thread(
  6782. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6783. svr_.wait_until_ready();
  6784. }
  6785. virtual void TearDown() {
  6786. svr_.stop();
  6787. t_.join();
  6788. }
  6789. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6790. SSLClient cli_;
  6791. SSLServer svr_;
  6792. #else
  6793. Client cli_;
  6794. Server svr_;
  6795. #endif
  6796. thread t_;
  6797. };
  6798. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6799. auto res = cli_.Get("/hi");
  6800. ASSERT_TRUE(res);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6803. EXPECT_EQ("Hello World!", res->body);
  6804. }
  6805. class ServerUpDownTest : public ::testing::Test {
  6806. protected:
  6807. ServerUpDownTest() : cli_(HOST, PORT) {}
  6808. virtual void SetUp() {
  6809. t_ = thread([&]() {
  6810. svr_.bind_to_any_port(HOST);
  6811. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6812. ASSERT_TRUE(svr_.listen_after_bind());
  6813. });
  6814. svr_.wait_until_ready();
  6815. }
  6816. virtual void TearDown() {
  6817. svr_.stop();
  6818. t_.join();
  6819. }
  6820. Client cli_;
  6821. Server svr_;
  6822. thread t_;
  6823. };
  6824. TEST_F(ServerUpDownTest, QuickStartStop) {
  6825. // Should not crash, especially when run with
  6826. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6827. }
  6828. class PayloadMaxLengthTest : public ::testing::Test {
  6829. protected:
  6830. PayloadMaxLengthTest()
  6831. : cli_(HOST, PORT)
  6832. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6833. ,
  6834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6835. #endif
  6836. {
  6837. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6838. cli_.enable_server_certificate_verification(false);
  6839. #endif
  6840. }
  6841. virtual void SetUp() {
  6842. svr_.set_payload_max_length(8);
  6843. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6844. res.set_content("test", "text/plain");
  6845. });
  6846. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6847. svr_.wait_until_ready();
  6848. }
  6849. virtual void TearDown() {
  6850. svr_.stop();
  6851. t_.join();
  6852. }
  6853. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6854. SSLClient cli_;
  6855. SSLServer svr_;
  6856. #else
  6857. Client cli_;
  6858. Server svr_;
  6859. #endif
  6860. thread t_;
  6861. };
  6862. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6863. auto res = cli_.Post("/test", "123456789", "text/plain");
  6864. ASSERT_TRUE(res);
  6865. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6866. res = cli_.Post("/test", "12345678", "text/plain");
  6867. ASSERT_TRUE(res);
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6871. // Test chunked encoding with payload exceeding the 8-byte limit
  6872. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6873. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6874. ASSERT_TRUE(res);
  6875. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6876. }
  6877. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6878. // Test chunked encoding with payload within the 8-byte limit
  6879. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6880. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6881. ASSERT_TRUE(res);
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. }
  6884. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6885. // Test using send_request to send chunked data exceeding payload limit
  6886. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6887. "Host: " +
  6888. std::string(HOST) + ":" + std::to_string(PORT) +
  6889. "\r\n"
  6890. "Transfer-Encoding: chunked\r\n"
  6891. "Connection: close\r\n"
  6892. "\r\n"
  6893. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6894. "0123456789\r\n"
  6895. "0\r\n" // End chunk
  6896. "\r\n";
  6897. std::string response;
  6898. bool result = send_request(1, chunked_request, &response);
  6899. if (!result) {
  6900. // If send_request fails, it might be because the server closed the
  6901. // connection due to payload limit enforcement, which is acceptable
  6902. SUCCEED()
  6903. << "Server rejected oversized chunked request (connection closed)";
  6904. } else {
  6905. // If we got a response, check if it's an error response or connection was
  6906. // closed early Short response length indicates connection was closed due to
  6907. // payload limit
  6908. if (response.length() <= 10) {
  6909. SUCCEED() << "Server closed connection for oversized chunked request";
  6910. } else {
  6911. // Check for error status codes
  6912. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6913. response.find("Payload Too Large") != std::string::npos ||
  6914. response.find("400") != std::string::npos);
  6915. }
  6916. }
  6917. }
  6918. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6919. // Test request without Content-Length header exceeding payload limit
  6920. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6921. "Host: " +
  6922. std::string(HOST) + ":" +
  6923. std::to_string(PORT) +
  6924. "\r\n"
  6925. "Connection: close\r\n"
  6926. "\r\n";
  6927. // Add payload exceeding the 8-byte limit
  6928. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6929. request_without_content_length += large_payload;
  6930. std::string response;
  6931. bool result = send_request(1, request_without_content_length, &response);
  6932. if (!result) {
  6933. // If send_request fails, server likely closed connection due to payload
  6934. // limit
  6935. SUCCEED() << "Server rejected oversized request without Content-Length "
  6936. "(connection closed)";
  6937. } else {
  6938. // Check if server responded with error or closed connection early
  6939. if (response.length() <= 10) {
  6940. SUCCEED() << "Server closed connection for oversized request without "
  6941. "Content-Length";
  6942. } else {
  6943. // Check for error status codes
  6944. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6945. response.find("Payload Too Large") != std::string::npos ||
  6946. response.find("400") != std::string::npos);
  6947. }
  6948. }
  6949. }
  6950. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6951. // Test request without Content-Length header within payload limit
  6952. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6953. "Host: " +
  6954. std::string(HOST) + ":" +
  6955. std::to_string(PORT) +
  6956. "\r\n"
  6957. "Connection: close\r\n"
  6958. "\r\n";
  6959. // Add payload within the 8-byte limit
  6960. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  6961. request_without_content_length += small_payload;
  6962. std::string response;
  6963. bool result = send_request(1, request_without_content_length, &response);
  6964. // For requests without Content-Length, the server may have different behavior
  6965. // The key is that it should not reject due to payload limit for small
  6966. // payloads
  6967. if (result) {
  6968. // Check for any HTTP response (success or error, but not connection closed)
  6969. if (response.length() > 10) {
  6970. SUCCEED()
  6971. << "Server processed request without Content-Length within limit";
  6972. } else {
  6973. // Short response might indicate connection closed, which is acceptable
  6974. SUCCEED() << "Server closed connection for request without "
  6975. "Content-Length (acceptable behavior)";
  6976. }
  6977. } else {
  6978. // Connection failure might be due to protocol requirements
  6979. SUCCEED() << "Connection issue with request without Content-Length "
  6980. "(environment-specific)";
  6981. }
  6982. }
  6983. class LargePayloadMaxLengthTest : public ::testing::Test {
  6984. protected:
  6985. LargePayloadMaxLengthTest()
  6986. : cli_(HOST, PORT)
  6987. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6988. ,
  6989. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6990. #endif
  6991. {
  6992. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6993. cli_.enable_server_certificate_verification(false);
  6994. #endif
  6995. }
  6996. virtual void SetUp() {
  6997. // Set 10MB payload limit
  6998. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  6999. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7000. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7001. res.set_content("Large payload test", "text/plain");
  7002. });
  7003. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7004. svr_.wait_until_ready();
  7005. }
  7006. virtual void TearDown() {
  7007. svr_.stop();
  7008. t_.join();
  7009. }
  7010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7011. SSLClient cli_;
  7012. SSLServer svr_;
  7013. #else
  7014. Client cli_;
  7015. Server svr_;
  7016. #endif
  7017. thread t_;
  7018. };
  7019. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7020. // Test chunked encoding with payload within 10MB limit
  7021. std::string medium_payload(5 * 1024 * 1024,
  7022. 'A'); // 5MB payload, within 10MB limit
  7023. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7024. ASSERT_TRUE(res);
  7025. EXPECT_EQ(StatusCode::OK_200, res->status);
  7026. }
  7027. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7028. // Test chunked encoding with payload exceeding 10MB limit
  7029. std::string large_payload(12 * 1024 * 1024,
  7030. 'B'); // 12MB payload, exceeds 10MB limit
  7031. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7032. ASSERT_TRUE(res);
  7033. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7034. }
  7035. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7036. // Test request without Content-Length header within 10MB limit
  7037. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7038. "Host: " +
  7039. std::string(HOST) + ":" +
  7040. std::to_string(PORT) +
  7041. "\r\n"
  7042. "Connection: close\r\n"
  7043. "\r\n";
  7044. // Add 1MB payload (within 10MB limit)
  7045. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7046. request_without_content_length += medium_payload;
  7047. std::string response;
  7048. bool result = send_request(5, request_without_content_length, &response);
  7049. if (result) {
  7050. // Should get a proper HTTP response for payloads within limit
  7051. if (response.length() > 10) {
  7052. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7053. "10MB limit";
  7054. } else {
  7055. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7056. "Content-Length)";
  7057. }
  7058. } else {
  7059. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7060. }
  7061. }
  7062. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7063. // Test request without Content-Length header exceeding 10MB limit
  7064. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7065. "Host: " +
  7066. std::string(HOST) + ":" +
  7067. std::to_string(PORT) +
  7068. "\r\n"
  7069. "Connection: close\r\n"
  7070. "\r\n";
  7071. // Add 12MB payload (exceeds 10MB limit)
  7072. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7073. request_without_content_length += large_payload;
  7074. std::string response;
  7075. bool result = send_request(10, request_without_content_length, &response);
  7076. if (!result) {
  7077. // Server should close connection due to payload limit
  7078. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7079. "(connection closed)";
  7080. } else {
  7081. // Check for error response
  7082. if (response.length() <= 10) {
  7083. SUCCEED()
  7084. << "Server closed connection for 12MB request exceeding 10MB limit";
  7085. } else {
  7086. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7087. response.find("Payload Too Large") != std::string::npos ||
  7088. response.find("400") != std::string::npos);
  7089. }
  7090. }
  7091. }
  7092. TEST(HostAndPortPropertiesTest, NoSSL) {
  7093. httplib::Client cli("www.google.com", 1234);
  7094. ASSERT_EQ("www.google.com", cli.host());
  7095. ASSERT_EQ(1234, cli.port());
  7096. }
  7097. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7098. httplib::Client cli("www.google.com:1234");
  7099. ASSERT_EQ("www.google.com", cli.host());
  7100. ASSERT_EQ(1234, cli.port());
  7101. }
  7102. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7103. TEST(HostAndPortPropertiesTest, SSL) {
  7104. httplib::SSLClient cli("www.google.com");
  7105. ASSERT_EQ("www.google.com", cli.host());
  7106. ASSERT_EQ(443, cli.port());
  7107. }
  7108. #endif
  7109. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7110. TEST(SSLClientTest, UpdateCAStore) {
  7111. httplib::SSLClient httplib_client("www.google.com");
  7112. auto ca_store_1 = X509_STORE_new();
  7113. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7114. nullptr);
  7115. httplib_client.set_ca_cert_store(ca_store_1);
  7116. auto ca_store_2 = X509_STORE_new();
  7117. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7118. nullptr);
  7119. httplib_client.set_ca_cert_store(ca_store_2);
  7120. }
  7121. TEST(SSLClientTest, ServerNameIndication_Online) {
  7122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7123. auto host = "httpcan.org";
  7124. auto path = std::string{"/get"};
  7125. #else
  7126. auto host = "nghttp2.org";
  7127. auto path = std::string{"/httpbin/get"};
  7128. #endif
  7129. SSLClient cli(host, 443);
  7130. auto res = cli.Get(path);
  7131. ASSERT_TRUE(res);
  7132. ASSERT_EQ(StatusCode::OK_200, res->status);
  7133. }
  7134. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7135. // Use a site that will cause SSL verification failure due to self-signed cert
  7136. SSLClient cli("self-signed.badssl.com", 443);
  7137. cli.enable_server_certificate_verification(true);
  7138. auto res = cli.Get("/");
  7139. ASSERT_TRUE(!res);
  7140. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7141. // For SSL server verification errors, ssl_error should be 0, only
  7142. // ssl_openssl_error should be set
  7143. EXPECT_EQ(0, res.ssl_error());
  7144. // Verify OpenSSL error is captured for SSLServerVerification
  7145. // This occurs when SSL_get_verify_result() returns a verification failure
  7146. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7147. res.ssl_openssl_error());
  7148. }
  7149. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7150. // Use a site where hostname doesn't match the certificate
  7151. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7152. SSLClient cli("wrong.host.badssl.com", 443);
  7153. cli.enable_server_certificate_verification(true);
  7154. cli.enable_server_hostname_verification(true);
  7155. auto res = cli.Get("/");
  7156. ASSERT_TRUE(!res);
  7157. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7158. // For SSL hostname verification errors, ssl_error should be 0, only
  7159. // ssl_openssl_error should be set
  7160. EXPECT_EQ(0, res.ssl_error());
  7161. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7162. // This occurs when verify_host() fails due to hostname mismatch
  7163. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7164. res.ssl_openssl_error());
  7165. }
  7166. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7167. Client cli("https://google.com");
  7168. auto res = cli.Get("/");
  7169. ASSERT_TRUE(res);
  7170. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7171. }
  7172. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7173. SSLClient cli("google.com");
  7174. cli.set_ca_cert_path(CA_CERT_FILE);
  7175. auto res = cli.Get("/");
  7176. ASSERT_TRUE(res);
  7177. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7178. }
  7179. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7180. SSLClient cli("google.com");
  7181. cli.enable_server_certificate_verification(true);
  7182. cli.set_ca_cert_path("hello");
  7183. auto res = cli.Get("/");
  7184. ASSERT_TRUE(!res);
  7185. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7186. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7187. // should be set
  7188. EXPECT_EQ(0, res.ssl_error());
  7189. // Verify OpenSSL error is captured for SSLLoadingCerts
  7190. // This error occurs when SSL_CTX_load_verify_locations() fails
  7191. // > openssl errstr 0x80000002
  7192. // error:80000002:system library::No such file or directory
  7193. // > openssl errstr 0xA000126
  7194. // error:0A000126:SSL routines::unexpected eof while reading
  7195. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7196. res.ssl_openssl_error() == 0xA000126);
  7197. }
  7198. TEST(SSLClientTest, ServerCertificateVerification4) {
  7199. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7200. ASSERT_TRUE(svr.is_valid());
  7201. svr.Get("/test", [&](const Request &, Response &res) {
  7202. res.set_content("test", "text/plain");
  7203. svr.stop();
  7204. ASSERT_TRUE(true);
  7205. });
  7206. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7207. auto se = detail::scope_exit([&] {
  7208. t.join();
  7209. ASSERT_FALSE(svr.is_running());
  7210. });
  7211. svr.wait_until_ready();
  7212. SSLClient cli("127.0.0.1", PORT);
  7213. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7214. cli.enable_server_certificate_verification(true);
  7215. cli.set_connection_timeout(30);
  7216. auto res = cli.Get("/test");
  7217. ASSERT_TRUE(res);
  7218. ASSERT_EQ(StatusCode::OK_200, res->status);
  7219. }
  7220. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7221. std::string cert;
  7222. read_file(CA_CERT_FILE, cert);
  7223. SSLClient cli("google.com");
  7224. cli.load_ca_cert_store(cert.data(), cert.size());
  7225. const auto res = cli.Get("/");
  7226. ASSERT_TRUE(res);
  7227. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7228. }
  7229. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7230. // clang-format off
  7231. static constexpr char cert[] =
  7232. "GlobalSign Root CA\n"
  7233. "==================\n"
  7234. "-----BEGIN CERTIFICATE-----\n"
  7235. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7236. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7237. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7238. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7239. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7240. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7241. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7242. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7243. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7244. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7245. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7246. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7247. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7248. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7249. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7250. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7251. "-----END CERTIFICATE-----\n";
  7252. // clang-format on
  7253. SSLClient cli("google.com");
  7254. cli.load_ca_cert_store(cert, sizeof(cert));
  7255. const auto res = cli.Get("/");
  7256. ASSERT_TRUE(res);
  7257. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7258. }
  7259. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7260. SSLClient cli("www.youtube.com");
  7261. cli.set_ca_cert_path(CA_CERT_FILE);
  7262. cli.enable_server_certificate_verification(true);
  7263. cli.set_follow_location(true);
  7264. auto res = cli.Get("/");
  7265. ASSERT_TRUE(res);
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST(SSLClientTest, Issue2004_Online) {
  7269. Client client("https://google.com");
  7270. client.set_follow_location(true);
  7271. auto res = client.Get("/");
  7272. ASSERT_TRUE(res);
  7273. ASSERT_EQ(StatusCode::OK_200, res->status);
  7274. auto body = res->body;
  7275. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7276. }
  7277. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7278. // Create SSLClient with invalid cert/key to make is_valid() return false
  7279. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7280. "nonexistent_key.pem");
  7281. // is_valid() should be false due to cert loading failure
  7282. ASSERT_FALSE(cli.is_valid());
  7283. auto res = cli.Get("/");
  7284. ASSERT_FALSE(res);
  7285. EXPECT_EQ(Error::SSLConnection, res.error());
  7286. }
  7287. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7288. // Test for Issue #2251: SSL error not properly reported when client cert
  7289. // and key paths are swapped or mismatched
  7290. // This simulates the scenario where user accidentally swaps the cert and key
  7291. // files
  7292. // Using client cert file as private key and vice versa (completely wrong)
  7293. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7294. // Should fail validation due to cert/key mismatch
  7295. ASSERT_FALSE(cli.is_valid());
  7296. // Attempt to make a request should fail with proper error
  7297. auto res = cli.Get("/");
  7298. ASSERT_FALSE(res);
  7299. EXPECT_EQ(Error::SSLConnection, res.error());
  7300. // SSL error should be recorded in the Result object (this is the key fix for
  7301. // Issue #2251)
  7302. auto openssl_error = res.ssl_openssl_error();
  7303. EXPECT_NE(0u, openssl_error);
  7304. }
  7305. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7306. // Another variant: using valid file paths but with mismatched cert/key pair
  7307. // This tests the case where files exist but contain incompatible key material
  7308. // Using client cert with wrong key (cert2 key)
  7309. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7310. // Should fail validation
  7311. ASSERT_FALSE(cli.is_valid());
  7312. auto res = cli.Get("/");
  7313. ASSERT_FALSE(res);
  7314. // Must report error properly, not appear as success
  7315. EXPECT_EQ(Error::SSLConnection, res.error());
  7316. // OpenSSL error should be captured in Result
  7317. EXPECT_NE(0u, res.ssl_openssl_error());
  7318. }
  7319. #if 0
  7320. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7321. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7322. ASSERT_TRUE(cli != nullptr);
  7323. cli->set_address_family(AF_INET6);
  7324. cli->set_interface("en0");
  7325. auto res = cli->Get("/get");
  7326. ASSERT_TRUE(res);
  7327. ASSERT_EQ(StatusCode::OK_200, res->status);
  7328. }
  7329. #endif
  7330. void ClientCertPresent(
  7331. const std::string &client_cert_file,
  7332. const std::string &client_private_key_file,
  7333. const std::string &client_encrypted_private_key_pass = std::string()) {
  7334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7335. CLIENT_CA_CERT_DIR);
  7336. ASSERT_TRUE(svr.is_valid());
  7337. svr.Get("/test", [&](const Request &req, Response &res) {
  7338. res.set_content("test", "text/plain");
  7339. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7340. ASSERT_TRUE(peer_cert != nullptr);
  7341. auto subject_name = X509_get_subject_name(peer_cert);
  7342. ASSERT_TRUE(subject_name != nullptr);
  7343. std::string common_name;
  7344. {
  7345. char name[BUFSIZ];
  7346. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7347. name, sizeof(name));
  7348. common_name.assign(name, static_cast<size_t>(name_len));
  7349. }
  7350. EXPECT_EQ("Common Name", common_name);
  7351. X509_free(peer_cert);
  7352. });
  7353. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7354. auto se = detail::scope_exit([&] {
  7355. svr.stop();
  7356. t.join();
  7357. ASSERT_FALSE(svr.is_running());
  7358. });
  7359. svr.wait_until_ready();
  7360. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7361. client_encrypted_private_key_pass);
  7362. cli.enable_server_certificate_verification(false);
  7363. cli.set_connection_timeout(30);
  7364. auto res = cli.Get("/test");
  7365. ASSERT_TRUE(res);
  7366. ASSERT_EQ(StatusCode::OK_200, res->status);
  7367. }
  7368. TEST(SSLClientServerTest, ClientCertPresent) {
  7369. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7370. }
  7371. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7372. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7373. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7374. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7375. }
  7376. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7377. void MemoryClientCertPresent(
  7378. const std::string &client_cert_file,
  7379. const std::string &client_private_key_file,
  7380. const std::string &client_encrypted_private_key_pass = std::string()) {
  7381. auto f = fopen(SERVER_CERT_FILE, "r+");
  7382. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7383. fclose(f);
  7384. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7385. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7386. fclose(f);
  7387. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7388. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7389. auto client_ca_cert_store = X509_STORE_new();
  7390. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7391. X509_free(client_cert);
  7392. fclose(f);
  7393. f = fopen(client_cert_file.c_str(), "r+");
  7394. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7395. fclose(f);
  7396. f = fopen(client_private_key_file.c_str(), "r+");
  7397. auto client_private_key = PEM_read_PrivateKey(
  7398. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7399. fclose(f);
  7400. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7401. ASSERT_TRUE(svr.is_valid());
  7402. svr.Get("/test", [&](const Request &req, Response &res) {
  7403. res.set_content("test", "text/plain");
  7404. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7405. ASSERT_TRUE(peer_cert != nullptr);
  7406. auto subject_name = X509_get_subject_name(peer_cert);
  7407. ASSERT_TRUE(subject_name != nullptr);
  7408. std::string common_name;
  7409. {
  7410. char name[BUFSIZ];
  7411. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7412. name, sizeof(name));
  7413. common_name.assign(name, static_cast<size_t>(name_len));
  7414. }
  7415. EXPECT_EQ("Common Name", common_name);
  7416. X509_free(peer_cert);
  7417. });
  7418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7419. auto se = detail::scope_exit([&] {
  7420. svr.stop();
  7421. t.join();
  7422. ASSERT_FALSE(svr.is_running());
  7423. });
  7424. svr.wait_until_ready();
  7425. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7426. client_encrypted_private_key_pass);
  7427. cli.enable_server_certificate_verification(false);
  7428. cli.set_connection_timeout(30);
  7429. auto res = cli.Get("/test");
  7430. ASSERT_TRUE(res);
  7431. ASSERT_EQ(StatusCode::OK_200, res->status);
  7432. X509_free(server_cert);
  7433. EVP_PKEY_free(server_private_key);
  7434. X509_free(client_cert);
  7435. EVP_PKEY_free(client_private_key);
  7436. }
  7437. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7438. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7439. }
  7440. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7441. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7442. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7443. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7444. }
  7445. #endif
  7446. TEST(SSLClientServerTest, ClientCertMissing) {
  7447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7448. CLIENT_CA_CERT_DIR);
  7449. ASSERT_TRUE(svr.is_valid());
  7450. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7452. auto se = detail::scope_exit([&] {
  7453. svr.stop();
  7454. t.join();
  7455. ASSERT_FALSE(svr.is_running());
  7456. });
  7457. svr.wait_until_ready();
  7458. SSLClient cli(HOST, PORT);
  7459. cli.set_connection_timeout(30);
  7460. auto res = cli.Get("/test");
  7461. ASSERT_TRUE(!res);
  7462. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7463. // For SSL server verification errors, ssl_error should be 0, only
  7464. // ssl_openssl_error should be set
  7465. EXPECT_EQ(0, res.ssl_error());
  7466. // Verify OpenSSL error is captured for SSLServerVerification
  7467. // Note: This test may have different error codes depending on the exact
  7468. // verification failure
  7469. EXPECT_NE(0UL, res.ssl_openssl_error());
  7470. }
  7471. TEST(SSLClientServerTest, TrustDirOptional) {
  7472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7473. ASSERT_TRUE(svr.is_valid());
  7474. svr.Get("/test", [&](const Request &, Response &res) {
  7475. res.set_content("test", "text/plain");
  7476. });
  7477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7478. auto se = detail::scope_exit([&] {
  7479. svr.stop();
  7480. t.join();
  7481. ASSERT_FALSE(svr.is_running());
  7482. });
  7483. svr.wait_until_ready();
  7484. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7485. cli.enable_server_certificate_verification(false);
  7486. cli.set_connection_timeout(30);
  7487. auto res = cli.Get("/test");
  7488. ASSERT_TRUE(res);
  7489. ASSERT_EQ(StatusCode::OK_200, res->status);
  7490. }
  7491. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7492. class NoListenSSLServer : public SSLServer {
  7493. public:
  7494. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7495. const char *client_ca_cert_file_path,
  7496. const char *client_ca_cert_dir_path = nullptr)
  7497. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7498. client_ca_cert_dir_path),
  7499. stop_(false) {}
  7500. std::atomic_bool stop_;
  7501. private:
  7502. bool process_and_close_socket(socket_t /*sock*/) override {
  7503. // Don't create SSL context
  7504. while (!stop_.load()) {
  7505. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7506. }
  7507. return true;
  7508. }
  7509. };
  7510. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7511. CLIENT_CA_CERT_FILE);
  7512. ASSERT_TRUE(svr.is_valid());
  7513. svr.Get("/test", [&](const Request &, Response &res) {
  7514. res.set_content("test", "text/plain");
  7515. });
  7516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7517. auto se = detail::scope_exit([&] {
  7518. svr.stop_ = true;
  7519. svr.stop();
  7520. t.join();
  7521. ASSERT_FALSE(svr.is_running());
  7522. });
  7523. svr.wait_until_ready();
  7524. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7525. cli.enable_server_certificate_verification(false);
  7526. cli.set_connection_timeout(1);
  7527. auto res = cli.Get("/test");
  7528. ASSERT_TRUE(!res);
  7529. EXPECT_EQ(Error::SSLConnection, res.error());
  7530. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7531. }
  7532. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7533. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7534. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7535. SSL_CTX_set_options(&ssl_ctx,
  7536. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7537. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7538. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7539. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7540. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7541. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7542. "ECDHE-DSS-AES128-SHA256:"
  7543. "ECDHE-RSA-AES256-SHA256:"
  7544. "ECDHE-DSS-AES256-SHA256:";
  7545. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7546. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7547. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7548. SSL_FILETYPE_PEM) != 1) {
  7549. return false;
  7550. }
  7551. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7552. CLIENT_CA_CERT_DIR);
  7553. SSL_CTX_set_verify(
  7554. &ssl_ctx,
  7555. SSL_VERIFY_PEER |
  7556. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7557. nullptr);
  7558. return true;
  7559. };
  7560. SSLServer svr(setup_ssl_ctx_callback);
  7561. ASSERT_TRUE(svr.is_valid());
  7562. svr.Get("/test", [&](const Request &req, Response &res) {
  7563. res.set_content("test", "text/plain");
  7564. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7565. ASSERT_TRUE(peer_cert != nullptr);
  7566. auto subject_name = X509_get_subject_name(peer_cert);
  7567. ASSERT_TRUE(subject_name != nullptr);
  7568. std::string common_name;
  7569. {
  7570. char name[BUFSIZ];
  7571. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7572. name, sizeof(name));
  7573. common_name.assign(name, static_cast<size_t>(name_len));
  7574. }
  7575. EXPECT_EQ("Common Name", common_name);
  7576. X509_free(peer_cert);
  7577. });
  7578. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7579. auto se = detail::scope_exit([&] {
  7580. svr.stop();
  7581. t.join();
  7582. ASSERT_FALSE(svr.is_running());
  7583. });
  7584. svr.wait_until_ready();
  7585. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7586. cli.enable_server_certificate_verification(false);
  7587. cli.set_connection_timeout(30);
  7588. auto res = cli.Get("/test");
  7589. ASSERT_TRUE(res);
  7590. ASSERT_EQ(StatusCode::OK_200, res->status);
  7591. }
  7592. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7594. ASSERT_TRUE(svr.is_valid());
  7595. // Set up a handler to verify client certificate is present
  7596. bool client_cert_verified = false;
  7597. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7598. // Verify that client certificate was provided
  7599. client_cert_verified = true;
  7600. res.set_content("success", "text/plain");
  7601. });
  7602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7603. auto se = detail::scope_exit([&] {
  7604. svr.stop();
  7605. t.join();
  7606. ASSERT_FALSE(svr.is_running());
  7607. });
  7608. svr.wait_until_ready();
  7609. // Client with certificate
  7610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7611. cli.enable_server_certificate_verification(false);
  7612. cli.set_connection_timeout(30);
  7613. auto res = cli.Get("/test");
  7614. ASSERT_TRUE(res);
  7615. ASSERT_EQ(StatusCode::OK_200, res->status);
  7616. ASSERT_TRUE(client_cert_verified);
  7617. EXPECT_EQ("success", res->body);
  7618. }
  7619. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7620. // Test that when client CA cert file is provided,
  7621. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7622. // Create a server with client authentication
  7623. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7624. ASSERT_TRUE(svr.is_valid());
  7625. // We can't directly access the SSL_CTX from SSLServer to verify,
  7626. // but we can test that the server properly requests client certificates
  7627. // and accepts valid ones from the specified CA
  7628. bool handler_called = false;
  7629. svr.Get("/test", [&](const Request &req, Response &res) {
  7630. handler_called = true;
  7631. // Verify that a client certificate was provided
  7632. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7633. ASSERT_TRUE(peer_cert != nullptr);
  7634. // Get the issuer name
  7635. auto issuer_name = X509_get_issuer_name(peer_cert);
  7636. ASSERT_TRUE(issuer_name != nullptr);
  7637. char issuer_buf[256];
  7638. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7639. // The client certificate should be issued by our test CA
  7640. std::string issuer_str(issuer_buf);
  7641. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7642. X509_free(peer_cert);
  7643. res.set_content("authenticated", "text/plain");
  7644. });
  7645. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7646. auto se = detail::scope_exit([&] {
  7647. svr.stop();
  7648. t.join();
  7649. ASSERT_FALSE(svr.is_running());
  7650. });
  7651. svr.wait_until_ready();
  7652. // Connect with a client certificate issued by the CA
  7653. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7654. cli.enable_server_certificate_verification(false);
  7655. cli.set_connection_timeout(30);
  7656. auto res = cli.Get("/test");
  7657. ASSERT_TRUE(res);
  7658. ASSERT_EQ(StatusCode::OK_200, res->status);
  7659. ASSERT_TRUE(handler_called);
  7660. EXPECT_EQ("authenticated", res->body);
  7661. }
  7662. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7663. // Test 1: Valid CA file - no error should be recorded
  7664. {
  7665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7666. CLIENT_CA_CERT_FILE);
  7667. ASSERT_TRUE(svr.is_valid());
  7668. // With valid setup, last_ssl_error should be 0
  7669. EXPECT_EQ(0, svr.ssl_last_error());
  7670. }
  7671. // Test 2: Invalid CA file content
  7672. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7673. {
  7674. // Create a temporary file with completely invalid content
  7675. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7676. {
  7677. std::ofstream ofs(temp_invalid_ca);
  7678. ofs << "This is not a certificate file at all\n";
  7679. ofs << "Just plain text content\n";
  7680. }
  7681. // Create server with invalid CA file
  7682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7683. // Clean up temporary file
  7684. std::remove(temp_invalid_ca);
  7685. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7686. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7687. // Note: SSL_CTX_load_verify_locations typically fails first,
  7688. // but our error handling code path is still exercised
  7689. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7690. }
  7691. }
  7692. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7693. // Test SSL server using X509_STORE constructor with client CA certificates
  7694. // This test verifies that Phase 2 implementation correctly extracts CA names
  7695. // from an X509_STORE and sets them in the SSL context
  7696. // Load the CA certificate into memory
  7697. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7698. ASSERT_NE(nullptr, bio);
  7699. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7700. BIO_free(bio);
  7701. ASSERT_NE(nullptr, ca_cert);
  7702. // Create an X509_STORE and add the CA certificate
  7703. auto store = X509_STORE_new();
  7704. ASSERT_NE(nullptr, store);
  7705. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7706. // Load server certificate and private key
  7707. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7708. ASSERT_NE(nullptr, cert_bio);
  7709. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7710. BIO_free(cert_bio);
  7711. ASSERT_NE(nullptr, server_cert);
  7712. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7713. ASSERT_NE(nullptr, key_bio);
  7714. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7715. BIO_free(key_bio);
  7716. ASSERT_NE(nullptr, server_key);
  7717. // Create SSLServer with X509_STORE constructor
  7718. // Note: X509_STORE ownership is transferred to SSL_CTX
  7719. SSLServer svr(server_cert, server_key, store);
  7720. ASSERT_TRUE(svr.is_valid());
  7721. // No SSL error should be recorded for valid setup
  7722. EXPECT_EQ(0, svr.ssl_last_error());
  7723. // Set up server endpoints
  7724. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7725. res.set_content("ok", "text/plain");
  7726. });
  7727. // Start server in a thread
  7728. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7729. svr.wait_until_ready();
  7730. // Connect with client certificate (using constructor with paths)
  7731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7732. cli.enable_server_certificate_verification(false);
  7733. auto res = cli.Get("/test-x509store");
  7734. ASSERT_TRUE(res);
  7735. EXPECT_EQ(200, res->status);
  7736. EXPECT_EQ("ok", res->body);
  7737. // Clean up
  7738. X509_free(server_cert);
  7739. EVP_PKEY_free(server_key);
  7740. X509_free(ca_cert);
  7741. svr.stop();
  7742. server_thread.join();
  7743. }
  7744. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7745. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7746. // prepare large data
  7747. std::random_device seed_gen;
  7748. std::mt19937 random(seed_gen());
  7749. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7750. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7751. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7752. // server
  7753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7754. ASSERT_TRUE(svr.is_valid());
  7755. svr.Post("/binary", [&](const Request &req, Response &res) {
  7756. EXPECT_EQ(large_size_byte, req.body.size());
  7757. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7758. res.set_content(req.body, "application/octet-stream");
  7759. });
  7760. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7761. auto se = detail::scope_exit([&] {
  7762. svr.stop();
  7763. listen_thread.join();
  7764. ASSERT_FALSE(svr.is_running());
  7765. });
  7766. svr.wait_until_ready();
  7767. // client POST
  7768. SSLClient cli("localhost", PORT);
  7769. cli.enable_server_certificate_verification(false);
  7770. cli.set_read_timeout(std::chrono::seconds(100));
  7771. cli.set_write_timeout(std::chrono::seconds(100));
  7772. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7773. large_size_byte, "application/octet-stream");
  7774. // compare
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ(large_size_byte, res->body.size());
  7777. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7778. }
  7779. #endif
  7780. #ifdef _WIN32
  7781. TEST(CleanupTest, WSACleanup) {
  7782. int ret = WSACleanup();
  7783. ASSERT_EQ(0, ret);
  7784. }
  7785. #endif
  7786. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7787. TEST(NoSSLSupport, SimpleInterface) {
  7788. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7789. }
  7790. #endif
  7791. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7792. TEST(InvalidScheme, SimpleInterface) {
  7793. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7794. }
  7795. #endif
  7796. TEST(NoScheme, SimpleInterface) {
  7797. Client cli("yahoo.com:80");
  7798. ASSERT_TRUE(cli.is_valid());
  7799. }
  7800. TEST(SendAPI, SimpleInterface_Online) {
  7801. Client cli("http://yahoo.com");
  7802. Request req;
  7803. req.method = "GET";
  7804. req.path = "/";
  7805. auto res = cli.send(req);
  7806. ASSERT_TRUE(res);
  7807. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7808. }
  7809. TEST(SendAPI, WithParamsInRequest) {
  7810. Server svr;
  7811. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7812. EXPECT_TRUE(req.has_param("test"));
  7813. EXPECT_EQ("test_value", req.get_param_value("test"));
  7814. });
  7815. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7816. auto se = detail::scope_exit([&] {
  7817. svr.stop();
  7818. t.join();
  7819. ASSERT_FALSE(svr.is_running());
  7820. });
  7821. svr.wait_until_ready();
  7822. Client cli(HOST, PORT);
  7823. {
  7824. Request req;
  7825. req.method = "GET";
  7826. req.path = "/";
  7827. req.params.emplace("test", "test_value");
  7828. auto res = cli.send(req);
  7829. ASSERT_TRUE(res);
  7830. }
  7831. {
  7832. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7833. ASSERT_TRUE(res);
  7834. }
  7835. }
  7836. TEST(ClientImplMethods, GetSocketTest) {
  7837. httplib::Server svr;
  7838. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7839. res.status = StatusCode::OK_200;
  7840. });
  7841. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7842. auto se = detail::scope_exit([&] {
  7843. svr.stop();
  7844. thread.join();
  7845. ASSERT_FALSE(svr.is_running());
  7846. });
  7847. svr.wait_until_ready();
  7848. {
  7849. httplib::Client cli("http://127.0.0.1:3333");
  7850. cli.set_keep_alive(true);
  7851. // Use the behavior of cpp-httplib of opening the connection
  7852. // only when the first request happens. If that changes,
  7853. // this test would be obsolete.
  7854. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7855. // This also implicitly tests the server. But other tests would fail much
  7856. // earlier than this one to be considered.
  7857. auto res = cli.Get("/");
  7858. ASSERT_TRUE(res);
  7859. EXPECT_EQ(StatusCode::OK_200, res->status);
  7860. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7861. }
  7862. }
  7863. // Disabled due to out-of-memory problem on GitHub Actions
  7864. #ifdef _WIN64
  7865. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7866. // allocate content size larger than 2GB in memory
  7867. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7868. char *content = (char *)malloc(content_size);
  7869. ASSERT_TRUE(content);
  7870. Server svr;
  7871. svr.Get("/foo",
  7872. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7873. res.set_content(content, content_size, "application/octet-stream");
  7874. });
  7875. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7876. auto se = detail::scope_exit([&] {
  7877. svr.stop();
  7878. listen_thread.join();
  7879. if (content) free(content);
  7880. ASSERT_FALSE(svr.is_running());
  7881. });
  7882. svr.wait_until_ready();
  7883. Client cli(HOST, PORT);
  7884. auto res = cli.Get("/foo");
  7885. ASSERT_TRUE(res);
  7886. EXPECT_EQ(StatusCode::OK_200, res->status);
  7887. EXPECT_EQ(content_size, res->body.length());
  7888. }
  7889. #endif
  7890. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7891. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7892. Client cli("http://yahoo.com");
  7893. auto res = cli.Get("/");
  7894. ASSERT_TRUE(res);
  7895. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7896. cli.set_follow_location(true);
  7897. res = cli.Get("/");
  7898. ASSERT_TRUE(res);
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7901. }
  7902. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7903. Client cli("https://yahoo.com");
  7904. auto res = cli.Get("/");
  7905. ASSERT_TRUE(res);
  7906. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7907. cli.set_follow_location(true);
  7908. res = cli.Get("/");
  7909. ASSERT_TRUE(res);
  7910. EXPECT_EQ(StatusCode::OK_200, res->status);
  7911. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7912. }
  7913. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7914. Client cli("https://yahoo.com");
  7915. auto res = cli.Get("/");
  7916. ASSERT_TRUE(res);
  7917. ASSERT_FALSE(!res);
  7918. ASSERT_TRUE(res);
  7919. ASSERT_FALSE(res == nullptr);
  7920. ASSERT_TRUE(res != nullptr);
  7921. EXPECT_EQ(Error::Success, res.error());
  7922. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7923. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7924. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7925. cli.set_follow_location(true);
  7926. res = cli.Get("/");
  7927. ASSERT_TRUE(res);
  7928. EXPECT_EQ(Error::Success, res.error());
  7929. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7930. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7933. }
  7934. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7935. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7936. Client cli("https://cdnjs.cloudflare.com");
  7937. auto res =
  7938. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7939. ASSERT_TRUE(res);
  7940. EXPECT_EQ(StatusCode::OK_200, res->status);
  7941. EXPECT_EQ(287630U, res->body.size());
  7942. EXPECT_EQ("application/javascript; charset=utf-8",
  7943. res->get_header_value("Content-Type"));
  7944. }
  7945. #endif
  7946. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7947. #undef REDIR_HOST // Silence compiler warning
  7948. #define REDIR_HOST "https://httpbingo.org"
  7949. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7950. Client cli(REDIR_HOST);
  7951. cli.set_follow_location(true);
  7952. auto res =
  7953. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  7954. ASSERT_TRUE(res);
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. }
  7957. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  7958. Client cli(REDIR_HOST);
  7959. cli.set_follow_location(true);
  7960. Params params;
  7961. params.emplace("url", "http://example.com");
  7962. params.emplace("status_code", "302");
  7963. auto res = cli.Get(REDIR_PATH, params, Headers{});
  7964. ASSERT_TRUE(res);
  7965. EXPECT_EQ(StatusCode::OK_200, res->status);
  7966. }
  7967. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  7968. Client cli(REDIR_HOST);
  7969. cli.set_follow_location(true);
  7970. Params params;
  7971. params.emplace("url", "http://example.com");
  7972. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  7973. ASSERT_TRUE(res);
  7974. EXPECT_EQ(StatusCode::OK_200, res->status);
  7975. }
  7976. TEST(HttpToHttpsRedirectTest, CertFile) {
  7977. Server svr;
  7978. ASSERT_TRUE(svr.is_valid());
  7979. svr.Get("/index", [&](const Request &, Response &res) {
  7980. res.set_redirect("https://127.0.0.1:1235/index");
  7981. svr.stop();
  7982. });
  7983. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7984. ASSERT_TRUE(ssl_svr.is_valid());
  7985. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  7986. res.set_content("test", "text/plain");
  7987. ssl_svr.stop();
  7988. });
  7989. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7990. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  7991. auto se = detail::scope_exit([&] {
  7992. t2.join();
  7993. t.join();
  7994. ASSERT_FALSE(svr.is_running());
  7995. });
  7996. svr.wait_until_ready();
  7997. ssl_svr.wait_until_ready();
  7998. Client cli("127.0.0.1", PORT);
  7999. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8000. cli.enable_server_certificate_verification(true);
  8001. cli.set_follow_location(true);
  8002. cli.set_connection_timeout(30);
  8003. auto res = cli.Get("/index");
  8004. ASSERT_TRUE(res);
  8005. ASSERT_EQ(StatusCode::OK_200, res->status);
  8006. }
  8007. TEST(SSLClientRedirectTest, CertFile) {
  8008. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8009. ASSERT_TRUE(ssl_svr1.is_valid());
  8010. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8011. res.set_redirect("https://127.0.0.1:1235/index");
  8012. ssl_svr1.stop();
  8013. });
  8014. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8015. ASSERT_TRUE(ssl_svr2.is_valid());
  8016. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8017. res.set_content("test", "text/plain");
  8018. ssl_svr2.stop();
  8019. });
  8020. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8021. thread t2 =
  8022. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8023. auto se = detail::scope_exit([&] {
  8024. t2.join();
  8025. t.join();
  8026. ASSERT_FALSE(ssl_svr1.is_running());
  8027. });
  8028. ssl_svr1.wait_until_ready();
  8029. ssl_svr2.wait_until_ready();
  8030. SSLClient cli("127.0.0.1", PORT);
  8031. std::string cert;
  8032. read_file(SERVER_CERT2_FILE, cert);
  8033. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8034. cli.enable_server_certificate_verification(true);
  8035. cli.set_follow_location(true);
  8036. cli.set_connection_timeout(30);
  8037. auto res = cli.Get("/index");
  8038. ASSERT_TRUE(res);
  8039. ASSERT_EQ(StatusCode::OK_200, res->status);
  8040. }
  8041. TEST(MultipartFormDataTest, LargeData) {
  8042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8043. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8044. const ContentReader &content_reader) {
  8045. if (req.is_multipart_form_data()) {
  8046. std::vector<FormData> items;
  8047. content_reader(
  8048. [&](const FormData &file) {
  8049. items.push_back(file);
  8050. return true;
  8051. },
  8052. [&](const char *data, size_t data_length) {
  8053. items.back().content.append(data, data_length);
  8054. return true;
  8055. });
  8056. EXPECT_TRUE(std::string(items[0].name) == "document");
  8057. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8058. EXPECT_TRUE(items[0].filename == "2MB_data");
  8059. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8060. EXPECT_TRUE(items[1].name == "hello");
  8061. EXPECT_TRUE(items[1].content == "world");
  8062. EXPECT_TRUE(items[1].filename == "");
  8063. EXPECT_TRUE(items[1].content_type == "");
  8064. } else {
  8065. std::string body;
  8066. content_reader([&](const char *data, size_t data_length) {
  8067. body.append(data, data_length);
  8068. return true;
  8069. });
  8070. }
  8071. });
  8072. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8073. auto se = detail::scope_exit([&] {
  8074. svr.stop();
  8075. t.join();
  8076. ASSERT_FALSE(svr.is_running());
  8077. });
  8078. svr.wait_until_ready();
  8079. {
  8080. std::string data(1024 * 1024 * 2, '.');
  8081. std::stringstream buffer;
  8082. buffer << data;
  8083. Client cli("https://localhost:8080");
  8084. cli.enable_server_certificate_verification(false);
  8085. UploadFormDataItems items{
  8086. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8087. {"hello", "world", "", ""},
  8088. };
  8089. auto res = cli.Post("/post", items);
  8090. ASSERT_TRUE(res);
  8091. ASSERT_EQ(StatusCode::OK_200, res->status);
  8092. }
  8093. }
  8094. TEST(MultipartFormDataTest, DataProviderItems) {
  8095. std::random_device seed_gen;
  8096. std::mt19937 random(seed_gen());
  8097. std::string rand1;
  8098. rand1.resize(1000);
  8099. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8100. std::string rand2;
  8101. rand2.resize(3000);
  8102. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8104. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8105. const ContentReader &content_reader) {
  8106. ASSERT_FALSE(req.is_multipart_form_data());
  8107. std::string body;
  8108. content_reader([&](const char *data, size_t data_length) {
  8109. body.append(data, data_length);
  8110. return true;
  8111. });
  8112. EXPECT_EQ(body, "");
  8113. });
  8114. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  8115. const ContentReader &content_reader) {
  8116. ASSERT_TRUE(req.is_multipart_form_data());
  8117. std::vector<FormData> items;
  8118. content_reader(
  8119. [&](const FormData &file) {
  8120. items.push_back(file);
  8121. return true;
  8122. },
  8123. [&](const char *data, size_t data_length) {
  8124. items.back().content.append(data, data_length);
  8125. return true;
  8126. });
  8127. ASSERT_TRUE(items.size() == 2);
  8128. EXPECT_EQ(std::string(items[0].name), "name1");
  8129. EXPECT_EQ(items[0].content, "Testing123");
  8130. EXPECT_EQ(items[0].filename, "filename1");
  8131. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8132. EXPECT_EQ(items[1].name, "name2");
  8133. EXPECT_EQ(items[1].content, "Testing456");
  8134. EXPECT_EQ(items[1].filename, "");
  8135. EXPECT_EQ(items[1].content_type, "");
  8136. });
  8137. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8138. const ContentReader &content_reader) {
  8139. ASSERT_TRUE(req.is_multipart_form_data());
  8140. std::vector<FormData> items;
  8141. content_reader(
  8142. [&](const FormData &file) {
  8143. items.push_back(file);
  8144. return true;
  8145. },
  8146. [&](const char *data, size_t data_length) {
  8147. items.back().content.append(data, data_length);
  8148. return true;
  8149. });
  8150. ASSERT_TRUE(items.size() == 2);
  8151. EXPECT_EQ(items[0].name, "name3");
  8152. EXPECT_EQ(items[0].content, rand1);
  8153. EXPECT_EQ(items[0].filename, "filename3");
  8154. EXPECT_EQ(items[0].content_type, "");
  8155. EXPECT_EQ(items[1].name, "name4");
  8156. EXPECT_EQ(items[1].content, rand2);
  8157. EXPECT_EQ(items[1].filename, "filename4");
  8158. EXPECT_EQ(items[1].content_type, "");
  8159. });
  8160. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8161. const ContentReader &content_reader) {
  8162. ASSERT_TRUE(req.is_multipart_form_data());
  8163. std::vector<FormData> items;
  8164. content_reader(
  8165. [&](const FormData &file) {
  8166. items.push_back(file);
  8167. return true;
  8168. },
  8169. [&](const char *data, size_t data_length) {
  8170. items.back().content.append(data, data_length);
  8171. return true;
  8172. });
  8173. ASSERT_TRUE(items.size() == 4);
  8174. EXPECT_EQ(std::string(items[0].name), "name1");
  8175. EXPECT_EQ(items[0].content, "Testing123");
  8176. EXPECT_EQ(items[0].filename, "filename1");
  8177. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8178. EXPECT_EQ(items[1].name, "name2");
  8179. EXPECT_EQ(items[1].content, "Testing456");
  8180. EXPECT_EQ(items[1].filename, "");
  8181. EXPECT_EQ(items[1].content_type, "");
  8182. EXPECT_EQ(items[2].name, "name3");
  8183. EXPECT_EQ(items[2].content, rand1);
  8184. EXPECT_EQ(items[2].filename, "filename3");
  8185. EXPECT_EQ(items[2].content_type, "");
  8186. EXPECT_EQ(items[3].name, "name4");
  8187. EXPECT_EQ(items[3].content, rand2);
  8188. EXPECT_EQ(items[3].filename, "filename4");
  8189. EXPECT_EQ(items[3].content_type, "");
  8190. });
  8191. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8192. auto se = detail::scope_exit([&] {
  8193. svr.stop();
  8194. t.join();
  8195. ASSERT_FALSE(svr.is_running());
  8196. });
  8197. svr.wait_until_ready();
  8198. {
  8199. Client cli("https://localhost:8080");
  8200. cli.enable_server_certificate_verification(false);
  8201. UploadFormDataItems items{
  8202. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8203. {"name2", "Testing456", "", ""}, // not a file
  8204. };
  8205. {
  8206. auto res = cli.Post("/post-none", {}, {}, {});
  8207. ASSERT_TRUE(res);
  8208. ASSERT_EQ(StatusCode::OK_200, res->status);
  8209. }
  8210. FormDataProviderItems providers;
  8211. {
  8212. auto res =
  8213. cli.Post("/post-items", {}, items, providers); // empty providers
  8214. ASSERT_TRUE(res);
  8215. ASSERT_EQ(StatusCode::OK_200, res->status);
  8216. }
  8217. providers.push_back({"name3",
  8218. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8219. // test the offset is given correctly at each step
  8220. if (!offset)
  8221. sink.os.write(rand1.data(), 30);
  8222. else if (offset == 30)
  8223. sink.os.write(rand1.data() + 30, 300);
  8224. else if (offset == 330)
  8225. sink.os.write(rand1.data() + 330, 670);
  8226. else if (offset == rand1.size())
  8227. sink.done();
  8228. return true;
  8229. },
  8230. "filename3",
  8231. {}});
  8232. providers.push_back({"name4",
  8233. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8234. // test the offset is given correctly at each step
  8235. if (!offset)
  8236. sink.os.write(rand2.data(), 2000);
  8237. else if (offset == 2000)
  8238. sink.os.write(rand2.data() + 2000, 1);
  8239. else if (offset == 2001)
  8240. sink.os.write(rand2.data() + 2001, 999);
  8241. else if (offset == rand2.size())
  8242. sink.done();
  8243. return true;
  8244. },
  8245. "filename4",
  8246. {}});
  8247. {
  8248. auto res = cli.Post("/post-providers", {}, {}, providers);
  8249. ASSERT_TRUE(res);
  8250. ASSERT_EQ(StatusCode::OK_200, res->status);
  8251. }
  8252. {
  8253. auto res = cli.Post("/post-both", {}, items, providers);
  8254. ASSERT_TRUE(res);
  8255. ASSERT_EQ(StatusCode::OK_200, res->status);
  8256. }
  8257. }
  8258. }
  8259. TEST(MultipartFormDataTest, BadHeader) {
  8260. Server svr;
  8261. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8262. res.set_content("ok", "text/plain");
  8263. });
  8264. thread t = thread([&] { svr.listen(HOST, PORT); });
  8265. auto se = detail::scope_exit([&] {
  8266. svr.stop();
  8267. t.join();
  8268. ASSERT_FALSE(svr.is_running());
  8269. });
  8270. svr.wait_until_ready();
  8271. const std::string body =
  8272. "This is the preamble. It is to be ignored, though it\r\n"
  8273. "is a handy place for composition agents to include an\r\n"
  8274. "explanatory note to non-MIME conformant readers.\r\n"
  8275. "\r\n"
  8276. "\r\n"
  8277. "--simple boundary\r\n"
  8278. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8279. ": BAD...\r\n"
  8280. "\r\n"
  8281. "value1\r\n"
  8282. "--simple boundary\r\n"
  8283. "Content-Disposition: form-data; name=\"field2\"; "
  8284. "filename=\"example.txt\"\r\n"
  8285. "\r\n"
  8286. "value2\r\n"
  8287. "--simple boundary--\r\n"
  8288. "This is the epilogue. It is also to be ignored.\r\n";
  8289. std::string content_type =
  8290. R"(multipart/form-data; boundary="simple boundary")";
  8291. Client cli(HOST, PORT);
  8292. auto res = cli.Post("/post", body, content_type.c_str());
  8293. ASSERT_TRUE(res);
  8294. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8295. }
  8296. TEST(MultipartFormDataTest, WithPreamble) {
  8297. Server svr;
  8298. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8299. res.set_content("ok", "text/plain");
  8300. });
  8301. thread t = thread([&] { svr.listen(HOST, PORT); });
  8302. auto se = detail::scope_exit([&] {
  8303. svr.stop();
  8304. t.join();
  8305. ASSERT_FALSE(svr.is_running());
  8306. });
  8307. svr.wait_until_ready();
  8308. const std::string body =
  8309. "This is the preamble. It is to be ignored, though it\r\n"
  8310. "is a handy place for composition agents to include an\r\n"
  8311. "explanatory note to non-MIME conformant readers.\r\n"
  8312. "\r\n"
  8313. "\r\n"
  8314. "--simple boundary\r\n"
  8315. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8316. "\r\n"
  8317. "value1\r\n"
  8318. "--simple boundary\r\n"
  8319. "Content-Disposition: form-data; name=\"field2\"; "
  8320. "filename=\"example.txt\"\r\n"
  8321. "\r\n"
  8322. "value2\r\n"
  8323. "--simple boundary--\r\n"
  8324. "This is the epilogue. It is also to be ignored.\r\n";
  8325. std::string content_type =
  8326. R"(multipart/form-data; boundary="simple boundary")";
  8327. Client cli(HOST, PORT);
  8328. auto res = cli.Post("/post", body, content_type.c_str());
  8329. ASSERT_TRUE(res);
  8330. EXPECT_EQ(StatusCode::OK_200, res->status);
  8331. }
  8332. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8334. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8335. const ContentReader &content_reader) {
  8336. if (req.is_multipart_form_data()) {
  8337. std::vector<FormData> items;
  8338. content_reader(
  8339. [&](const FormData &file) {
  8340. items.push_back(file);
  8341. return true;
  8342. },
  8343. [&](const char *data, size_t data_length) {
  8344. items.back().content.append(data, data_length);
  8345. return true;
  8346. });
  8347. EXPECT_TRUE(std::string(items[0].name) == "document");
  8348. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8349. EXPECT_TRUE(items[0].filename == "2MB_data");
  8350. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8351. EXPECT_TRUE(items[1].name == "hello");
  8352. EXPECT_TRUE(items[1].content == "world");
  8353. EXPECT_TRUE(items[1].filename == "");
  8354. EXPECT_TRUE(items[1].content_type == "");
  8355. } else {
  8356. std::string body;
  8357. content_reader([&](const char *data, size_t data_length) {
  8358. body.append(data, data_length);
  8359. return true;
  8360. });
  8361. }
  8362. });
  8363. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8364. auto se = detail::scope_exit([&] {
  8365. svr.stop();
  8366. t.join();
  8367. ASSERT_FALSE(svr.is_running());
  8368. });
  8369. svr.wait_until_ready();
  8370. {
  8371. std::string data(1024 * 1024 * 2, '.');
  8372. std::stringstream buffer;
  8373. buffer << data;
  8374. Client cli("https://localhost:8080");
  8375. cli.enable_server_certificate_verification(false);
  8376. UploadFormDataItems items{
  8377. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8378. {"hello", "world", "", ""},
  8379. };
  8380. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8381. ASSERT_TRUE(res);
  8382. ASSERT_EQ(StatusCode::OK_200, res->status);
  8383. }
  8384. }
  8385. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8386. std::string data(1024 * 1024 * 2, '&');
  8387. std::stringstream buffer;
  8388. buffer << data;
  8389. Client cli("https://localhost:8080");
  8390. UploadFormDataItems items{
  8391. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8392. {"hello", "world", "", ""},
  8393. };
  8394. for (const char &c : " \t\r\n") {
  8395. auto res =
  8396. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8397. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8398. ASSERT_FALSE(res);
  8399. }
  8400. }
  8401. TEST(MultipartFormDataTest, PutFormData) {
  8402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8403. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8404. const ContentReader &content_reader) {
  8405. if (req.is_multipart_form_data()) {
  8406. std::vector<FormData> items;
  8407. content_reader(
  8408. [&](const FormData &file) {
  8409. items.push_back(file);
  8410. return true;
  8411. },
  8412. [&](const char *data, size_t data_length) {
  8413. items.back().content.append(data, data_length);
  8414. return true;
  8415. });
  8416. EXPECT_TRUE(std::string(items[0].name) == "document");
  8417. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8418. EXPECT_TRUE(items[0].filename == "2MB_data");
  8419. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8420. EXPECT_TRUE(items[1].name == "hello");
  8421. EXPECT_TRUE(items[1].content == "world");
  8422. EXPECT_TRUE(items[1].filename == "");
  8423. EXPECT_TRUE(items[1].content_type == "");
  8424. } else {
  8425. std::string body;
  8426. content_reader([&](const char *data, size_t data_length) {
  8427. body.append(data, data_length);
  8428. return true;
  8429. });
  8430. }
  8431. });
  8432. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8433. auto se = detail::scope_exit([&] {
  8434. svr.stop();
  8435. t.join();
  8436. ASSERT_FALSE(svr.is_running());
  8437. });
  8438. svr.wait_until_ready();
  8439. {
  8440. std::string data(1024 * 1024 * 2, '&');
  8441. std::stringstream buffer;
  8442. buffer << data;
  8443. Client cli("https://localhost:8080");
  8444. cli.enable_server_certificate_verification(false);
  8445. UploadFormDataItems items{
  8446. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8447. {"hello", "world", "", ""},
  8448. };
  8449. auto res = cli.Put("/put", items);
  8450. ASSERT_TRUE(res);
  8451. ASSERT_EQ(StatusCode::OK_200, res->status);
  8452. }
  8453. }
  8454. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8456. svr.Put("/put_customboundary",
  8457. [&](const Request &req, const Response & /*res*/,
  8458. const ContentReader &content_reader) {
  8459. if (req.is_multipart_form_data()) {
  8460. std::vector<FormData> items;
  8461. content_reader(
  8462. [&](const FormData &file) {
  8463. items.push_back(file);
  8464. return true;
  8465. },
  8466. [&](const char *data, size_t data_length) {
  8467. items.back().content.append(data, data_length);
  8468. return true;
  8469. });
  8470. EXPECT_TRUE(std::string(items[0].name) == "document");
  8471. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8472. EXPECT_TRUE(items[0].filename == "2MB_data");
  8473. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8474. EXPECT_TRUE(items[1].name == "hello");
  8475. EXPECT_TRUE(items[1].content == "world");
  8476. EXPECT_TRUE(items[1].filename == "");
  8477. EXPECT_TRUE(items[1].content_type == "");
  8478. } else {
  8479. std::string body;
  8480. content_reader([&](const char *data, size_t data_length) {
  8481. body.append(data, data_length);
  8482. return true;
  8483. });
  8484. }
  8485. });
  8486. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8487. auto se = detail::scope_exit([&] {
  8488. svr.stop();
  8489. t.join();
  8490. ASSERT_FALSE(svr.is_running());
  8491. });
  8492. svr.wait_until_ready();
  8493. {
  8494. std::string data(1024 * 1024 * 2, '&');
  8495. std::stringstream buffer;
  8496. buffer << data;
  8497. Client cli("https://localhost:8080");
  8498. cli.enable_server_certificate_verification(false);
  8499. UploadFormDataItems items{
  8500. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8501. {"hello", "world", "", ""},
  8502. };
  8503. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8504. ASSERT_TRUE(res);
  8505. ASSERT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. }
  8508. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8509. std::string data(1024 * 1024 * 2, '&');
  8510. std::stringstream buffer;
  8511. buffer << data;
  8512. Client cli("https://localhost:8080");
  8513. cli.enable_server_certificate_verification(false);
  8514. UploadFormDataItems items{
  8515. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8516. {"hello", "world", "", ""},
  8517. };
  8518. for (const char &c : " \t\r\n") {
  8519. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8520. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8521. ASSERT_FALSE(res);
  8522. }
  8523. }
  8524. TEST(MultipartFormDataTest, AlternateFilename) {
  8525. auto handled = false;
  8526. Server svr;
  8527. svr.Post("/test", [&](const Request &req, Response &res) {
  8528. ASSERT_EQ(2u, req.form.files.size());
  8529. ASSERT_EQ(1u, req.form.fields.size());
  8530. // Test files
  8531. const auto &file1 = req.form.get_file("file1");
  8532. ASSERT_EQ("file1", file1.name);
  8533. ASSERT_EQ("A.txt", file1.filename);
  8534. ASSERT_EQ("text/plain", file1.content_type);
  8535. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8536. const auto &file2 = req.form.get_file("file2");
  8537. ASSERT_EQ("file2", file2.name);
  8538. ASSERT_EQ("a.html", file2.filename);
  8539. ASSERT_EQ("text/html", file2.content_type);
  8540. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8541. file2.content);
  8542. // Test text field
  8543. const auto &text = req.form.get_field("text");
  8544. ASSERT_EQ("text default", text);
  8545. res.set_content("ok", "text/plain");
  8546. handled = true;
  8547. });
  8548. thread t = thread([&] { svr.listen(HOST, PORT); });
  8549. auto se = detail::scope_exit([&] {
  8550. svr.stop();
  8551. t.join();
  8552. ASSERT_FALSE(svr.is_running());
  8553. ASSERT_TRUE(handled);
  8554. });
  8555. svr.wait_until_ready();
  8556. auto req = "POST /test HTTP/1.1\r\n"
  8557. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8558. "Content-Length: 399\r\n"
  8559. "\r\n"
  8560. "----------\r\n"
  8561. "Content-Disposition: form-data; name=\"text\"\r\n"
  8562. "\r\n"
  8563. "text default\r\n"
  8564. "----------\r\n"
  8565. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8566. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8567. "Content-Type: text/plain\r\n"
  8568. "\r\n"
  8569. "Content of a.txt.\r\n"
  8570. "\r\n"
  8571. "----------\r\n"
  8572. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8573. "\"a.html\"\r\n"
  8574. "Content-Type: text/html\r\n"
  8575. "\r\n"
  8576. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8577. "\r\n"
  8578. "------------\r\n";
  8579. ASSERT_TRUE(send_request(1, req));
  8580. }
  8581. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8582. auto handled = false;
  8583. Server svr;
  8584. svr.Post("/test", [&](const Request &req, Response &) {
  8585. ASSERT_EQ(2u, req.form.fields.size());
  8586. const auto &text1 = req.form.get_field("text1");
  8587. ASSERT_EQ("text1", text1);
  8588. const auto &text2 = req.form.get_field("text2");
  8589. ASSERT_EQ("text2", text2);
  8590. handled = true;
  8591. });
  8592. thread t = thread([&] { svr.listen(HOST, PORT); });
  8593. auto se = detail::scope_exit([&] {
  8594. svr.stop();
  8595. t.join();
  8596. ASSERT_FALSE(svr.is_running());
  8597. ASSERT_TRUE(handled);
  8598. });
  8599. svr.wait_until_ready();
  8600. auto req = "POST /test HTTP/1.1\r\n"
  8601. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8602. "Content-Length: 146\r\n"
  8603. "\r\n----------\r\n"
  8604. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8605. "\r\n"
  8606. "text1"
  8607. "\r\n----------\r\n"
  8608. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8609. "\r\n"
  8610. "text2"
  8611. "\r\n------------";
  8612. std::string response;
  8613. ASSERT_TRUE(send_request(1, req, &response));
  8614. ASSERT_EQ("200", response.substr(9, 3));
  8615. }
  8616. TEST(MultipartFormDataTest, ContentLength) {
  8617. auto handled = false;
  8618. Server svr;
  8619. svr.Post("/test", [&](const Request &req, Response &) {
  8620. ASSERT_EQ(2u, req.form.fields.size());
  8621. const auto &text1 = req.form.get_field("text1");
  8622. ASSERT_EQ("text1", text1);
  8623. const auto &text2 = req.form.get_field("text2");
  8624. ASSERT_EQ("text2", text2);
  8625. handled = true;
  8626. });
  8627. thread t = thread([&] { svr.listen(HOST, PORT); });
  8628. auto se = detail::scope_exit([&] {
  8629. svr.stop();
  8630. t.join();
  8631. ASSERT_FALSE(svr.is_running());
  8632. ASSERT_TRUE(handled);
  8633. });
  8634. svr.wait_until_ready();
  8635. auto req = "POST /test HTTP/1.1\r\n"
  8636. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8637. "Content-Length: 167\r\n"
  8638. "\r\n----------\r\n"
  8639. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8640. "Content-Length: 5\r\n"
  8641. "\r\n"
  8642. "text1"
  8643. "\r\n----------\r\n"
  8644. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8645. "\r\n"
  8646. "text2"
  8647. "\r\n------------\r\n";
  8648. std::string response;
  8649. ASSERT_TRUE(send_request(1, req, &response));
  8650. ASSERT_EQ("200", response.substr(9, 3));
  8651. }
  8652. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8653. auto handled = false;
  8654. Server svr;
  8655. svr.Post("/test", [&](const Request &req, Response &) {
  8656. ASSERT_EQ(2u, req.form.fields.size());
  8657. const auto &text1 = req.form.get_field("text1");
  8658. ASSERT_EQ("text1", text1);
  8659. // TODO: Add header access for text fields if needed
  8660. const auto &text2 = req.form.get_field("text2");
  8661. ASSERT_EQ("text2", text2);
  8662. // TODO: Header access for text fields needs to be implemented
  8663. // auto &headers = it->second.headers;
  8664. // ASSERT_EQ(3U, headers.size());
  8665. // auto custom_header = headers.find("x-whatever");
  8666. // ASSERT_TRUE(custom_header != headers.end());
  8667. // ASSERT_NE("customvalue", custom_header->second);
  8668. // ASSERT_EQ("CustomValue", custom_header->second);
  8669. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8670. handled = true;
  8671. });
  8672. thread t = thread([&] { svr.listen(HOST, PORT); });
  8673. auto se = detail::scope_exit([&] {
  8674. svr.stop();
  8675. t.join();
  8676. ASSERT_FALSE(svr.is_running());
  8677. ASSERT_TRUE(handled);
  8678. });
  8679. svr.wait_until_ready();
  8680. auto req = "POST /test HTTP/1.1\r\n"
  8681. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8682. "Content-Length: 232\r\n"
  8683. "\r\n----------\r\n"
  8684. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8685. "Content-Length: 5\r\n"
  8686. "X-Test: 1\r\n"
  8687. "\r\n"
  8688. "text1"
  8689. "\r\n----------\r\n"
  8690. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8691. "Content-Type: text/plain\r\n"
  8692. "X-Whatever: CustomValue\r\n"
  8693. "\r\n"
  8694. "text2"
  8695. "\r\n------------\r\n"
  8696. "That should be disregarded. Not even read";
  8697. std::string response;
  8698. ASSERT_TRUE(send_request(1, req, &response));
  8699. ASSERT_EQ("200", response.substr(9, 3));
  8700. }
  8701. #endif
  8702. TEST(MultipartFormDataTest, LargeHeader) {
  8703. auto handled = false;
  8704. Server svr;
  8705. svr.Post("/test", [&](const Request &req, Response &) {
  8706. ASSERT_EQ(1u, req.form.fields.size());
  8707. const auto &text = req.form.get_field("name1");
  8708. ASSERT_EQ("text1", text);
  8709. handled = true;
  8710. });
  8711. thread t = thread([&] { svr.listen(HOST, PORT); });
  8712. auto se = detail::scope_exit([&] {
  8713. svr.stop();
  8714. t.join();
  8715. ASSERT_FALSE(svr.is_running());
  8716. ASSERT_TRUE(handled);
  8717. });
  8718. svr.wait_until_ready();
  8719. auto boundary = std::string("cpp-httplib-multipart-data");
  8720. std::string content = "--" + boundary +
  8721. "\r\n"
  8722. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8723. "\r\n"
  8724. "text1\r\n"
  8725. "--" +
  8726. boundary + "--\r\n";
  8727. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8728. "Content-Type: multipart/form-data;boundary=" +
  8729. boundary +
  8730. "\r\n"
  8731. "Content-Length: " +
  8732. std::to_string(content.size()) +
  8733. "\r\n"
  8734. "Dummy-Header: ";
  8735. std::string header_suffix = "\r\n"
  8736. "\r\n";
  8737. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8738. size_t header_dummy_size =
  8739. read_buff_size -
  8740. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8741. auto header_dummy = std::string(header_dummy_size, '@');
  8742. auto req = header_prefix + header_dummy + header_suffix + content;
  8743. std::string response;
  8744. ASSERT_TRUE(send_request(1, req, &response));
  8745. ASSERT_EQ("200", response.substr(9, 3));
  8746. }
  8747. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8748. static constexpr unsigned int number_of_tasks{1000000};
  8749. std::atomic_uint count{0};
  8750. std::unique_ptr<TaskQueue> task_queue{
  8751. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8752. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8753. auto queued = task_queue->enqueue(
  8754. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8755. EXPECT_TRUE(queued);
  8756. }
  8757. EXPECT_NO_THROW(task_queue->shutdown());
  8758. EXPECT_EQ(number_of_tasks, count.load());
  8759. }
  8760. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8761. static constexpr unsigned int number_of_tasks{1000000};
  8762. static constexpr unsigned int qlimit{2};
  8763. unsigned int queued_count{0};
  8764. std::atomic_uint count{0};
  8765. std::unique_ptr<TaskQueue> task_queue{
  8766. new ThreadPool{/*num_threads=*/1, qlimit}};
  8767. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8768. if (task_queue->enqueue(
  8769. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8770. queued_count++;
  8771. }
  8772. }
  8773. EXPECT_NO_THROW(task_queue->shutdown());
  8774. EXPECT_EQ(queued_count, count.load());
  8775. EXPECT_TRUE(queued_count <= number_of_tasks);
  8776. EXPECT_TRUE(queued_count >= qlimit);
  8777. }
  8778. TEST(TaskQueueTest, MaxQueuedRequests) {
  8779. static constexpr unsigned int qlimit{3};
  8780. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8781. std::condition_variable sem_cv;
  8782. std::mutex sem_mtx;
  8783. int credits = 0;
  8784. bool queued;
  8785. /* Fill up the queue with tasks that will block until we give them credits to
  8786. * complete. */
  8787. for (unsigned int n = 0; n <= qlimit;) {
  8788. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8789. std::unique_lock<std::mutex> lock(sem_mtx);
  8790. while (credits <= 0) {
  8791. sem_cv.wait(lock);
  8792. }
  8793. /* Consume the credit and signal the test code if they are all gone. */
  8794. if (--credits == 0) { sem_cv.notify_one(); }
  8795. });
  8796. if (n < qlimit) {
  8797. /* The first qlimit enqueues must succeed. */
  8798. EXPECT_TRUE(queued);
  8799. } else {
  8800. /* The last one will succeed only when the worker thread
  8801. * starts and dequeues the first blocking task. Although
  8802. * not necessary for the correctness of this test, we sleep for
  8803. * a short while to avoid busy waiting. */
  8804. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8805. }
  8806. if (queued) { n++; }
  8807. }
  8808. /* Further enqueues must fail since the queue is full. */
  8809. for (auto i = 0; i < 4; i++) {
  8810. queued = task_queue->enqueue([] {});
  8811. EXPECT_FALSE(queued);
  8812. }
  8813. /* Give the credits to allow the previous tasks to complete. */
  8814. {
  8815. std::unique_lock<std::mutex> lock(sem_mtx);
  8816. credits += qlimit + 1;
  8817. }
  8818. sem_cv.notify_all();
  8819. /* Wait for all the credits to be consumed. */
  8820. {
  8821. std::unique_lock<std::mutex> lock(sem_mtx);
  8822. while (credits > 0) {
  8823. sem_cv.wait(lock);
  8824. }
  8825. }
  8826. /* Check that we are able again to enqueue at least qlimit tasks. */
  8827. for (unsigned int i = 0; i < qlimit; i++) {
  8828. queued = task_queue->enqueue([] {});
  8829. EXPECT_TRUE(queued);
  8830. }
  8831. EXPECT_NO_THROW(task_queue->shutdown());
  8832. }
  8833. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8834. Server svr;
  8835. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8836. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8837. });
  8838. svr.Get("/hello", [](const Request &req, Response &res) {
  8839. res.set_content(req.get_param_value("key"), "text/plain");
  8840. });
  8841. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. thread.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. {
  8849. Client cli(HOST, PORT);
  8850. cli.set_follow_location(true);
  8851. auto res = cli.Get("/");
  8852. ASSERT_TRUE(res);
  8853. EXPECT_EQ(StatusCode::OK_200, res->status);
  8854. EXPECT_EQ("val&key2=val2", res->body);
  8855. }
  8856. }
  8857. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8858. Server svr;
  8859. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8860. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8861. });
  8862. svr.Get("/hello", [](const Request &req, Response &res) {
  8863. res.set_content(req.get_param_value("key"), "text/plain");
  8864. });
  8865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8866. auto se = detail::scope_exit([&] {
  8867. svr.stop();
  8868. thread.join();
  8869. ASSERT_FALSE(svr.is_running());
  8870. });
  8871. svr.wait_until_ready();
  8872. {
  8873. Client cli(HOST, PORT);
  8874. cli.set_follow_location(true);
  8875. auto res = cli.Get("/");
  8876. ASSERT_TRUE(res);
  8877. EXPECT_EQ(StatusCode::OK_200, res->status);
  8878. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8879. }
  8880. }
  8881. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8882. TEST(RedirectTest, Issue2185_Online) {
  8883. SSLClient client("github.com");
  8884. client.set_follow_location(true);
  8885. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8886. "Coollab-Windows.zip");
  8887. ASSERT_TRUE(res);
  8888. EXPECT_EQ(StatusCode::OK_200, res->status);
  8889. EXPECT_EQ(9920427U, res->body.size());
  8890. }
  8891. #endif
  8892. TEST(VulnerabilityTest, CRLFInjection) {
  8893. Server svr;
  8894. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8895. res.set_content("Hello 1", "text/plain");
  8896. });
  8897. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8898. res.set_content("Hello 2", "text/plain");
  8899. });
  8900. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8901. res.set_content("Hello 3", "text/plain");
  8902. });
  8903. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8904. res.set_content("Hello 4", "text/plain");
  8905. });
  8906. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8907. for (const auto &x : req.headers) {
  8908. auto key = x.first;
  8909. EXPECT_STRNE("evil", key.c_str());
  8910. }
  8911. });
  8912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8913. auto se = detail::scope_exit([&] {
  8914. svr.stop();
  8915. thread.join();
  8916. ASSERT_FALSE(svr.is_running());
  8917. });
  8918. svr.wait_until_ready();
  8919. {
  8920. Client cli(HOST, PORT);
  8921. cli.Post("/test1", "A=B",
  8922. "application/x-www-form-urlencoded\r\nevil: hello1");
  8923. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8924. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8925. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8926. }
  8927. }
  8928. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  8929. auto server_thread = std::thread([] {
  8930. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8931. int on = 1;
  8932. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  8933. sockaddr_in addr{};
  8934. addr.sin_family = AF_INET;
  8935. addr.sin_port = htons(PORT);
  8936. ::inet_pton(AF_INET, HOST, &addr.sin_addr);
  8937. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8938. ::listen(srv, 1);
  8939. sockaddr_in cli_addr{};
  8940. socklen_t cli_len = sizeof(cli_addr);
  8941. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8942. struct timeval tv;
  8943. tv.tv_sec = 1;
  8944. tv.tv_usec = 0;
  8945. ::setsockopt(cli, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
  8946. std::string buf_all;
  8947. char buf[2048];
  8948. ssize_t n;
  8949. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  8950. buf_all.append(buf, static_cast<size_t>(n));
  8951. size_t pos;
  8952. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  8953. auto request_block = buf_all.substr(0, pos + 4); // include separator
  8954. auto e = request_block.find("\r\n");
  8955. if (e != std::string::npos) {
  8956. auto request_line = request_block.substr(0, e);
  8957. std::string msg =
  8958. "CRLF injection detected in request line: '" + request_line + "'";
  8959. EXPECT_FALSE(true) << msg;
  8960. }
  8961. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  8962. ::send(cli, resp.c_str(), resp.size(), 0);
  8963. buf_all.erase(0, pos + 4);
  8964. }
  8965. }
  8966. ::close(cli);
  8967. ::close(srv);
  8968. });
  8969. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  8970. auto cli = httplib::Client(HOST, PORT);
  8971. auto headers = httplib::Headers{
  8972. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  8973. {"Connection", "keep-alive"}};
  8974. auto res = cli.Get("/hi", headers);
  8975. EXPECT_FALSE(res);
  8976. if (res) { EXPECT_EQ(httplib::Error::InvalidHeaders, res.error()); }
  8977. server_thread.join();
  8978. }
  8979. TEST(PathParamsTest, StaticMatch) {
  8980. const auto pattern = "/users/all";
  8981. detail::PathParamsMatcher matcher(pattern);
  8982. Request request;
  8983. request.path = "/users/all";
  8984. ASSERT_TRUE(matcher.match(request));
  8985. std::unordered_map<std::string, std::string> expected_params = {};
  8986. EXPECT_EQ(request.path_params, expected_params);
  8987. }
  8988. TEST(PathParamsTest, StaticMismatch) {
  8989. const auto pattern = "/users/all";
  8990. detail::PathParamsMatcher matcher(pattern);
  8991. Request request;
  8992. request.path = "/users/1";
  8993. ASSERT_FALSE(matcher.match(request));
  8994. }
  8995. TEST(PathParamsTest, SingleParamInTheMiddle) {
  8996. const auto pattern = "/users/:id/subscriptions";
  8997. detail::PathParamsMatcher matcher(pattern);
  8998. Request request;
  8999. request.path = "/users/42/subscriptions";
  9000. ASSERT_TRUE(matcher.match(request));
  9001. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9002. EXPECT_EQ(request.path_params, expected_params);
  9003. }
  9004. TEST(PathParamsTest, SingleParamInTheEnd) {
  9005. const auto pattern = "/users/:id";
  9006. detail::PathParamsMatcher matcher(pattern);
  9007. Request request;
  9008. request.path = "/users/24";
  9009. ASSERT_TRUE(matcher.match(request));
  9010. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9011. EXPECT_EQ(request.path_params, expected_params);
  9012. }
  9013. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9014. const auto pattern = "/users/:id/";
  9015. detail::PathParamsMatcher matcher(pattern);
  9016. Request request;
  9017. request.path = "/users/42/";
  9018. ASSERT_TRUE(matcher.match(request));
  9019. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9020. EXPECT_EQ(request.path_params, expected_params);
  9021. }
  9022. TEST(PathParamsTest, EmptyParam) {
  9023. const auto pattern = "/users/:id/";
  9024. detail::PathParamsMatcher matcher(pattern);
  9025. Request request;
  9026. request.path = "/users//";
  9027. ASSERT_TRUE(matcher.match(request));
  9028. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9029. EXPECT_EQ(request.path_params, expected_params);
  9030. }
  9031. TEST(PathParamsTest, FragmentMismatch) {
  9032. const auto pattern = "/users/:id/";
  9033. detail::PathParamsMatcher matcher(pattern);
  9034. Request request;
  9035. request.path = "/admins/24/";
  9036. ASSERT_FALSE(matcher.match(request));
  9037. }
  9038. TEST(PathParamsTest, ExtraFragments) {
  9039. const auto pattern = "/users/:id";
  9040. detail::PathParamsMatcher matcher(pattern);
  9041. Request request;
  9042. request.path = "/users/42/subscriptions";
  9043. ASSERT_FALSE(matcher.match(request));
  9044. }
  9045. TEST(PathParamsTest, MissingTrailingParam) {
  9046. const auto pattern = "/users/:id";
  9047. detail::PathParamsMatcher matcher(pattern);
  9048. Request request;
  9049. request.path = "/users";
  9050. ASSERT_FALSE(matcher.match(request));
  9051. }
  9052. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9053. const auto pattern = "/users/:id/subscriptions";
  9054. detail::PathParamsMatcher matcher(pattern);
  9055. Request request;
  9056. request.path = "/users/subscriptions";
  9057. ASSERT_FALSE(matcher.match(request));
  9058. }
  9059. TEST(PathParamsTest, MultipleParams) {
  9060. const auto pattern = "/users/:userid/subscriptions/:subid";
  9061. detail::PathParamsMatcher matcher(pattern);
  9062. Request request;
  9063. request.path = "/users/42/subscriptions/2";
  9064. ASSERT_TRUE(matcher.match(request));
  9065. std::unordered_map<std::string, std::string> expected_params = {
  9066. {"userid", "42"}, {"subid", "2"}};
  9067. EXPECT_EQ(request.path_params, expected_params);
  9068. }
  9069. TEST(PathParamsTest, SequenceOfParams) {
  9070. const auto pattern = "/values/:x/:y/:z";
  9071. detail::PathParamsMatcher matcher(pattern);
  9072. Request request;
  9073. request.path = "/values/1/2/3";
  9074. ASSERT_TRUE(matcher.match(request));
  9075. std::unordered_map<std::string, std::string> expected_params = {
  9076. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9077. EXPECT_EQ(request.path_params, expected_params);
  9078. }
  9079. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9080. const auto pattern = "/prefix:suffix";
  9081. detail::PathParamsMatcher matcher(pattern);
  9082. Request request;
  9083. request.path = "/prefix:suffix";
  9084. ASSERT_TRUE(matcher.match(request));
  9085. const std::unordered_map<std::string, std::string> expected_params = {};
  9086. EXPECT_EQ(request.path_params, expected_params);
  9087. }
  9088. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9089. // If ipv6 regex working, regex match codepath is taken.
  9090. // else port will default to 80 in Client impl
  9091. int clientImplMagicPort = 80;
  9092. int port = 4321;
  9093. // above ports must be different to avoid false negative
  9094. EXPECT_NE(clientImplMagicPort, port);
  9095. std::string ipV6TestURL = "http://[ff06::c3]";
  9096. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9097. CLIENT_PRIVATE_KEY_FILE);
  9098. EXPECT_EQ(cli.port(), port);
  9099. }
  9100. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9101. auto file_path = "./www/dir/index.html";
  9102. auto dir_path = "./www/dir";
  9103. detail::FileStat stat_file(file_path);
  9104. EXPECT_TRUE(stat_file.is_file());
  9105. EXPECT_FALSE(stat_file.is_dir());
  9106. detail::FileStat stat_dir(dir_path);
  9107. EXPECT_FALSE(stat_dir.is_file());
  9108. EXPECT_TRUE(stat_dir.is_dir());
  9109. }
  9110. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9111. // IPv4 with default HTTP port (80)
  9112. EXPECT_EQ("example.com",
  9113. detail::make_host_and_port_string("example.com", 80, false));
  9114. // IPv4 with default HTTPS port (443)
  9115. EXPECT_EQ("example.com",
  9116. detail::make_host_and_port_string("example.com", 443, true));
  9117. // IPv4 with non-default HTTP port
  9118. EXPECT_EQ("example.com:8080",
  9119. detail::make_host_and_port_string("example.com", 8080, false));
  9120. // IPv4 with non-default HTTPS port
  9121. EXPECT_EQ("example.com:8443",
  9122. detail::make_host_and_port_string("example.com", 8443, true));
  9123. // IPv6 with default HTTP port (80)
  9124. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9125. // IPv6 with default HTTPS port (443)
  9126. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9127. // IPv6 with non-default HTTP port
  9128. EXPECT_EQ("[::1]:8080",
  9129. detail::make_host_and_port_string("::1", 8080, false));
  9130. // IPv6 with non-default HTTPS port
  9131. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9132. // IPv6 full address with default port
  9133. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9134. detail::make_host_and_port_string(
  9135. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9136. // IPv6 full address with non-default port
  9137. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9138. detail::make_host_and_port_string(
  9139. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9140. // IPv6 localhost with non-default port
  9141. EXPECT_EQ("[::1]:3000",
  9142. detail::make_host_and_port_string("::1", 3000, false));
  9143. // IPv6 with zone ID (link-local address) with default port
  9144. EXPECT_EQ("[fe80::1%eth0]",
  9145. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9146. // IPv6 with zone ID (link-local address) with non-default port
  9147. EXPECT_EQ("[fe80::1%eth0]:8080",
  9148. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9149. // Edge case: Port 443 with is_ssl=false (should add port)
  9150. EXPECT_EQ("example.com:443",
  9151. detail::make_host_and_port_string("example.com", 443, false));
  9152. // Edge case: Port 80 with is_ssl=true (should add port)
  9153. EXPECT_EQ("example.com:80",
  9154. detail::make_host_and_port_string("example.com", 80, true));
  9155. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9156. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9157. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9158. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9159. // Security fix: Already bracketed IPv6 should not get double brackets
  9160. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9161. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9162. EXPECT_EQ("[::1]:8080",
  9163. detail::make_host_and_port_string("[::1]", 8080, false));
  9164. EXPECT_EQ("[2001:db8::1]:8080",
  9165. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9166. EXPECT_EQ("[fe80::1%eth0]",
  9167. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9168. EXPECT_EQ("[fe80::1%eth0]:8080",
  9169. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9170. // Edge case: Empty host (should return as-is)
  9171. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9172. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9173. // This is a known limitation but shouldn't crash
  9174. EXPECT_EQ("[host:name]",
  9175. detail::make_host_and_port_string("host:name", 80, false));
  9176. // Port number edge cases (no validation, but should not crash)
  9177. EXPECT_EQ("example.com:0",
  9178. detail::make_host_and_port_string("example.com", 0, false));
  9179. EXPECT_EQ("example.com:-1",
  9180. detail::make_host_and_port_string("example.com", -1, false));
  9181. EXPECT_EQ("example.com:65535",
  9182. detail::make_host_and_port_string("example.com", 65535, false));
  9183. EXPECT_EQ("example.com:65536",
  9184. detail::make_host_and_port_string("example.com", 65536, false));
  9185. }
  9186. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9187. TEST(SSLClientHostHeaderTest, Issue2301) {
  9188. httplib::SSLClient cli("roblox.com", 443);
  9189. cli.set_follow_location(true);
  9190. auto res = cli.Get("/");
  9191. ASSERT_TRUE(res);
  9192. EXPECT_EQ(StatusCode::OK_200, res->status);
  9193. }
  9194. #endif
  9195. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9196. Server svr;
  9197. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9198. EXPECT_EQ(res.status, 400);
  9199. });
  9200. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9201. auto se = detail::scope_exit([&] {
  9202. svr.stop();
  9203. thread.join();
  9204. ASSERT_FALSE(svr.is_running());
  9205. });
  9206. svr.wait_until_ready();
  9207. Client cli(HOST, PORT);
  9208. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9209. }
  9210. TEST(InvalidHeaderCharsTest, is_field_name) {
  9211. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9212. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9213. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9214. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9215. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9216. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9217. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9218. EXPECT_FALSE(detail::fields::is_field_name(""));
  9219. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9220. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9221. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9222. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9223. }
  9224. TEST(InvalidHeaderCharsTest, is_field_value) {
  9225. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9226. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9227. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9228. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9229. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9230. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9231. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9232. EXPECT_TRUE(detail::fields::is_field_value(""));
  9233. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9234. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9235. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9236. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9237. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9238. }
  9239. TEST(InvalidHeaderCharsTest, OnServer) {
  9240. Server svr;
  9241. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9242. std::string header = "Not Set";
  9243. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9244. res.set_header(header, "value");
  9245. res.set_content("Page Content Page Content", "text/plain");
  9246. });
  9247. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9248. std::string header = "Not Set";
  9249. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9250. res.set_header("X-Test", header);
  9251. res.set_content("Page Content Page Content", "text/plain");
  9252. });
  9253. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9254. auto se = detail::scope_exit([&] {
  9255. svr.stop();
  9256. thread.join();
  9257. ASSERT_FALSE(svr.is_running());
  9258. });
  9259. svr.wait_until_ready();
  9260. Client cli(HOST, PORT);
  9261. {
  9262. auto res = cli.Get(
  9263. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9264. ASSERT_TRUE(res);
  9265. EXPECT_EQ("Page Content Page Content", res->body);
  9266. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9267. }
  9268. {
  9269. auto res = cli.Get(
  9270. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9271. ASSERT_TRUE(res);
  9272. EXPECT_EQ("Page Content Page Content", res->body);
  9273. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9274. }
  9275. }
  9276. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9277. auto handled = false;
  9278. Server svr;
  9279. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9280. thread t = thread([&] { svr.listen(HOST, PORT); });
  9281. auto se = detail::scope_exit([&] {
  9282. svr.stop();
  9283. t.join();
  9284. ASSERT_FALSE(svr.is_running());
  9285. ASSERT_FALSE(handled);
  9286. });
  9287. svr.wait_until_ready();
  9288. auto req = "POST /test HTTP/1.1\r\n"
  9289. "Content-Length: x\r\n"
  9290. "\r\n";
  9291. std::string response;
  9292. ASSERT_TRUE(send_request(1, req, &response));
  9293. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9294. response.substr(0, response.find("\r\n")));
  9295. }
  9296. #ifndef _WIN32
  9297. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9298. static constexpr char reject[] = "Unauthorized";
  9299. static constexpr char accept[] = "Upload accepted";
  9300. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9301. Server svr;
  9302. svr.set_expect_100_continue_handler(
  9303. [](const Request & /*req*/, Response &res) {
  9304. res.status = StatusCode::Unauthorized_401;
  9305. res.set_content(reject, "text/plain");
  9306. return res.status;
  9307. });
  9308. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9309. res.set_content(accept, "text/plain");
  9310. });
  9311. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9312. auto se = detail::scope_exit([&] {
  9313. svr.stop();
  9314. thread.join();
  9315. ASSERT_FALSE(svr.is_running());
  9316. });
  9317. svr.wait_until_ready();
  9318. {
  9319. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9320. curl_easy_init(), &curl_easy_cleanup};
  9321. ASSERT_NE(curl, nullptr);
  9322. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9323. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9324. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9325. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9326. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9327. &curl_slist_free_all};
  9328. ASSERT_NE(list, nullptr);
  9329. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9330. struct read_data {
  9331. size_t read_size;
  9332. size_t total_size;
  9333. } data = {0, total_size};
  9334. using read_callback_t =
  9335. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9336. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9337. void *userdata) -> size_t {
  9338. read_data *data = (read_data *)userdata;
  9339. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9340. std::fill_n(ptr, size * nmemb, 'A');
  9341. data->read_size += size * nmemb;
  9342. return size * nmemb;
  9343. };
  9344. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9345. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9346. std::vector<char> buffer;
  9347. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9348. using write_callback_t =
  9349. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9350. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9351. void *userdata) -> size_t {
  9352. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9353. buffer->reserve(buffer->size() + size * nmemb + 1);
  9354. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9355. return size * nmemb;
  9356. };
  9357. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9358. {
  9359. const auto res = curl_easy_perform(curl.get());
  9360. ASSERT_EQ(res, CURLE_OK);
  9361. }
  9362. {
  9363. auto response_code = long{};
  9364. const auto res =
  9365. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9366. ASSERT_EQ(res, CURLE_OK);
  9367. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9368. }
  9369. {
  9370. auto dl = curl_off_t{};
  9371. const auto res =
  9372. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9373. ASSERT_EQ(res, CURLE_OK);
  9374. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9375. }
  9376. {
  9377. buffer.push_back('\0');
  9378. ASSERT_STRCASEEQ(buffer.data(), reject);
  9379. }
  9380. }
  9381. }
  9382. #endif
  9383. template <typename S, typename C>
  9384. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9385. svr.Get("/stream", [&](const Request &, Response &res) {
  9386. auto data = new std::string("01234567890123456789");
  9387. res.set_content_provider(
  9388. data->size(), "text/plain",
  9389. [&, data](size_t offset, size_t length, DataSink &sink) {
  9390. const size_t DATA_CHUNK_SIZE = 4;
  9391. const auto &d = *data;
  9392. std::this_thread::sleep_for(std::chrono::seconds(1));
  9393. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9394. return true;
  9395. },
  9396. [data](bool success) {
  9397. EXPECT_FALSE(success);
  9398. delete data;
  9399. });
  9400. });
  9401. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9402. auto i = new size_t(0);
  9403. res.set_content_provider(
  9404. "text/plain",
  9405. [i](size_t, DataSink &sink) {
  9406. if (*i < 5) {
  9407. std::this_thread::sleep_for(std::chrono::seconds(1));
  9408. sink.write("abcd", 4);
  9409. (*i)++;
  9410. } else {
  9411. sink.done();
  9412. }
  9413. return true;
  9414. },
  9415. [i](bool success) {
  9416. EXPECT_FALSE(success);
  9417. delete i;
  9418. });
  9419. });
  9420. svr.Get("/chunked", [&](const Request &, Response &res) {
  9421. auto i = new size_t(0);
  9422. res.set_chunked_content_provider(
  9423. "text/plain",
  9424. [i](size_t, DataSink &sink) {
  9425. if (*i < 5) {
  9426. std::this_thread::sleep_for(std::chrono::seconds(1));
  9427. sink.os << "abcd";
  9428. (*i)++;
  9429. } else {
  9430. sink.done();
  9431. }
  9432. return true;
  9433. },
  9434. [i](bool success) {
  9435. EXPECT_FALSE(success);
  9436. delete i;
  9437. });
  9438. });
  9439. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9440. auto se = detail::scope_exit([&] {
  9441. svr.stop();
  9442. listen_thread.join();
  9443. ASSERT_FALSE(svr.is_running());
  9444. });
  9445. svr.wait_until_ready();
  9446. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9447. {
  9448. auto start = std::chrono::steady_clock::now();
  9449. auto res = cli.Get("/stream");
  9450. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9451. std::chrono::steady_clock::now() - start)
  9452. .count();
  9453. ASSERT_FALSE(res);
  9454. EXPECT_EQ(Error::Read, res.error());
  9455. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9456. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9457. }
  9458. {
  9459. auto start = std::chrono::steady_clock::now();
  9460. auto res = cli.Get("/stream_without_length");
  9461. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9462. std::chrono::steady_clock::now() - start)
  9463. .count();
  9464. ASSERT_FALSE(res);
  9465. EXPECT_EQ(Error::Read, res.error());
  9466. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9467. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9468. }
  9469. {
  9470. auto start = std::chrono::steady_clock::now();
  9471. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9472. EXPECT_EQ("abcd", string(data, data_length));
  9473. return true;
  9474. });
  9475. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9476. std::chrono::steady_clock::now() - start)
  9477. .count();
  9478. ASSERT_FALSE(res);
  9479. EXPECT_EQ(Error::Read, res.error());
  9480. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9481. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9482. }
  9483. }
  9484. TEST(MaxTimeoutTest, ContentStream) {
  9485. time_t timeout = 2000;
  9486. time_t threshold = 200;
  9487. Server svr;
  9488. Client cli("localhost", PORT);
  9489. max_timeout_test(svr, cli, timeout, threshold);
  9490. }
  9491. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9492. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9493. time_t timeout = 2000;
  9494. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9496. SSLClient cli("localhost", PORT);
  9497. cli.enable_server_certificate_verification(false);
  9498. max_timeout_test(svr, cli, timeout, threshold);
  9499. }
  9500. #endif
  9501. class EventDispatcher {
  9502. public:
  9503. EventDispatcher() {}
  9504. bool wait_event(DataSink *sink) {
  9505. unique_lock<mutex> lk(m_);
  9506. int id = id_;
  9507. // Wait with timeout to prevent hanging if client disconnects
  9508. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9509. [&] { return cid_ == id; })) {
  9510. return false; // Timeout occurred
  9511. }
  9512. sink->write(message_.data(), message_.size());
  9513. return true;
  9514. }
  9515. void send_event(const string &message) {
  9516. lock_guard<mutex> lk(m_);
  9517. cid_ = id_++;
  9518. message_ = message;
  9519. cv_.notify_all();
  9520. }
  9521. private:
  9522. mutex m_;
  9523. condition_variable cv_;
  9524. atomic_int id_{0};
  9525. atomic_int cid_{-1};
  9526. string message_;
  9527. };
  9528. TEST(ClientInThreadTest, Issue2068) {
  9529. EventDispatcher ed;
  9530. Server svr;
  9531. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9532. res.set_chunked_content_provider("text/event-stream",
  9533. [&](size_t /*offset*/, DataSink &sink) {
  9534. return ed.wait_event(&sink);
  9535. });
  9536. });
  9537. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9538. svr.wait_until_ready();
  9539. thread event_thread([&] {
  9540. int id = 0;
  9541. while (svr.is_running()) {
  9542. this_thread::sleep_for(chrono::milliseconds(500));
  9543. std::stringstream ss;
  9544. ss << "data: " << id << "\n\n";
  9545. ed.send_event(ss.str());
  9546. id++;
  9547. }
  9548. });
  9549. auto se = detail::scope_exit([&] {
  9550. svr.stop();
  9551. listen_thread.join();
  9552. event_thread.join();
  9553. ASSERT_FALSE(svr.is_running());
  9554. });
  9555. {
  9556. auto client = detail::make_unique<Client>(HOST, PORT);
  9557. client->set_read_timeout(std::chrono::minutes(10));
  9558. std::atomic<bool> stop{false};
  9559. std::thread t([&] {
  9560. client->Get("/event1",
  9561. [&](const char *, size_t) -> bool { return !stop; });
  9562. });
  9563. std::this_thread::sleep_for(std::chrono::seconds(2));
  9564. stop = true;
  9565. client->stop();
  9566. t.join();
  9567. // Reset client after thread has finished
  9568. client.reset();
  9569. }
  9570. }
  9571. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9572. Server svr;
  9573. svr.Get("/", [](const Request &req, Response &res) {
  9574. EXPECT_EQ(2U, req.trailers.size());
  9575. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9576. // Denied
  9577. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9578. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9579. // Accepted
  9580. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9581. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9582. EXPECT_TRUE(req.has_trailer("X-World"));
  9583. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9584. res.set_content("ok", "text/plain");
  9585. });
  9586. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9587. auto se = detail::scope_exit([&] {
  9588. svr.stop();
  9589. t.join();
  9590. ASSERT_FALSE(svr.is_running());
  9591. });
  9592. svr.wait_until_ready();
  9593. const std::string req = "GET / HTTP/1.1\r\n"
  9594. "Transfer-Encoding: chunked\r\n"
  9595. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9596. "\r\n"
  9597. "0\r\n"
  9598. "Content-Length: 10\r\n"
  9599. "Host: internal.local\r\n"
  9600. "Content-Type: malicious/content\r\n"
  9601. "Cookie: any\r\n"
  9602. "Set-Cookie: any\r\n"
  9603. "X-Forwarded-For: attacker.com\r\n"
  9604. "X-Real-Ip: 1.1.1.1\r\n"
  9605. "X-Hello: hello\r\n"
  9606. "X-World: world\r\n"
  9607. "\r\n";
  9608. std::string res;
  9609. ASSERT_TRUE(send_request(1, req, &res));
  9610. }
  9611. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9612. Server svr;
  9613. std::string observed_remote_addr;
  9614. std::string observed_xff;
  9615. svr.Get("/ip", [&](const Request &req, Response &res) {
  9616. observed_remote_addr = req.remote_addr;
  9617. observed_xff = req.get_header_value("X-Forwarded-For");
  9618. res.set_content("ok", "text/plain");
  9619. });
  9620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9621. auto se = detail::scope_exit([&] {
  9622. svr.stop();
  9623. t.join();
  9624. ASSERT_FALSE(svr.is_running());
  9625. });
  9626. svr.wait_until_ready();
  9627. Client cli(HOST, PORT);
  9628. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9629. ASSERT_TRUE(res);
  9630. EXPECT_EQ(StatusCode::OK_200, res->status);
  9631. EXPECT_EQ(observed_xff, "203.0.113.66");
  9632. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9633. observed_remote_addr == "127.0.0.1");
  9634. }
  9635. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9636. Server svr;
  9637. svr.set_trusted_proxies({"203.0.113.66"});
  9638. std::string observed_remote_addr;
  9639. std::string observed_xff;
  9640. svr.Get("/ip", [&](const Request &req, Response &res) {
  9641. observed_remote_addr = req.remote_addr;
  9642. observed_xff = req.get_header_value("X-Forwarded-For");
  9643. res.set_content("ok", "text/plain");
  9644. });
  9645. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9646. auto se = detail::scope_exit([&] {
  9647. svr.stop();
  9648. t.join();
  9649. ASSERT_FALSE(svr.is_running());
  9650. });
  9651. svr.wait_until_ready();
  9652. Client cli(HOST, PORT);
  9653. auto res = cli.Get("/ip");
  9654. ASSERT_TRUE(res);
  9655. EXPECT_EQ(StatusCode::OK_200, res->status);
  9656. EXPECT_EQ(observed_xff, "");
  9657. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9658. observed_remote_addr == "127.0.0.1");
  9659. }
  9660. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9661. Server svr;
  9662. svr.set_trusted_proxies({"203.0.113.66"});
  9663. std::string observed_remote_addr;
  9664. std::string observed_xff;
  9665. svr.Get("/ip", [&](const Request &req, Response &res) {
  9666. observed_remote_addr = req.remote_addr;
  9667. observed_xff = req.get_header_value("X-Forwarded-For");
  9668. res.set_content("ok", "text/plain");
  9669. });
  9670. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. t.join();
  9674. ASSERT_FALSE(svr.is_running());
  9675. });
  9676. svr.wait_until_ready();
  9677. Client cli(HOST, PORT);
  9678. auto res =
  9679. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9680. ASSERT_TRUE(res);
  9681. EXPECT_EQ(StatusCode::OK_200, res->status);
  9682. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9683. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9684. }
  9685. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9686. Server svr;
  9687. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9688. std::string observed_remote_addr;
  9689. std::string observed_xff;
  9690. svr.Get("/ip", [&](const Request &req, Response &res) {
  9691. observed_remote_addr = req.remote_addr;
  9692. observed_xff = req.get_header_value("X-Forwarded-For");
  9693. res.set_content("ok", "text/plain");
  9694. });
  9695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9696. auto se = detail::scope_exit([&] {
  9697. svr.stop();
  9698. t.join();
  9699. ASSERT_FALSE(svr.is_running());
  9700. });
  9701. svr.wait_until_ready();
  9702. Client cli(HOST, PORT);
  9703. auto res = cli.Get(
  9704. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9705. ASSERT_TRUE(res);
  9706. EXPECT_EQ(StatusCode::OK_200, res->status);
  9707. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9708. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9709. }
  9710. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9711. Server svr;
  9712. svr.set_trusted_proxies({"192.0.2.45"});
  9713. std::string observed_remote_addr;
  9714. std::string observed_xff;
  9715. svr.Get("/ip", [&](const Request &req, Response &res) {
  9716. observed_remote_addr = req.remote_addr;
  9717. observed_xff = req.get_header_value("X-Forwarded-For");
  9718. res.set_content("ok", "text/plain");
  9719. });
  9720. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9721. auto se = detail::scope_exit([&] {
  9722. svr.stop();
  9723. t.join();
  9724. ASSERT_FALSE(svr.is_running());
  9725. });
  9726. svr.wait_until_ready();
  9727. Client cli(HOST, PORT);
  9728. auto res =
  9729. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9730. ASSERT_TRUE(res);
  9731. EXPECT_EQ(StatusCode::OK_200, res->status);
  9732. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9733. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9734. }
  9735. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9736. Server svr;
  9737. svr.set_trusted_proxies({"192.0.2.45"});
  9738. std::string observed_remote_addr;
  9739. std::string observed_xff;
  9740. svr.Get("/ip", [&](const Request &req, Response &res) {
  9741. observed_remote_addr = req.remote_addr;
  9742. observed_xff = req.get_header_value("X-Forwarded-For");
  9743. res.set_content("ok", "text/plain");
  9744. });
  9745. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9746. auto se = detail::scope_exit([&] {
  9747. svr.stop();
  9748. t.join();
  9749. ASSERT_FALSE(svr.is_running());
  9750. });
  9751. svr.wait_until_ready();
  9752. Client cli(HOST, PORT);
  9753. auto res = cli.Get(
  9754. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9755. ASSERT_TRUE(res);
  9756. EXPECT_EQ(StatusCode::OK_200, res->status);
  9757. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9758. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9759. }
  9760. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9761. Server svr;
  9762. svr.set_trusted_proxies({"192.0.2.45"});
  9763. std::string observed_remote_addr;
  9764. std::string observed_xff;
  9765. svr.Get("/ip", [&](const Request &req, Response &res) {
  9766. observed_remote_addr = req.remote_addr;
  9767. observed_xff = req.get_header_value("X-Forwarded-For");
  9768. res.set_content("ok", "text/plain");
  9769. });
  9770. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9771. auto se = detail::scope_exit([&] {
  9772. svr.stop();
  9773. t.join();
  9774. ASSERT_FALSE(svr.is_running());
  9775. });
  9776. svr.wait_until_ready();
  9777. std::string raw_req =
  9778. "GET /ip HTTP/1.1\r\n"
  9779. "Host: localhost\r\n"
  9780. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9781. "Connection: close\r\n"
  9782. "\r\n";
  9783. std::string out;
  9784. ASSERT_TRUE(send_request(5, raw_req, &out));
  9785. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9786. // Header parser trims surrounding whitespace of the header value
  9787. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9788. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9789. }
  9790. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9791. Server svr;
  9792. svr.Post("/post", [&](const Request &req, Response &res) {
  9793. res.set_content(req.body, "text/plain");
  9794. });
  9795. svr.Put("/put", [&](const Request &req, Response &res) {
  9796. res.set_content(req.body, "text/plain");
  9797. });
  9798. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9799. res.set_content(req.body, "text/plain");
  9800. });
  9801. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9802. res.set_content(req.body, "text/plain");
  9803. });
  9804. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9805. auto se = detail::scope_exit([&] {
  9806. svr.stop();
  9807. t.join();
  9808. ASSERT_FALSE(svr.is_running());
  9809. });
  9810. svr.wait_until_ready();
  9811. std::string resp;
  9812. // POST without Content-Length
  9813. ASSERT_TRUE(send_request(5,
  9814. "POST /post HTTP/1.1\r\n"
  9815. "Host: localhost\r\n"
  9816. "Connection: close\r\n"
  9817. "\r\n",
  9818. &resp));
  9819. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9820. // PUT without Content-Length
  9821. resp.clear();
  9822. ASSERT_TRUE(send_request(5,
  9823. "PUT /put HTTP/1.1\r\n"
  9824. "Host: localhost\r\n"
  9825. "Connection: close\r\n"
  9826. "\r\n",
  9827. &resp));
  9828. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9829. // PATCH without Content-Length
  9830. resp.clear();
  9831. ASSERT_TRUE(send_request(5,
  9832. "PATCH /patch HTTP/1.1\r\n"
  9833. "Host: localhost\r\n"
  9834. "Connection: close\r\n"
  9835. "\r\n",
  9836. &resp));
  9837. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9838. // DELETE without Content-Length
  9839. resp.clear();
  9840. ASSERT_TRUE(send_request(5,
  9841. "DELETE /delete HTTP/1.1\r\n"
  9842. "Host: localhost\r\n"
  9843. "Connection: close\r\n"
  9844. "\r\n",
  9845. &resp));
  9846. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9847. }
  9848. //==============================================================================
  9849. // open_stream() Tests
  9850. //==============================================================================
  9851. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9852. std::string result;
  9853. char buf[8192];
  9854. ssize_t n;
  9855. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9856. result.append(buf, static_cast<size_t>(n));
  9857. }
  9858. return result;
  9859. }
  9860. // Mock stream for unit tests
  9861. class MockStream : public Stream {
  9862. public:
  9863. std::string data;
  9864. size_t pos = 0;
  9865. ssize_t error_after = -1; // -1 = no error
  9866. explicit MockStream(const std::string &d, ssize_t err = -1)
  9867. : data(d), error_after(err) {}
  9868. bool is_readable() const override { return true; }
  9869. bool wait_readable() const override { return true; }
  9870. bool wait_writable() const override { return true; }
  9871. ssize_t read(char *ptr, size_t size) override {
  9872. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9873. if (pos >= data.size()) return 0;
  9874. size_t limit =
  9875. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9876. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9877. std::memcpy(ptr, data.data() + pos, to_read);
  9878. pos += to_read;
  9879. return static_cast<ssize_t>(to_read);
  9880. }
  9881. ssize_t write(const char *, size_t) override { return -1; }
  9882. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9883. ip = "127.0.0.1";
  9884. port = 0;
  9885. }
  9886. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9887. ip = "127.0.0.1";
  9888. port = 0;
  9889. }
  9890. socket_t socket() const override { return INVALID_SOCKET; }
  9891. time_t duration() const override { return 0; }
  9892. };
  9893. TEST(StreamHandleTest, Basic) {
  9894. ClientImpl::StreamHandle handle;
  9895. EXPECT_FALSE(handle.is_valid());
  9896. handle.response = detail::make_unique<Response>();
  9897. handle.error = Error::Connection;
  9898. EXPECT_FALSE(handle.is_valid());
  9899. handle.error = Error::Success;
  9900. EXPECT_TRUE(handle.is_valid());
  9901. }
  9902. TEST(BodyReaderTest, Basic) {
  9903. MockStream stream("Hello, World!");
  9904. detail::BodyReader reader;
  9905. reader.stream = &stream;
  9906. reader.content_length = 13;
  9907. char buf[32];
  9908. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9909. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9910. EXPECT_TRUE(reader.eof);
  9911. }
  9912. TEST(BodyReaderTest, NoStream) {
  9913. detail::BodyReader reader;
  9914. char buf[32];
  9915. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9916. EXPECT_EQ(Error::Connection, reader.last_error);
  9917. }
  9918. TEST(BodyReaderTest, Error) {
  9919. MockStream stream("Hello, World!", 5);
  9920. detail::BodyReader reader;
  9921. reader.stream = &stream;
  9922. reader.content_length = 13;
  9923. char buf[32];
  9924. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9925. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9926. EXPECT_EQ(Error::Read, reader.last_error);
  9927. }
  9928. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9929. // Mock-based StreamHandle tests relying on private internals are removed.
  9930. class OpenStreamTest : public ::testing::Test {
  9931. protected:
  9932. void SetUp() override {
  9933. svr_.Get("/hello", [](const Request &, Response &res) {
  9934. res.set_content("Hello World!", "text/plain");
  9935. });
  9936. svr_.Get("/large", [](const Request &, Response &res) {
  9937. res.set_content(std::string(10000, 'X'), "text/plain");
  9938. });
  9939. svr_.Get("/chunked", [](const Request &, Response &res) {
  9940. res.set_chunked_content_provider("text/plain",
  9941. [](size_t offset, DataSink &sink) {
  9942. if (offset < 15) {
  9943. sink.write("chunk", 5);
  9944. return true;
  9945. }
  9946. sink.done();
  9947. return true;
  9948. });
  9949. });
  9950. svr_.Get("/compressible", [](const Request &, Response &res) {
  9951. res.set_chunked_content_provider("text/plain", [](size_t offset,
  9952. DataSink &sink) {
  9953. if (offset < 100 * 1024) {
  9954. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  9955. sink.write(chunk.data(), chunk.size());
  9956. return true;
  9957. }
  9958. sink.done();
  9959. return true;
  9960. });
  9961. });
  9962. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  9963. [](const Request & /*req*/, Response &res) {
  9964. auto i = new int(0);
  9965. res.set_header("Trailer", "Content-Length, X-Allowed");
  9966. res.set_chunked_content_provider(
  9967. "text/plain",
  9968. [i](size_t /*offset*/, DataSink &sink) {
  9969. switch (*i) {
  9970. case 0: sink.os << "123"; break;
  9971. case 1: sink.os << "456"; break;
  9972. case 2: sink.os << "789"; break;
  9973. case 3: {
  9974. sink.done_with_trailer(
  9975. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  9976. } break;
  9977. }
  9978. (*i)++;
  9979. return true;
  9980. },
  9981. [i](bool success) {
  9982. EXPECT_TRUE(success);
  9983. delete i;
  9984. });
  9985. });
  9986. // Echo headers endpoint for header-related tests
  9987. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  9988. std::string body;
  9989. for (const auto &h : req.headers) {
  9990. body.append(h.first);
  9991. body.push_back(':');
  9992. body.append(h.second);
  9993. body.push_back('\n');
  9994. }
  9995. res.set_content(body, "text/plain");
  9996. });
  9997. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  9998. std::string body;
  9999. for (const auto &h : req.headers) {
  10000. body.append(h.first);
  10001. body.push_back(':');
  10002. body.append(h.second);
  10003. body.push_back('\n');
  10004. }
  10005. res.set_content(body, "text/plain");
  10006. });
  10007. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10008. svr_.wait_until_ready();
  10009. }
  10010. void TearDown() override {
  10011. svr_.stop();
  10012. if (thread_.joinable()) thread_.join();
  10013. }
  10014. Server svr_;
  10015. std::thread thread_;
  10016. };
  10017. TEST_F(OpenStreamTest, Basic) {
  10018. Client cli("127.0.0.1", 8787);
  10019. auto handle = cli.open_stream("GET", "/hello");
  10020. EXPECT_TRUE(handle.is_valid());
  10021. EXPECT_EQ("Hello World!", read_all(handle));
  10022. }
  10023. TEST_F(OpenStreamTest, SmallBuffer) {
  10024. Client cli("127.0.0.1", 8787);
  10025. auto handle = cli.open_stream("GET", "/hello");
  10026. std::string result;
  10027. char buf[4];
  10028. ssize_t n;
  10029. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10030. result.append(buf, static_cast<size_t>(n));
  10031. EXPECT_EQ("Hello World!", result);
  10032. }
  10033. TEST_F(OpenStreamTest, DefaultHeaders) {
  10034. Client cli("127.0.0.1", 8787);
  10035. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10036. {
  10037. auto handle = cli.open_stream("GET", "/echo-headers");
  10038. ASSERT_TRUE(handle.is_valid());
  10039. auto body = read_all(handle);
  10040. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10041. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10042. std::string::npos);
  10043. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10044. }
  10045. // open_stream POST with body and no explicit content_type should NOT add
  10046. // text/plain Content-Type (behavior differs from non-streaming path), but
  10047. // should include Content-Length
  10048. {
  10049. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10050. ASSERT_TRUE(handle.is_valid());
  10051. auto body = read_all(handle);
  10052. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10053. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10054. }
  10055. // open_stream POST with explicit Content-Type should preserve it
  10056. {
  10057. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10058. {{"Content-Type", "application/custom"}},
  10059. "{}", "application/custom");
  10060. ASSERT_TRUE(handle.is_valid());
  10061. auto body = read_all(handle);
  10062. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10063. }
  10064. // User-specified User-Agent must not be overwritten for stream API
  10065. {
  10066. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10067. {{"User-Agent", "MyAgent/1.2"}});
  10068. ASSERT_TRUE(handle.is_valid());
  10069. auto body = read_all(handle);
  10070. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10071. }
  10072. }
  10073. TEST_F(OpenStreamTest, Large) {
  10074. Client cli("127.0.0.1", 8787);
  10075. auto handle = cli.open_stream("GET", "/large");
  10076. EXPECT_EQ(10000u, read_all(handle).size());
  10077. }
  10078. TEST_F(OpenStreamTest, ConnectionError) {
  10079. Client cli("127.0.0.1", 9999);
  10080. auto handle = cli.open_stream("GET", "/hello");
  10081. EXPECT_FALSE(handle.is_valid());
  10082. }
  10083. TEST_F(OpenStreamTest, Chunked) {
  10084. Client cli("127.0.0.1", 8787);
  10085. auto handle = cli.open_stream("GET", "/chunked");
  10086. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10087. "Transfer-Encoding") == "chunked");
  10088. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10089. }
  10090. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10091. Client cli("127.0.0.1", 8787);
  10092. auto handle =
  10093. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10094. ASSERT_TRUE(handle.is_valid());
  10095. // Consume body to allow trailers to be received/parsed
  10096. auto body = read_all(handle);
  10097. // Explicitly parse trailers (ensure trailers are available for assertion)
  10098. handle.parse_trailers_if_needed();
  10099. EXPECT_EQ(std::string("123456789"), body);
  10100. // The response should include a Trailer header declaring both names
  10101. ASSERT_TRUE(handle.response);
  10102. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10103. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10104. handle.response->get_header_value("Trailer"));
  10105. // Prohibited trailer must not be present
  10106. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10107. // Allowed trailer should be present
  10108. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10109. EXPECT_EQ(std::string("yes"),
  10110. handle.response->get_trailer_value("X-Allowed"));
  10111. // Verify trailers are NOT present as regular headers
  10112. EXPECT_EQ(std::string(""),
  10113. handle.response->get_header_value("Content-Length"));
  10114. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10115. }
  10116. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10117. TEST_F(OpenStreamTest, Gzip) {
  10118. Client cli("127.0.0.1", 8787);
  10119. auto handle = cli.open_stream("GET", "/compressible", {},
  10120. {{"Accept-Encoding", "gzip"}});
  10121. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10122. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10123. }
  10124. #endif
  10125. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10126. TEST_F(OpenStreamTest, Brotli) {
  10127. Client cli("127.0.0.1", 8787);
  10128. auto handle =
  10129. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10130. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10131. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10132. }
  10133. #endif
  10134. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10135. TEST_F(OpenStreamTest, Zstd) {
  10136. Client cli("127.0.0.1", 8787);
  10137. auto handle = cli.open_stream("GET", "/compressible", {},
  10138. {{"Accept-Encoding", "zstd"}});
  10139. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10140. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10141. }
  10142. #endif
  10143. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10144. class SSLOpenStreamTest : public ::testing::Test {
  10145. protected:
  10146. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10147. void SetUp() override {
  10148. svr_.Get("/hello", [](const Request &, Response &res) {
  10149. res.set_content("Hello SSL World!", "text/plain");
  10150. });
  10151. svr_.Get("/chunked", [](const Request &, Response &res) {
  10152. res.set_chunked_content_provider("text/plain",
  10153. [](size_t offset, DataSink &sink) {
  10154. if (offset < 15) {
  10155. sink.write("chunk", 5);
  10156. return true;
  10157. }
  10158. sink.done();
  10159. return true;
  10160. });
  10161. });
  10162. svr_.Post("/echo", [](const Request &req, Response &res) {
  10163. res.set_content(req.body, req.get_header_value("Content-Type"));
  10164. });
  10165. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10166. std::string body = req.body;
  10167. res.set_chunked_content_provider(
  10168. "text/plain", [body](size_t offset, DataSink &sink) {
  10169. if (offset < body.size()) {
  10170. sink.write(body.data() + offset, body.size() - offset);
  10171. }
  10172. sink.done();
  10173. return true;
  10174. });
  10175. });
  10176. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10177. svr_.wait_until_ready();
  10178. }
  10179. void TearDown() override {
  10180. svr_.stop();
  10181. if (thread_.joinable()) thread_.join();
  10182. }
  10183. SSLServer svr_;
  10184. std::thread thread_;
  10185. };
  10186. TEST_F(SSLOpenStreamTest, Basic) {
  10187. SSLClient cli("127.0.0.1", 8788);
  10188. cli.enable_server_certificate_verification(false);
  10189. auto handle = cli.open_stream("GET", "/hello");
  10190. ASSERT_TRUE(handle.is_valid());
  10191. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10192. }
  10193. TEST_F(SSLOpenStreamTest, Chunked) {
  10194. SSLClient cli("127.0.0.1", 8788);
  10195. cli.enable_server_certificate_verification(false);
  10196. auto handle = cli.open_stream("GET", "/chunked");
  10197. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10198. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10199. "Transfer-Encoding") == "chunked");
  10200. auto body = read_all(handle);
  10201. EXPECT_EQ("chunkchunkchunk", body);
  10202. }
  10203. TEST_F(SSLOpenStreamTest, Post) {
  10204. SSLClient cli("127.0.0.1", 8788);
  10205. cli.enable_server_certificate_verification(false);
  10206. auto handle =
  10207. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10208. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10209. EXPECT_EQ(200, handle.response->status);
  10210. auto body = read_all(handle);
  10211. EXPECT_EQ("Hello SSL POST", body);
  10212. }
  10213. TEST_F(SSLOpenStreamTest, PostChunked) {
  10214. SSLClient cli("127.0.0.1", 8788);
  10215. cli.enable_server_certificate_verification(false);
  10216. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10217. "Chunked SSL Data", "text/plain");
  10218. ASSERT_TRUE(handle.is_valid());
  10219. EXPECT_EQ(200, handle.response->status);
  10220. auto body = read_all(handle);
  10221. EXPECT_EQ("Chunked SSL Data", body);
  10222. }
  10223. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10224. //==============================================================================
  10225. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10226. // results for various scenarios.
  10227. //==============================================================================
  10228. TEST(ParityTest, GetVsOpenStream) {
  10229. Server svr;
  10230. const std::string path = "/parity";
  10231. const std::string content = "Parity test content: hello world";
  10232. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10233. res.set_content(content, "text/plain");
  10234. });
  10235. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. t.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. Client cli(HOST, PORT);
  10243. // Non-stream path
  10244. auto r1 = cli.Get(path);
  10245. ASSERT_TRUE(r1);
  10246. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10247. // Stream path
  10248. auto h = cli.open_stream("GET", path);
  10249. ASSERT_TRUE(h.is_valid());
  10250. EXPECT_EQ(r1->body, read_all(h));
  10251. }
  10252. // Helper to compress data with provided compressor type T
  10253. template <typename Compressor>
  10254. static std::string compress_payload_for_parity(const std::string &in) {
  10255. std::string out;
  10256. Compressor compressor;
  10257. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10258. [&](const char *data, size_t n) {
  10259. out.append(data, n);
  10260. return true;
  10261. });
  10262. EXPECT_TRUE(ok);
  10263. return out;
  10264. }
  10265. // Helper function for compression parity tests
  10266. template <typename Compressor>
  10267. static void test_compression_parity(const std::string &original,
  10268. const std::string &path,
  10269. const std::string &encoding) {
  10270. const std::string compressed =
  10271. compress_payload_for_parity<Compressor>(original);
  10272. Server svr;
  10273. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10274. res.set_content(compressed, "application/octet-stream");
  10275. res.set_header("Content-Encoding", encoding);
  10276. });
  10277. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10278. auto se = detail::scope_exit([&] {
  10279. svr.stop();
  10280. t.join();
  10281. ASSERT_FALSE(svr.is_running());
  10282. });
  10283. svr.wait_until_ready();
  10284. Client cli(HOST, PORT);
  10285. // Non-streaming
  10286. {
  10287. auto res = cli.Get(path);
  10288. ASSERT_TRUE(res);
  10289. EXPECT_EQ(StatusCode::OK_200, res->status);
  10290. EXPECT_EQ(original, res->body);
  10291. }
  10292. // Streaming
  10293. {
  10294. auto h = cli.open_stream("GET", path);
  10295. ASSERT_TRUE(h.is_valid());
  10296. EXPECT_EQ(original, read_all(h));
  10297. }
  10298. }
  10299. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10300. TEST(ParityTest, Gzip) {
  10301. test_compression_parity<detail::gzip_compressor>(
  10302. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10303. }
  10304. #endif
  10305. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10306. TEST(ParityTest, Brotli) {
  10307. test_compression_parity<detail::brotli_compressor>(
  10308. "Hello, brotli parity test payload", "/parity-br", "br");
  10309. }
  10310. #endif
  10311. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10312. TEST(ParityTest, Zstd) {
  10313. test_compression_parity<detail::zstd_compressor>(
  10314. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10315. }
  10316. #endif
  10317. //==============================================================================
  10318. // New Stream API Tests
  10319. //==============================================================================
  10320. inline std::string read_body(httplib::stream::Result &result) {
  10321. std::string body;
  10322. while (result.next()) {
  10323. body.append(result.data(), result.size());
  10324. }
  10325. return body;
  10326. }
  10327. TEST(ClientConnectionTest, Basic) {
  10328. httplib::ClientConnection conn;
  10329. EXPECT_FALSE(conn.is_open());
  10330. conn.sock = 1;
  10331. EXPECT_TRUE(conn.is_open());
  10332. httplib::ClientConnection conn2(std::move(conn));
  10333. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10334. conn2.sock = INVALID_SOCKET;
  10335. }
  10336. // Unified test server for all stream::* tests
  10337. class StreamApiTest : public ::testing::Test {
  10338. protected:
  10339. void SetUp() override {
  10340. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10341. res.set_content("Hello World!", "text/plain");
  10342. });
  10343. svr_.Get("/echo-params",
  10344. [](const httplib::Request &req, httplib::Response &res) {
  10345. std::string r;
  10346. for (const auto &p : req.params) {
  10347. if (!r.empty()) r += "&";
  10348. r += p.first + "=" + p.second;
  10349. }
  10350. res.set_content(r, "text/plain");
  10351. });
  10352. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10353. res.set_content(req.body, req.get_header_value("Content-Type"));
  10354. });
  10355. svr_.Post("/echo-headers",
  10356. [](const httplib::Request &req, httplib::Response &res) {
  10357. std::string r;
  10358. for (const auto &h : req.headers)
  10359. r += h.first + ": " + h.second + "\n";
  10360. res.set_content(r, "text/plain");
  10361. });
  10362. svr_.Post("/echo-params",
  10363. [](const httplib::Request &req, httplib::Response &res) {
  10364. std::string r = "params:";
  10365. for (const auto &p : req.params)
  10366. r += p.first + "=" + p.second + ";";
  10367. res.set_content(r + " body:" + req.body, "text/plain");
  10368. });
  10369. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10370. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10371. });
  10372. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10373. res.set_content("PUT:" + req.body, "text/plain");
  10374. });
  10375. svr_.Patch("/echo",
  10376. [](const httplib::Request &req, httplib::Response &res) {
  10377. res.set_content("PATCH:" + req.body, "text/plain");
  10378. });
  10379. svr_.Delete(
  10380. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10381. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10382. "text/plain");
  10383. });
  10384. svr_.Get("/head-test",
  10385. [](const httplib::Request &, httplib::Response &res) {
  10386. res.set_content("body for HEAD", "text/plain");
  10387. });
  10388. svr_.Options("/options",
  10389. [](const httplib::Request &, httplib::Response &res) {
  10390. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10391. });
  10392. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10393. svr_.wait_until_ready();
  10394. }
  10395. void TearDown() override {
  10396. svr_.stop();
  10397. if (thread_.joinable()) thread_.join();
  10398. }
  10399. httplib::Server svr_;
  10400. std::thread thread_;
  10401. };
  10402. // stream::Get tests
  10403. TEST_F(StreamApiTest, GetBasic) {
  10404. httplib::Client cli(HOST, PORT);
  10405. auto result = httplib::stream::Get(cli, "/hello");
  10406. ASSERT_TRUE(result.is_valid());
  10407. EXPECT_EQ(200, result.status());
  10408. EXPECT_EQ("Hello World!", read_body(result));
  10409. }
  10410. TEST_F(StreamApiTest, GetWithParams) {
  10411. httplib::Client cli(HOST, PORT);
  10412. httplib::Params params{{"foo", "bar"}};
  10413. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10414. ASSERT_TRUE(result.is_valid());
  10415. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10416. }
  10417. TEST_F(StreamApiTest, GetConnectionError) {
  10418. httplib::Client cli(HOST, 9999);
  10419. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10420. }
  10421. TEST_F(StreamApiTest, Get404) {
  10422. httplib::Client cli(HOST, PORT);
  10423. auto result = httplib::stream::Get(cli, "/nonexistent");
  10424. EXPECT_TRUE(result.is_valid());
  10425. EXPECT_EQ(404, result.status());
  10426. }
  10427. // stream::Post tests
  10428. TEST_F(StreamApiTest, PostBasic) {
  10429. httplib::Client cli(HOST, PORT);
  10430. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10431. "application/json");
  10432. ASSERT_TRUE(result.is_valid());
  10433. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10434. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10435. }
  10436. TEST_F(StreamApiTest, PostWithHeaders) {
  10437. httplib::Client cli(HOST, PORT);
  10438. httplib::Headers headers{{"X-Custom", "value"}};
  10439. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10440. "text/plain");
  10441. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10442. }
  10443. TEST_F(StreamApiTest, PostWithParams) {
  10444. httplib::Client cli(HOST, PORT);
  10445. httplib::Params params{{"k", "v"}};
  10446. auto result =
  10447. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10448. auto body = read_body(result);
  10449. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10450. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10451. }
  10452. TEST_F(StreamApiTest, PostLarge) {
  10453. httplib::Client cli(HOST, PORT);
  10454. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10455. size_t total = 0;
  10456. while (result.next()) {
  10457. total += result.size();
  10458. }
  10459. EXPECT_EQ(100u * 1024u, total);
  10460. }
  10461. // stream::Put/Patch tests
  10462. TEST_F(StreamApiTest, PutAndPatch) {
  10463. httplib::Client cli(HOST, PORT);
  10464. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10465. EXPECT_EQ("PUT:test", read_body(put));
  10466. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10467. EXPECT_EQ("PATCH:test", read_body(patch));
  10468. }
  10469. // stream::Delete tests
  10470. TEST_F(StreamApiTest, Delete) {
  10471. httplib::Client cli(HOST, PORT);
  10472. auto del1 = httplib::stream::Delete(cli, "/resource");
  10473. EXPECT_EQ("Deleted", read_body(del1));
  10474. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10475. EXPECT_EQ("Deleted:data", read_body(del2));
  10476. }
  10477. // stream::Head/Options tests
  10478. TEST_F(StreamApiTest, HeadAndOptions) {
  10479. httplib::Client cli(HOST, PORT);
  10480. auto head = httplib::stream::Head(cli, "/head-test");
  10481. EXPECT_TRUE(head.is_valid());
  10482. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10483. auto opts = httplib::stream::Options(cli, "/options");
  10484. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10485. }
  10486. // SSL stream::* tests
  10487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10488. class SSLStreamApiTest : public ::testing::Test {
  10489. protected:
  10490. void SetUp() override {
  10491. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10492. res.set_content("Hello SSL!", "text/plain");
  10493. });
  10494. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10495. res.set_content(req.body, "text/plain");
  10496. });
  10497. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10498. svr_.wait_until_ready();
  10499. }
  10500. void TearDown() override {
  10501. svr_.stop();
  10502. if (thread_.joinable()) thread_.join();
  10503. }
  10504. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10505. std::thread thread_;
  10506. };
  10507. TEST_F(SSLStreamApiTest, GetAndPost) {
  10508. httplib::SSLClient cli("127.0.0.1", 8803);
  10509. cli.enable_server_certificate_verification(false);
  10510. auto get = httplib::stream::Get(cli, "/hello");
  10511. EXPECT_EQ("Hello SSL!", read_body(get));
  10512. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10513. EXPECT_EQ("test", read_body(post));
  10514. }
  10515. #endif
  10516. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10517. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10518. // BodyReader
  10519. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10520. // Test that read timeout during streaming is detected
  10521. // Use a large content-length response where server delays mid-stream
  10522. Server svr;
  10523. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10524. // Send a large response with delay in the middle
  10525. res.set_content_provider(
  10526. 1000, // content_length
  10527. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10528. if (offset < 100) {
  10529. // Send first 100 bytes immediately
  10530. std::string data(100, 'A');
  10531. sink.write(data.c_str(), data.size());
  10532. return true;
  10533. }
  10534. // Then delay longer than client timeout
  10535. std::this_thread::sleep_for(std::chrono::seconds(3));
  10536. std::string data(900, 'B');
  10537. sink.write(data.c_str(), data.size());
  10538. return true;
  10539. });
  10540. });
  10541. auto port = 8091;
  10542. std::thread t([&]() { svr.listen("localhost", port); });
  10543. svr.wait_until_ready();
  10544. Client cli("localhost", port);
  10545. cli.set_read_timeout(1, 0); // 1 second timeout
  10546. auto handle = cli.open_stream("GET", "/slow-stream");
  10547. ASSERT_TRUE(handle.is_valid());
  10548. char buf[256];
  10549. ssize_t total = 0;
  10550. ssize_t n;
  10551. bool got_error = false;
  10552. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10553. total += n;
  10554. }
  10555. if (n < 0) {
  10556. got_error = true;
  10557. // Should be timeout or read error
  10558. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10559. handle.get_read_error() == Error::Read)
  10560. << "Actual error: " << to_string(handle.get_read_error());
  10561. }
  10562. // Either we got an error, or we got less data than expected
  10563. EXPECT_TRUE(got_error || total < 1000)
  10564. << "Expected timeout but got all " << total << " bytes";
  10565. svr.stop();
  10566. t.join();
  10567. }
  10568. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10569. // Test connection closed detection via BodyReader
  10570. Server svr;
  10571. std::atomic<bool> close_now{false};
  10572. svr.Get("/will-close", [&](const Request &, Response &res) {
  10573. res.set_content_provider(
  10574. 10000, // Large content_length that we won't fully send
  10575. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10576. if (offset < 100) {
  10577. std::string data(100, 'X');
  10578. sink.write(data.c_str(), data.size());
  10579. return true;
  10580. }
  10581. // Wait for signal then abort
  10582. while (!close_now) {
  10583. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10584. }
  10585. return false; // Abort - server will close connection
  10586. });
  10587. });
  10588. auto port = 8092;
  10589. std::thread t([&]() { svr.listen("localhost", port); });
  10590. svr.wait_until_ready();
  10591. Client cli("localhost", port);
  10592. auto handle = cli.open_stream("GET", "/will-close");
  10593. ASSERT_TRUE(handle.is_valid());
  10594. char buf[256];
  10595. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10596. EXPECT_GT(n, 0) << "First read should succeed";
  10597. // Signal server to close
  10598. close_now = true;
  10599. // Keep reading until error or EOF
  10600. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10601. // Keep reading
  10602. }
  10603. // Should get an error since content_length wasn't satisfied
  10604. if (n < 0) {
  10605. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10606. handle.get_read_error() == Error::Read)
  10607. << "Actual error: " << to_string(handle.get_read_error());
  10608. }
  10609. svr.stop();
  10610. t.join();
  10611. }
  10612. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10613. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10614. // Test that read timeout during SSL streaming is detected
  10615. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10616. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10617. res.set_content_provider(
  10618. 1000, "text/plain",
  10619. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10620. if (offset < 100) {
  10621. std::string data(100, 'A');
  10622. sink.write(data.c_str(), data.size());
  10623. return true;
  10624. }
  10625. std::this_thread::sleep_for(std::chrono::seconds(3));
  10626. std::string data(900, 'B');
  10627. sink.write(data.c_str(), data.size());
  10628. return true;
  10629. });
  10630. });
  10631. auto port = 8093;
  10632. std::thread t([&]() { svr.listen("localhost", port); });
  10633. svr.wait_until_ready();
  10634. SSLClient cli("localhost", port);
  10635. cli.enable_server_certificate_verification(false);
  10636. cli.set_read_timeout(1, 0); // 1 second timeout
  10637. auto handle = cli.open_stream("GET", "/slow-stream");
  10638. ASSERT_TRUE(handle.is_valid());
  10639. char buf[256];
  10640. ssize_t total = 0;
  10641. ssize_t n;
  10642. bool got_error = false;
  10643. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10644. total += n;
  10645. }
  10646. if (n < 0) {
  10647. got_error = true;
  10648. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10649. handle.get_read_error() == Error::Read)
  10650. << "Actual error: " << to_string(handle.get_read_error());
  10651. }
  10652. EXPECT_TRUE(got_error || total < 1000)
  10653. << "Expected timeout but got all " << total << " bytes";
  10654. svr.stop();
  10655. t.join();
  10656. }
  10657. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10658. // Test SSL connection closed detection
  10659. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10660. std::atomic<bool> close_now{false};
  10661. svr.Get("/will-close", [&](const Request &, Response &res) {
  10662. res.set_content_provider(
  10663. 10000, "text/plain",
  10664. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10665. if (offset < 100) {
  10666. std::string data(100, 'X');
  10667. sink.write(data.c_str(), data.size());
  10668. return true;
  10669. }
  10670. while (!close_now) {
  10671. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10672. }
  10673. return false;
  10674. });
  10675. });
  10676. auto port = 8094;
  10677. std::thread t([&]() { svr.listen("localhost", port); });
  10678. svr.wait_until_ready();
  10679. SSLClient cli("localhost", port);
  10680. cli.enable_server_certificate_verification(false);
  10681. auto handle = cli.open_stream("GET", "/will-close");
  10682. ASSERT_TRUE(handle.is_valid());
  10683. char buf[256];
  10684. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10685. EXPECT_GT(n, 0);
  10686. // Signal server to close
  10687. close_now = true;
  10688. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10689. // Keep reading
  10690. }
  10691. if (n < 0) {
  10692. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10693. handle.get_read_error() == Error::Read)
  10694. << "Actual error: " << to_string(handle.get_read_error());
  10695. }
  10696. svr.stop();
  10697. t.join();
  10698. }
  10699. #endif
  10700. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10701. using namespace httplib;
  10702. // Create a test file
  10703. const char *fname = "etag_testfile.txt";
  10704. const char *content = "etag-content";
  10705. {
  10706. std::ofstream ofs(fname);
  10707. ofs << content;
  10708. ASSERT_TRUE(ofs.good());
  10709. }
  10710. Server svr;
  10711. svr.set_mount_point("/static", ".");
  10712. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10713. svr.wait_until_ready();
  10714. Client cli(HOST, PORT);
  10715. // First request: should get 200 with ETag header
  10716. auto res1 = cli.Get("/static/etag_testfile.txt");
  10717. ASSERT_TRUE(res1);
  10718. ASSERT_EQ(200, res1->status);
  10719. ASSERT_TRUE(res1->has_header("ETag"));
  10720. std::string etag = res1->get_header_value("ETag");
  10721. EXPECT_FALSE(etag.empty());
  10722. // Verify ETag format: W/"hex-hex"
  10723. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10724. EXPECT_EQ('W', etag[0]);
  10725. EXPECT_EQ('/', etag[1]);
  10726. EXPECT_EQ('"', etag[2]);
  10727. EXPECT_EQ('"', etag.back());
  10728. // Exact match: expect 304 Not Modified
  10729. Headers h2 = {{"If-None-Match", etag}};
  10730. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10731. ASSERT_TRUE(res2);
  10732. EXPECT_EQ(304, res2->status);
  10733. // Wildcard match: expect 304 Not Modified
  10734. Headers h3 = {{"If-None-Match", "*"}};
  10735. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10736. ASSERT_TRUE(res3);
  10737. EXPECT_EQ(304, res3->status);
  10738. // Non-matching ETag: expect 200
  10739. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10740. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10741. ASSERT_TRUE(res4);
  10742. EXPECT_EQ(200, res4->status);
  10743. // Multiple ETags with one matching: expect 304
  10744. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10745. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10746. ASSERT_TRUE(res5);
  10747. EXPECT_EQ(304, res5->status);
  10748. svr.stop();
  10749. t.join();
  10750. std::remove(fname);
  10751. }
  10752. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10753. using namespace httplib;
  10754. Server svr;
  10755. svr.set_mount_point("/static", ".");
  10756. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10757. svr.wait_until_ready();
  10758. Client cli(HOST, PORT);
  10759. // Send If-None-Match: * to a non-existent file
  10760. Headers h = {{"If-None-Match", "*"}};
  10761. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10762. ASSERT_TRUE(res);
  10763. EXPECT_EQ(404, res->status);
  10764. svr.stop();
  10765. t.join();
  10766. }
  10767. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10768. using namespace httplib;
  10769. // Create a test file
  10770. const char *fname = "ims_testfile.txt";
  10771. const char *content = "if-modified-since-test";
  10772. {
  10773. std::ofstream ofs(fname);
  10774. ofs << content;
  10775. ASSERT_TRUE(ofs.good());
  10776. }
  10777. Server svr;
  10778. svr.set_mount_point("/static", ".");
  10779. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10780. svr.wait_until_ready();
  10781. Client cli(HOST, PORT);
  10782. // First request: should get 200 with Last-Modified header
  10783. auto res1 = cli.Get("/static/ims_testfile.txt");
  10784. ASSERT_TRUE(res1);
  10785. ASSERT_EQ(200, res1->status);
  10786. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10787. std::string last_modified = res1->get_header_value("Last-Modified");
  10788. EXPECT_FALSE(last_modified.empty());
  10789. // If-Modified-Since with same time: expect 304
  10790. Headers h2 = {{"If-Modified-Since", last_modified}};
  10791. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10792. ASSERT_TRUE(res2);
  10793. EXPECT_EQ(304, res2->status);
  10794. // If-Modified-Since with future time: expect 304
  10795. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10796. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10797. ASSERT_TRUE(res3);
  10798. EXPECT_EQ(304, res3->status);
  10799. // If-Modified-Since with past time: expect 200
  10800. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10801. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10802. ASSERT_TRUE(res4);
  10803. EXPECT_EQ(200, res4->status);
  10804. // If-None-Match takes precedence over If-Modified-Since
  10805. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10806. ASSERT_TRUE(res1->has_header("ETag"));
  10807. std::string etag = res1->get_header_value("ETag");
  10808. Headers h5 = {{"If-None-Match", etag},
  10809. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10810. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10811. ASSERT_TRUE(res5);
  10812. EXPECT_EQ(304, res5->status);
  10813. svr.stop();
  10814. t.join();
  10815. std::remove(fname);
  10816. }
  10817. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10818. using namespace httplib;
  10819. Server svr;
  10820. // Endpoint that returns compressible content
  10821. svr.Get("/compressible", [](const Request &, Response &res) {
  10822. // Return a large enough body to trigger compression
  10823. std::string body(1000, 'a');
  10824. res.set_content(body, "text/plain");
  10825. });
  10826. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10827. svr.wait_until_ready();
  10828. Client cli(HOST, PORT);
  10829. // Request with gzip support: should get Vary header when compressed
  10830. cli.set_compress(true);
  10831. auto res1 = cli.Get("/compressible");
  10832. ASSERT_TRUE(res1);
  10833. EXPECT_EQ(200, res1->status);
  10834. // If Content-Encoding is set, Vary should also be set
  10835. if (res1->has_header("Content-Encoding")) {
  10836. EXPECT_TRUE(res1->has_header("Vary"));
  10837. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10838. }
  10839. // Request without Accept-Encoding header: should not have compression
  10840. Headers h_no_compress;
  10841. auto res2 = cli.Get("/compressible", h_no_compress);
  10842. ASSERT_TRUE(res2);
  10843. EXPECT_EQ(200, res2->status);
  10844. // Verify Vary header is present when compression is applied
  10845. // (the exact behavior depends on server configuration)
  10846. svr.stop();
  10847. t.join();
  10848. }
  10849. TEST(ETagTest, IfRangeWithETag) {
  10850. using namespace httplib;
  10851. // Create a test file with known content
  10852. const char *fname = "if_range_testfile.txt";
  10853. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10854. {
  10855. std::ofstream ofs(fname);
  10856. ofs << content;
  10857. ASSERT_TRUE(ofs.good());
  10858. }
  10859. Server svr;
  10860. svr.set_mount_point("/static", ".");
  10861. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10862. svr.wait_until_ready();
  10863. Client cli(HOST, PORT);
  10864. // First request: get ETag
  10865. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10866. ASSERT_TRUE(res1);
  10867. ASSERT_EQ(200, res1->status);
  10868. ASSERT_TRUE(res1->has_header("ETag"));
  10869. std::string etag = res1->get_header_value("ETag");
  10870. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10871. // Since our server generates weak ETags (W/"..."), If-Range with our
  10872. // ETag should NOT result in partial content - it should return full content.
  10873. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10874. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10875. ASSERT_TRUE(res2);
  10876. // Weak ETag in If-Range -> full content (200), not partial (206)
  10877. EXPECT_EQ(200, res2->status);
  10878. EXPECT_EQ(content, res2->body);
  10879. EXPECT_FALSE(res2->has_header("Content-Range"));
  10880. // Range request with non-matching If-Range (ETag): should get 200 (full
  10881. // content)
  10882. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10883. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10884. ASSERT_TRUE(res3);
  10885. EXPECT_EQ(200, res3->status);
  10886. EXPECT_EQ(content, res3->body);
  10887. EXPECT_FALSE(res3->has_header("Content-Range"));
  10888. // Range request with strong ETag (hypothetical - our server doesn't generate
  10889. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10890. // should return full content)
  10891. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10892. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10893. ASSERT_TRUE(res4);
  10894. EXPECT_EQ(200, res4->status);
  10895. EXPECT_EQ(content, res4->body);
  10896. EXPECT_FALSE(res4->has_header("Content-Range"));
  10897. svr.stop();
  10898. t.join();
  10899. std::remove(fname);
  10900. }
  10901. TEST(ETagTest, IfRangeWithDate) {
  10902. using namespace httplib;
  10903. // Create a test file
  10904. const char *fname = "if_range_date_testfile.txt";
  10905. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10906. {
  10907. std::ofstream ofs(fname);
  10908. ofs << content;
  10909. ASSERT_TRUE(ofs.good());
  10910. }
  10911. Server svr;
  10912. svr.set_mount_point("/static", ".");
  10913. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10914. svr.wait_until_ready();
  10915. Client cli(HOST, PORT);
  10916. // First request: get Last-Modified
  10917. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10918. ASSERT_TRUE(res1);
  10919. ASSERT_EQ(200, res1->status);
  10920. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10921. std::string last_modified = res1->get_header_value("Last-Modified");
  10922. // Range request with matching If-Range (date): should get 206
  10923. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10924. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10925. ASSERT_TRUE(res2);
  10926. EXPECT_EQ(206, res2->status);
  10927. EXPECT_EQ("FGHIJ", res2->body);
  10928. // Range request with old If-Range date: should get 200 (full content)
  10929. Headers h3 = {{"Range", "bytes=5-9"},
  10930. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10931. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10932. ASSERT_TRUE(res3);
  10933. EXPECT_EQ(200, res3->status);
  10934. EXPECT_EQ(content, res3->body);
  10935. // Range request with future If-Range date: should get 206
  10936. Headers h4 = {{"Range", "bytes=0-4"},
  10937. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10938. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10939. ASSERT_TRUE(res4);
  10940. EXPECT_EQ(206, res4->status);
  10941. EXPECT_EQ("ABCDE", res4->body);
  10942. svr.stop();
  10943. t.join();
  10944. std::remove(fname);
  10945. }
  10946. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10947. using namespace httplib;
  10948. const char *fname = "etag_malformed.txt";
  10949. const char *content = "malformed-etag";
  10950. {
  10951. std::ofstream ofs(fname);
  10952. ofs << content;
  10953. ASSERT_TRUE(ofs.good());
  10954. }
  10955. Server svr;
  10956. svr.set_mount_point("/static", ".");
  10957. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10958. svr.wait_until_ready();
  10959. Client cli(HOST, PORT);
  10960. // baseline: should get 200 and an ETag
  10961. auto res1 = cli.Get("/static/etag_malformed.txt");
  10962. ASSERT_TRUE(res1);
  10963. ASSERT_EQ(200, res1->status);
  10964. ASSERT_TRUE(res1->has_header("ETag"));
  10965. // Malformed ETag value (missing quotes) should be treated as non-matching
  10966. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  10967. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  10968. ASSERT_TRUE(res_bad);
  10969. EXPECT_EQ(200, res_bad->status);
  10970. // Whitespace-only header value should be considered invalid / non-matching
  10971. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  10972. "Host: localhost\r\n"
  10973. "If-None-Match: \r\n"
  10974. "Connection: close\r\n"
  10975. "\r\n";
  10976. std::string out;
  10977. ASSERT_TRUE(send_request(5, raw_req, &out));
  10978. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10979. svr.stop();
  10980. t.join();
  10981. std::remove(fname);
  10982. }
  10983. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  10984. using namespace httplib;
  10985. const char *fname = "ims_invalid_format.txt";
  10986. const char *content = "ims-bad-format";
  10987. {
  10988. std::ofstream ofs(fname);
  10989. ofs << content;
  10990. ASSERT_TRUE(ofs.good());
  10991. }
  10992. Server svr;
  10993. svr.set_mount_point("/static", ".");
  10994. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10995. svr.wait_until_ready();
  10996. Client cli(HOST, PORT);
  10997. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  10998. ASSERT_TRUE(res1);
  10999. ASSERT_EQ(200, res1->status);
  11000. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11001. // If-Modified-Since with invalid format should not result in 304
  11002. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11003. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11004. ASSERT_TRUE(res_bad);
  11005. EXPECT_EQ(200, res_bad->status);
  11006. // If-Range with invalid date format should be treated as mismatch -> full
  11007. // content (200)
  11008. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11009. {"If-Range", "invalid-date"}};
  11010. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11011. ASSERT_TRUE(res_ifrange);
  11012. EXPECT_EQ(200, res_ifrange->status);
  11013. svr.stop();
  11014. t.join();
  11015. std::remove(fname);
  11016. }
  11017. TEST(ETagTest, IfRangeWithMalformedETag) {
  11018. using namespace httplib;
  11019. const char *fname = "ifrange_malformed.txt";
  11020. const std::string content = "0123456789";
  11021. {
  11022. std::ofstream ofs(fname);
  11023. ofs << content;
  11024. ASSERT_TRUE(ofs.good());
  11025. }
  11026. Server svr;
  11027. svr.set_mount_point("/static", ".");
  11028. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11029. svr.wait_until_ready();
  11030. Client cli(HOST, PORT);
  11031. // First request: get ETag
  11032. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11033. ASSERT_TRUE(res1);
  11034. ASSERT_EQ(200, res1->status);
  11035. ASSERT_TRUE(res1->has_header("ETag"));
  11036. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11037. // full content (200)
  11038. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11039. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11040. ASSERT_TRUE(res2);
  11041. EXPECT_EQ(200, res2->status);
  11042. EXPECT_EQ(content, res2->body);
  11043. svr.stop();
  11044. t.join();
  11045. std::remove(fname);
  11046. }
  11047. TEST(ETagTest, ExtremeLargeDateValues) {
  11048. using namespace httplib;
  11049. const char *fname = "ims_extreme_date.txt";
  11050. const char *content = "ims-extreme-date";
  11051. {
  11052. std::ofstream ofs(fname);
  11053. ofs << content;
  11054. ASSERT_TRUE(ofs.good());
  11055. }
  11056. Server svr;
  11057. svr.set_mount_point("/static", ".");
  11058. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11059. svr.wait_until_ready();
  11060. Client cli(HOST, PORT);
  11061. auto res1 = cli.Get(std::string("/static/") + fname);
  11062. ASSERT_TRUE(res1);
  11063. ASSERT_EQ(200, res1->status);
  11064. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11065. // Extremely large year that may overflow date parsing routines.
  11066. Headers h_large_date = {
  11067. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11068. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11069. ASSERT_TRUE(res_bad);
  11070. // Expect server to treat this as invalid/mismatch and return full content
  11071. EXPECT_EQ(200, res_bad->status);
  11072. // If-Range with extremely large date should be treated as mismatch -> full
  11073. // content (200)
  11074. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11075. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11076. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11077. ASSERT_TRUE(res_ifrange);
  11078. EXPECT_EQ(200, res_ifrange->status);
  11079. svr.stop();
  11080. t.join();
  11081. std::remove(fname);
  11082. }
  11083. TEST(ETagTest, NegativeFileModificationTime) {
  11084. using namespace httplib;
  11085. const char *fname = "ims_negative_mtime.txt";
  11086. const std::string content = "negative-mtime";
  11087. {
  11088. std::ofstream ofs(fname);
  11089. ofs << content;
  11090. ASSERT_TRUE(ofs.good());
  11091. }
  11092. // Try to set file mtime to a negative value. This may fail on some
  11093. // platforms/filesystems; if it fails, the test will still verify server
  11094. // behaves safely by performing a regular conditional request.
  11095. #if defined(__APPLE__) || defined(__linux__)
  11096. bool set_negative = false;
  11097. do {
  11098. struct timeval times[2];
  11099. // access time: now
  11100. times[0].tv_sec = time(nullptr);
  11101. times[0].tv_usec = 0;
  11102. // modification time: negative (e.g., -1)
  11103. times[1].tv_sec = -1;
  11104. times[1].tv_usec = 0;
  11105. if (utimes(fname, times) == 0) { set_negative = true; }
  11106. } while (0);
  11107. #else
  11108. bool set_negative = false;
  11109. #endif
  11110. Server svr;
  11111. svr.set_mount_point("/static", ".");
  11112. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11113. svr.wait_until_ready();
  11114. Client cli(HOST, PORT);
  11115. auto res1 = cli.Get(std::string("/static/") + fname);
  11116. ASSERT_TRUE(res1);
  11117. ASSERT_EQ(200, res1->status);
  11118. bool has_last_modified = res1->has_header("Last-Modified");
  11119. std::string last_modified;
  11120. if (has_last_modified) {
  11121. last_modified = res1->get_header_value("Last-Modified");
  11122. }
  11123. if (set_negative) {
  11124. // If we successfully set a negative mtime, ensure server returns a
  11125. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11126. // with an old date and ensure server handles it without crash.
  11127. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11128. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11129. ASSERT_TRUE(res2);
  11130. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11131. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11132. } else {
  11133. // Could not set negative mtime on this platform; fall back to verifying
  11134. // that normal invalid/malformed dates are treated safely (non-304).
  11135. Headers h_bad_date = {
  11136. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11137. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11138. ASSERT_TRUE(res_bad);
  11139. EXPECT_EQ(200, res_bad->status);
  11140. }
  11141. svr.stop();
  11142. t.join();
  11143. std::remove(fname);
  11144. }
  11145. //==============================================================================
  11146. // SSE Parsing Tests
  11147. //==============================================================================
  11148. class SSEParsingTest : public ::testing::Test {
  11149. protected:
  11150. // Test helper that mimics SSE parsing behavior
  11151. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11152. int &retry_ms) {
  11153. // Blank line signals end of event
  11154. if (line.empty() || line == "\r") { return true; }
  11155. // Lines starting with ':' are comments (ignored)
  11156. if (!line.empty() && line[0] == ':') { return false; }
  11157. // Find the colon separator
  11158. auto colon_pos = line.find(':');
  11159. if (colon_pos == std::string::npos) {
  11160. // Line with no colon is treated as field name with empty value
  11161. return false;
  11162. }
  11163. std::string field = line.substr(0, colon_pos);
  11164. std::string value;
  11165. // Value starts after colon, skip optional single space
  11166. if (colon_pos + 1 < line.size()) {
  11167. size_t value_start = colon_pos + 1;
  11168. if (line[value_start] == ' ') { value_start++; }
  11169. value = line.substr(value_start);
  11170. // Remove trailing \r if present
  11171. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11172. }
  11173. // Handle known fields
  11174. if (field == "event") {
  11175. msg.event = value;
  11176. } else if (field == "data") {
  11177. // Multiple data lines are concatenated with newlines
  11178. if (!msg.data.empty()) { msg.data += "\n"; }
  11179. msg.data += value;
  11180. } else if (field == "id") {
  11181. // Empty id is valid (clears the last event ID)
  11182. msg.id = value;
  11183. } else if (field == "retry") {
  11184. // Parse retry interval in milliseconds
  11185. try {
  11186. retry_ms = std::stoi(value);
  11187. } catch (...) {
  11188. // Invalid retry value, ignore
  11189. }
  11190. }
  11191. // Unknown fields are ignored per SSE spec
  11192. return false;
  11193. }
  11194. };
  11195. // Test: Single-line data
  11196. TEST_F(SSEParsingTest, SingleLineData) {
  11197. sse::SSEMessage msg;
  11198. int retry_ms = 3000;
  11199. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11200. EXPECT_EQ(msg.data, "hello");
  11201. EXPECT_EQ(msg.event, "message");
  11202. // Blank line ends event
  11203. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11204. }
  11205. // Test: Multi-line data
  11206. TEST_F(SSEParsingTest, MultiLineData) {
  11207. sse::SSEMessage msg;
  11208. int retry_ms = 3000;
  11209. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11210. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11211. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11212. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11213. }
  11214. // Test: Custom event types
  11215. TEST_F(SSEParsingTest, CustomEventType) {
  11216. sse::SSEMessage msg;
  11217. int retry_ms = 3000;
  11218. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11219. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11220. EXPECT_EQ(msg.event, "update");
  11221. EXPECT_EQ(msg.data, "payload");
  11222. }
  11223. // Test: Event ID handling
  11224. TEST_F(SSEParsingTest, EventIdHandling) {
  11225. sse::SSEMessage msg;
  11226. int retry_ms = 3000;
  11227. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11228. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11229. EXPECT_EQ(msg.id, "12345");
  11230. }
  11231. // Test: Empty event ID (clears last event ID)
  11232. TEST_F(SSEParsingTest, EmptyEventId) {
  11233. sse::SSEMessage msg;
  11234. msg.id = "previous";
  11235. int retry_ms = 3000;
  11236. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11237. EXPECT_EQ(msg.id, "");
  11238. }
  11239. // Test: Retry field parsing
  11240. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11241. sse::SSEMessage msg;
  11242. int retry_ms = 3000;
  11243. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11244. EXPECT_EQ(retry_ms, 5000);
  11245. }
  11246. // Test: Invalid retry value
  11247. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11248. sse::SSEMessage msg;
  11249. int retry_ms = 3000;
  11250. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11251. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11252. }
  11253. // Test: Comments (lines starting with :)
  11254. TEST_F(SSEParsingTest, CommentsIgnored) {
  11255. sse::SSEMessage msg;
  11256. int retry_ms = 3000;
  11257. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11258. EXPECT_EQ(msg.data, "");
  11259. EXPECT_EQ(msg.event, "message");
  11260. }
  11261. // Test: Colon in value
  11262. TEST_F(SSEParsingTest, ColonInValue) {
  11263. sse::SSEMessage msg;
  11264. int retry_ms = 3000;
  11265. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11266. EXPECT_EQ(msg.data, "hello:world:test");
  11267. }
  11268. // Test: Line with no colon (field name only)
  11269. TEST_F(SSEParsingTest, FieldNameOnly) {
  11270. sse::SSEMessage msg;
  11271. int retry_ms = 3000;
  11272. // According to SSE spec, this is treated as field name with empty value
  11273. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11274. // Since we don't recognize "data" without colon, data should be empty
  11275. EXPECT_EQ(msg.data, "");
  11276. }
  11277. // Test: Trailing \r handling
  11278. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11279. sse::SSEMessage msg;
  11280. int retry_ms = 3000;
  11281. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11282. EXPECT_EQ(msg.data, "hello");
  11283. }
  11284. // Test: Unknown fields ignored
  11285. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11286. sse::SSEMessage msg;
  11287. int retry_ms = 3000;
  11288. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11289. EXPECT_EQ(msg.data, "");
  11290. EXPECT_EQ(msg.event, "message");
  11291. }
  11292. // Test: Space after colon is optional
  11293. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11294. sse::SSEMessage msg1, msg2;
  11295. int retry_ms = 3000;
  11296. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11297. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11298. EXPECT_EQ(msg1.data, "hello");
  11299. EXPECT_EQ(msg2.data, "hello");
  11300. }
  11301. // Test: SSEMessage clear
  11302. TEST_F(SSEParsingTest, MessageClear) {
  11303. sse::SSEMessage msg;
  11304. msg.event = "custom";
  11305. msg.data = "some data";
  11306. msg.id = "123";
  11307. msg.clear();
  11308. EXPECT_EQ(msg.event, "message");
  11309. EXPECT_EQ(msg.data, "");
  11310. EXPECT_EQ(msg.id, "");
  11311. }
  11312. // Test: Complete event parsing
  11313. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11314. sse::SSEMessage msg;
  11315. int retry_ms = 3000;
  11316. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11317. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11318. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11319. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11320. // Blank line ends event
  11321. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11322. EXPECT_EQ(msg.event, "notification");
  11323. EXPECT_EQ(msg.id, "evt-42");
  11324. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11325. EXPECT_EQ(retry_ms, 1000);
  11326. }
  11327. //==============================================================================
  11328. // Integration Tests with Server
  11329. //==============================================================================
  11330. class SSEIntegrationTest : public ::testing::Test {
  11331. protected:
  11332. void SetUp() override {
  11333. stop_server_.store(false);
  11334. events_.clear();
  11335. server_ = httplib::detail::make_unique<Server>();
  11336. setup_server();
  11337. start_server();
  11338. }
  11339. void TearDown() override {
  11340. stop_server_.store(true);
  11341. event_cv_.notify_all();
  11342. server_->stop();
  11343. if (server_thread_.joinable()) { server_thread_.join(); }
  11344. }
  11345. void setup_server() {
  11346. // Simple SSE endpoint
  11347. server_->Get("/events", [this](const Request &req, Response &res) {
  11348. auto last_id = req.get_header_value("Last-Event-ID");
  11349. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11350. res.set_chunked_content_provider(
  11351. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11352. std::unique_lock<std::mutex> lock(event_mutex_);
  11353. if (event_cv_.wait_for(
  11354. lock, std::chrono::milliseconds(200), [this] {
  11355. return !events_.empty() || stop_server_.load();
  11356. })) {
  11357. if (stop_server_.load()) { return false; }
  11358. if (!events_.empty()) {
  11359. std::string event = events_.front();
  11360. events_.erase(events_.begin());
  11361. sink.write(event.data(), event.size());
  11362. return true;
  11363. }
  11364. }
  11365. return !stop_server_.load();
  11366. });
  11367. });
  11368. // Endpoint that returns error
  11369. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11370. res.status = 500;
  11371. res.set_content("Internal Server Error", "text/plain");
  11372. });
  11373. // Endpoint for custom event types
  11374. server_->Get("/custom-events", [](const Request &, Response &res) {
  11375. res.set_chunked_content_provider(
  11376. "text/event-stream", [](size_t offset, DataSink &sink) {
  11377. if (offset == 0) {
  11378. std::string event = "event: update\ndata: updated\n\n"
  11379. "event: delete\ndata: deleted\n\n";
  11380. sink.write(event.data(), event.size());
  11381. }
  11382. return false; // End stream after sending
  11383. });
  11384. });
  11385. }
  11386. void start_server() {
  11387. port_ = server_->bind_to_any_port(HOST);
  11388. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11389. // Wait for server to start
  11390. while (!server_->is_running()) {
  11391. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11392. }
  11393. }
  11394. int get_port() const { return port_; }
  11395. void send_event(const std::string &event) {
  11396. std::lock_guard<std::mutex> lock(event_mutex_);
  11397. events_.push_back(event);
  11398. event_cv_.notify_all();
  11399. }
  11400. std::unique_ptr<Server> server_;
  11401. std::thread server_thread_;
  11402. std::mutex event_mutex_;
  11403. std::condition_variable event_cv_;
  11404. std::vector<std::string> events_;
  11405. std::atomic<bool> stop_server_{false};
  11406. std::string last_received_event_id_;
  11407. int port_ = 0;
  11408. };
  11409. // Test: Successful connection and on_open callback
  11410. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11411. // Add a simple endpoint that sends one event and closes
  11412. server_->Get("/simple-event", [](const Request &, Response &res) {
  11413. res.set_chunked_content_provider(
  11414. "text/event-stream", [](size_t offset, DataSink &sink) {
  11415. if (offset == 0) {
  11416. std::string event = "data: hello\n\n";
  11417. sink.write(event.data(), event.size());
  11418. }
  11419. return false; // Close stream after sending
  11420. });
  11421. });
  11422. Client client("localhost", get_port());
  11423. sse::SSEClient sse(client, "/simple-event");
  11424. std::atomic<bool> open_called{false};
  11425. std::atomic<bool> message_received{false};
  11426. sse.on_open([&open_called]() { open_called.store(true); });
  11427. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11428. if (msg.data == "hello") { message_received.store(true); }
  11429. });
  11430. sse.set_reconnect_interval(100);
  11431. sse.set_max_reconnect_attempts(1);
  11432. // Start async
  11433. sse.start_async();
  11434. // Wait for message to be processed
  11435. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11436. sse.stop();
  11437. EXPECT_TRUE(open_called.load());
  11438. EXPECT_TRUE(message_received.load());
  11439. }
  11440. // Test: on_message callback
  11441. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11442. // Endpoint that sends multiple events then closes
  11443. server_->Get("/multi-event", [](const Request &, Response &res) {
  11444. res.set_chunked_content_provider(
  11445. "text/event-stream", [](size_t offset, DataSink &sink) {
  11446. if (offset == 0) {
  11447. std::string events = "data: message1\n\ndata: message2\n\n";
  11448. sink.write(events.data(), events.size());
  11449. }
  11450. return false;
  11451. });
  11452. });
  11453. Client client("localhost", get_port());
  11454. sse::SSEClient sse(client, "/multi-event");
  11455. std::vector<std::string> received_messages;
  11456. std::mutex messages_mutex;
  11457. sse.on_message([&](const sse::SSEMessage &msg) {
  11458. std::lock_guard<std::mutex> lock(messages_mutex);
  11459. received_messages.push_back(msg.data);
  11460. });
  11461. sse.set_reconnect_interval(100);
  11462. sse.set_max_reconnect_attempts(1);
  11463. sse.start_async();
  11464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11465. sse.stop();
  11466. std::lock_guard<std::mutex> lock(messages_mutex);
  11467. EXPECT_GE(received_messages.size(), 2u);
  11468. if (received_messages.size() >= 2) {
  11469. EXPECT_EQ(received_messages[0], "message1");
  11470. EXPECT_EQ(received_messages[1], "message2");
  11471. }
  11472. }
  11473. // Test: on_event for specific types
  11474. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11475. Client client("localhost", get_port());
  11476. sse::SSEClient sse(client, "/custom-events");
  11477. std::atomic<bool> update_received{false};
  11478. std::atomic<bool> delete_received{false};
  11479. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11480. if (msg.data == "updated") { update_received.store(true); }
  11481. });
  11482. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11483. if (msg.data == "deleted") { delete_received.store(true); }
  11484. });
  11485. sse.set_max_reconnect_attempts(1);
  11486. sse.start_async();
  11487. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11488. sse.stop();
  11489. EXPECT_TRUE(update_received.load());
  11490. EXPECT_TRUE(delete_received.load());
  11491. }
  11492. // Test: on_error callback on connection failure
  11493. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11494. // Connect to a non-existent port
  11495. Client client("localhost", 59999);
  11496. sse::SSEClient sse(client, "/events");
  11497. std::atomic<bool> error_called{false};
  11498. Error received_error = Error::Success;
  11499. sse.on_error([&](Error err) {
  11500. error_called.store(true);
  11501. received_error = err;
  11502. });
  11503. sse.set_reconnect_interval(50);
  11504. sse.set_max_reconnect_attempts(1);
  11505. sse.start_async();
  11506. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11507. sse.stop();
  11508. EXPECT_TRUE(error_called.load());
  11509. EXPECT_NE(received_error, Error::Success);
  11510. }
  11511. // Test: Last-Event-ID header sent on reconnect
  11512. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11513. // Endpoint that sends event with ID
  11514. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11515. res.set_chunked_content_provider(
  11516. "text/event-stream", [](size_t offset, DataSink &sink) {
  11517. if (offset == 0) {
  11518. std::string event = "id: evt-123\ndata: test\n\n";
  11519. sink.write(event.data(), event.size());
  11520. }
  11521. return false;
  11522. });
  11523. });
  11524. Client client("localhost", get_port());
  11525. sse::SSEClient sse(client, "/event-with-id");
  11526. std::atomic<bool> id_received{false};
  11527. sse.on_message([&](const sse::SSEMessage &msg) {
  11528. if (!msg.id.empty()) { id_received.store(true); }
  11529. });
  11530. sse.set_reconnect_interval(100);
  11531. sse.set_max_reconnect_attempts(1);
  11532. sse.start_async();
  11533. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11534. sse.stop();
  11535. EXPECT_TRUE(id_received.load());
  11536. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11537. }
  11538. // Test: Manual stop
  11539. TEST_F(SSEIntegrationTest, ManualStop) {
  11540. // Endpoint that sends one event and stays open briefly
  11541. std::atomic<bool> handler_running{true};
  11542. server_->Get("/stay-open", [&handler_running](const Request &,
  11543. Response &res) {
  11544. res.set_chunked_content_provider(
  11545. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11546. if (offset == 0) {
  11547. std::string event = "data: connected\n\n";
  11548. sink.write(event.data(), event.size());
  11549. }
  11550. // Keep connection open while handler_running is true
  11551. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11552. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11553. }
  11554. return false;
  11555. });
  11556. });
  11557. Client client("localhost", get_port());
  11558. sse::SSEClient sse(client, "/stay-open");
  11559. std::atomic<bool> connected{false};
  11560. sse.on_open([&connected]() { connected.store(true); });
  11561. sse.set_reconnect_interval(100);
  11562. sse.set_max_reconnect_attempts(1);
  11563. sse.start_async();
  11564. // Wait for connection to establish
  11565. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11566. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11567. }
  11568. EXPECT_TRUE(connected.load());
  11569. EXPECT_TRUE(sse.is_connected());
  11570. // Signal handler to stop
  11571. handler_running.store(false);
  11572. // Stop SSE client
  11573. sse.stop();
  11574. EXPECT_FALSE(sse.is_connected());
  11575. }
  11576. // Test: SSEClient with custom headers
  11577. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11578. // Setup a server endpoint that checks for custom header
  11579. std::atomic<bool> header_received{false};
  11580. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11581. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11582. header_received.store(true);
  11583. }
  11584. res.set_chunked_content_provider("text/event-stream",
  11585. [](size_t, DataSink &) { return false; });
  11586. });
  11587. Client client("localhost", get_port());
  11588. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11589. sse::SSEClient sse(client, "/header-check", headers);
  11590. sse.set_max_reconnect_attempts(1);
  11591. sse.start_async();
  11592. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11593. sse.stop();
  11594. EXPECT_TRUE(header_received.load());
  11595. }
  11596. // Test: Reconnect interval configuration
  11597. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11598. Client client("localhost", get_port());
  11599. sse::SSEClient sse(client, "/events");
  11600. auto &result = sse.set_reconnect_interval(500);
  11601. // Builder pattern should return reference to self
  11602. EXPECT_EQ(&result, &sse);
  11603. }
  11604. // Test: Max reconnect attempts
  11605. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11606. // Connect to non-existent port to force reconnects
  11607. Client client("localhost", 59998);
  11608. sse::SSEClient sse(client, "/events");
  11609. std::atomic<int> error_count{0};
  11610. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11611. sse.set_reconnect_interval(50);
  11612. sse.set_max_reconnect_attempts(2);
  11613. auto start = std::chrono::steady_clock::now();
  11614. sse.start(); // Blocking call
  11615. auto end = std::chrono::steady_clock::now();
  11616. // Should have stopped after 2 failed attempts
  11617. EXPECT_GE(error_count.load(), 2);
  11618. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11619. auto duration =
  11620. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11621. #ifdef _WIN32
  11622. // Windows is much slower for socket connection failures
  11623. EXPECT_LT(duration.count(), 7000);
  11624. #else
  11625. EXPECT_LT(duration.count(), 1000);
  11626. #endif
  11627. }
  11628. // Test: Multi-line data in integration
  11629. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11630. // Endpoint with multi-line data
  11631. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11632. res.set_chunked_content_provider(
  11633. "text/event-stream", [](size_t offset, DataSink &sink) {
  11634. if (offset == 0) {
  11635. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11636. sink.write(event.data(), event.size());
  11637. }
  11638. return false;
  11639. });
  11640. });
  11641. Client client("localhost", get_port());
  11642. sse::SSEClient sse(client, "/multiline-data");
  11643. std::string received_data;
  11644. std::mutex data_mutex;
  11645. sse.on_message([&](const sse::SSEMessage &msg) {
  11646. std::lock_guard<std::mutex> lock(data_mutex);
  11647. received_data = msg.data;
  11648. });
  11649. sse.set_reconnect_interval(100);
  11650. sse.set_max_reconnect_attempts(1);
  11651. sse.start_async();
  11652. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11653. sse.stop();
  11654. std::lock_guard<std::mutex> lock(data_mutex);
  11655. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11656. }
  11657. // Test: Auto-reconnect after server disconnection
  11658. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11659. std::atomic<int> connection_count{0};
  11660. std::atomic<int> message_count{0};
  11661. // Endpoint that sends one event and closes, forcing reconnect
  11662. server_->Get("/reconnect-test",
  11663. [&connection_count](const Request &, Response &res) {
  11664. connection_count.fetch_add(1);
  11665. res.set_chunked_content_provider(
  11666. "text/event-stream", [](size_t offset, DataSink &sink) {
  11667. if (offset == 0) {
  11668. std::string event = "data: hello\n\n";
  11669. sink.write(event.data(), event.size());
  11670. }
  11671. return false; // Close connection after sending
  11672. });
  11673. });
  11674. Client client("localhost", get_port());
  11675. sse::SSEClient sse(client, "/reconnect-test");
  11676. sse.on_message([&message_count](const sse::SSEMessage &) {
  11677. message_count.fetch_add(1);
  11678. });
  11679. sse.set_reconnect_interval(100);
  11680. sse.set_max_reconnect_attempts(3);
  11681. sse.start_async();
  11682. // Wait long enough for multiple reconnects
  11683. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11684. sse.stop();
  11685. // Should have connected multiple times (initial + reconnects)
  11686. EXPECT_GE(connection_count.load(), 2);
  11687. // Should have received messages from multiple connections
  11688. EXPECT_GE(message_count.load(), 2);
  11689. }
  11690. // Test: Last-Event-ID sent on reconnect
  11691. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11692. std::atomic<int> connection_count{0};
  11693. std::vector<std::string> received_last_event_ids;
  11694. std::mutex id_mutex;
  11695. // Endpoint that checks Last-Event-ID header and sends event with ID
  11696. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11697. int conn = connection_count.fetch_add(1);
  11698. // Capture the Last-Event-ID header from each connection
  11699. {
  11700. std::lock_guard<std::mutex> lock(id_mutex);
  11701. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11702. }
  11703. res.set_chunked_content_provider(
  11704. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11705. if (offset == 0) {
  11706. std::string event =
  11707. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11708. sink.write(event.data(), event.size());
  11709. }
  11710. return false;
  11711. });
  11712. });
  11713. Client client("localhost", get_port());
  11714. sse::SSEClient sse(client, "/reconnect-with-id");
  11715. sse.set_reconnect_interval(100);
  11716. sse.set_max_reconnect_attempts(3);
  11717. sse.start_async();
  11718. // Wait for at least 2 connections
  11719. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11720. sse.stop();
  11721. // Verify behavior
  11722. std::lock_guard<std::mutex> lock(id_mutex);
  11723. EXPECT_GE(received_last_event_ids.size(), 2u);
  11724. // First connection should have no Last-Event-ID
  11725. if (!received_last_event_ids.empty()) {
  11726. EXPECT_EQ(received_last_event_ids[0], "");
  11727. }
  11728. // Second connection should have Last-Event-ID from first connection
  11729. if (received_last_event_ids.size() >= 2) {
  11730. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11731. }
  11732. }